LocalMusic.ets 758 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205
  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 { resolvePlayerDismissMorphTarget } from '../common/util/PlayerDismissHelper';
  119. import { isBaiduStreamingPlaybackUrl, resolveSeekGuardDecision } from '../common/util/PlaybackSeekGuard';
  120. import {
  121. cloneVideoItem,
  122. preloadNextSongIfNeeded,
  123. setVideoUrlForSong,
  124. getTypeOrder,
  125. isWebDavType,
  126. isSmbType,
  127. isNavidromeType,
  128. isFtpType,
  129. isBaiduType,
  130. isJellyfinType,
  131. isEmbyType,
  132. isAudioStationType,
  133. isPlexType,
  134. isRemoteCloudType,
  135. mergeCoverWithPriority,
  136. WorkerEditMusicResult,
  137. WebDavMetadataUpdatePayload,
  138. isDaoLiYuType
  139. } from '../common/util/RemotePlayerUtil';
  140. import { PlaylistPlayRequest, consumePendingPlaylistPlay, clearPendingPlaylistPlay } from '../common/util/PlaylistPlayRequestStore';
  141. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  142. import app from '@system.app';
  143. import { TextNodeController } from './PipLyricTextBuilder';
  144. import { IndexerView } from './IndexerView';
  145. import { KeyCode } from '@kit.InputKit';
  146. import { KnockController } from '../controller/KnockController';
  147. import { DeleteComptent } from '../view/DeleteComptent';
  148. import { ABLoopComptent } from '../view/ABLoopComptent';
  149. import { FixMessyView } from '../view/FixMessyView';
  150. import {
  151. parseCueFile,
  152. CueTrack,
  153. CueInfo,
  154. getCueTrackDuration,
  155. getCueTrackEndOffset,
  156. getCueTrackStartOffset,
  157. importCueTracks,
  158. isCueSplitItem
  159. } from '../common/util/CueUtils';
  160. import { CueComptent } from '../view/CueComptent';
  161. import { SearchHistoryUtil } from '../common/util/SearchHistoryUtil';
  162. import { IsoExtractComptent } from '../view/IsoExtractComptent';
  163. import PlaylistTable from '../common/util/PlaylistTable';
  164. import { showAddToPlaylistDialog } from '../dialog/AddToPlaylistDialog';
  165. import { showCreatePlaylistDialog } from '../dialog/PlaylistDialog';
  166. import { convertPlaylistSongsToVideoItems, emptyView,updateAllSongsSortOrder } from '../pages/PlaylistDetailPage';
  167. import { Playlist, PlaylistSong } from '../viewmodel/Playlist';
  168. import { Song } from '../viewmodel/Song';
  169. import { WebDavAccount } from '../viewmodel/WebDavAccount';
  170. import { SongType } from '../common/enums/SongType';
  171. import { RemoteDriveManager, WebDavAuthInfo as WebDavManagerAuthInfo,
  172. buildHttpHeadersWithWebDav,
  173. WebDavAuthItem} from '../common/util/RemoteDriveManager';
  174. import PermissionUtil from '../common/util/PermissionUtil'
  175. import { EditAudio, setRingTone } from './EditAudio';
  176. import { ExtractAccompaniment } from './ExtractAccompaniment';
  177. import { ExtractAudioFromVideo } from './ExtractAudioFromVideo';
  178. import { AudioFormatConverter } from './AudioFormatConverter';
  179. import { MergeAudio } from './MergeAudio';
  180. import { AIVoiceSeparation } from './AIVoiceSeparation';
  181. import { WebDavUrlUtil } from '../common/util/WebDavUrlUtil';
  182. import { ChangeTone } from './ChangeTone';
  183. import {
  184. hdsEffect,
  185. HdsVisualComponent,
  186. HdsSceneController,
  187. HdsSceneType,
  188. HdsVisualComponentAttribute,
  189. } from '@kit.UIDesignKit';
  190. import { GlobalAlphabetIndexerModifier } from '../Styels/GlobalStyles'
  191. import { getFirstLetter } from '../Constants';
  192. import { audio } from '@kit.AudioKit';
  193. import { PointLightDefaultButton } from './PointLight/PointLightDeFaultButton';
  194. import { CoverThumbCache } from '../common/util/CoverThumbCache';
  195. import { LyricCopySheet } from './LyricCopySheet';
  196. import {
  197. IsoArchiveAudioEntry,
  198. IsoExtractFailureDetail,
  199. IsoExtractProgressMessage,
  200. IsoExtractTaskResult,
  201. listIsoAudioEntriesTask,
  202. extractIsoAudioEntriesTask
  203. } from '../common/util/IsoArchiveUtil';
  204. const TAG = 'LocalMusic';
  205. const HICAR_LOG_TAG = 'HiCarWindow';
  206. const PREF_PLAY_COVER_SCALE_GUIDE_SHOWN = 'play_cover_scale_guide_show';
  207. function logHiCarWindow(message: string): void {
  208. void ServerLogUtil.info(HICAR_LOG_TAG, message);
  209. }
  210. export interface WorkerMetadataPayload {
  211. originFilePath: string;
  212. originId?: string;
  213. bit_rate?: string;
  214. duration?: string;
  215. sampleRate?: string;
  216. mimeType?: string;
  217. md5Str?: string;
  218. videoSize?: number;
  219. size?: string;
  220. pixelMapPath?: string;
  221. artist?: string;
  222. album?: string;
  223. name?: string;
  224. lyricContent?: string;
  225. bits_per_raw_sample?: string;
  226. channels?: string;
  227. channel_layout?: string;
  228. start_time?: string;
  229. genre?: string;
  230. year?: string;
  231. probe_score?: number;
  232. track?: string;
  233. disc?: string;
  234. ALBUMARTIST?: string;
  235. COMPOSER?: string;
  236. COMMENT?: string;
  237. LYRICIST?: string;
  238. nb_streams?: number;
  239. nb_programs?: number;
  240. error?: string;
  241. }
  242. interface WorkerMessageScanDone {
  243. code: 101;
  244. data: Record<string, never>;
  245. }
  246. interface WorkerMessageMediaList {
  247. code: 102;
  248. data: Array<VideoItem>;
  249. totalCount: number;
  250. }
  251. interface WorkerMessageArtistList {
  252. code: 103;
  253. data1: Map<string, Array<VideoItem>>;
  254. data2: Array<VideoItem>;
  255. totalCount: number;
  256. }
  257. interface WorkerMessageAlbumList {
  258. code: 104;
  259. data1: Map<string, Array<VideoItem>>;
  260. data2: Array<VideoItem>;
  261. totalCount: number;
  262. }
  263. interface WorkerMessageMetadata {
  264. code: 105;
  265. data: WorkerMetadataPayload;
  266. }
  267. interface WorkerMessageEditResult {
  268. code: 106;
  269. data: WorkerEditMusicResult;
  270. }
  271. interface AlphaTaskItem {
  272. type: number;
  273. name?: string;
  274. pyStr?: string;
  275. fileName?: string;
  276. artist?: string;
  277. album?: string;
  278. }
  279. type LocalMusicWorkerMessage =
  280. WorkerMessageScanDone
  281. | WorkerMessageMediaList
  282. | WorkerMessageArtistList
  283. | WorkerMessageAlbumList
  284. | WorkerMessageMetadata
  285. | WorkerMessageEditResult;
  286. const DEFAULT_INDEX =
  287. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  288. 'X', 'Y', 'Z']
  289. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  290. // 元数据提取状态追踪
  291. const metadataExtractionInFlight: Map<string, Promise<void>> = new Map();
  292. // setVideoUrlForSong 函数已移至 MusicPlayerUtil.ets
  293. // 定义接口
  294. interface HiCarAspectRatio {
  295. ratio: number;
  296. name: string;
  297. }
  298. interface GeneratedObjectLiteralInterface_1 {
  299. assetId: string;
  300. title: string;
  301. artist: string;
  302. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  303. mediaUri: string;
  304. // 该字段大写,音频'AUDIO',视频'VIDEO'
  305. mediaType: string;
  306. mediaSize: number;
  307. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  308. startPosition: number;
  309. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  310. duration: number;
  311. albumCoverUri: string;
  312. albumTitle: string;
  313. appName: string;
  314. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  315. drmScheme: string;
  316. }
  317. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  318. const ITEM_HEIGHT: number = 65; // 列表项中高度
  319. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  320. /**
  321. * 排序模式枚举
  322. * 定义各种排序方式的升序基准值
  323. */
  324. export enum SortMode {
  325. ByArtist = 0, // 按艺术家升序
  326. ByAlbum = 2, // 按专辑升序
  327. ByName = 4, // 按名称升序
  328. ByTime = 6, // 按时间升序
  329. ByAddTime = 7, // 按添加时间(只有降序)
  330. ByCount = 8, // 按数量升序
  331. ByDiscTrack = 10 // 按碟片编号-音轨号升序
  332. }
  333. //功能强大的音乐播放器
  334. @Preview
  335. @Component
  336. export struct LocalMusic {
  337. @State default_layout:number = 0
  338. @State isGeKongPlayNext: boolean = true//是否开启隔空手势播放下一首
  339. @State bluetoothDisconnectPause: boolean = false // 蓝牙设备断开暂停
  340. @State isBluetoothConnected: boolean = false // 蓝牙连接状态
  341. @State bluetoothLyricEnabled: boolean = false // 蓝牙歌词开关
  342. @State bluetoothLyricMode: number = 0 // 蓝牙歌词显示模式
  343. private lastBluetoothLyricLine: string = '' // 上一次发送的歌词行
  344. private audioRoutingManager?: audio.AudioRoutingManager
  345. private outputDeviceChangeCallback?: Callback<audio.DeviceChangeAction>
  346. private audioInterruptResumePending: boolean = false
  347. @State showFindLocation: boolean = true
  348. @StorageProp("EnablePointLight") enablePointLight: boolean = true
  349. @State showSimple: boolean = true//开启沉浸模式
  350. @State isPaging: boolean = true;//是否分页加载机制
  351. @State isCoverRectangle: boolean = true;
  352. @State showZMIndex: boolean = false //是否右侧显示字母索引
  353. private prevOffsetY: number = 0; // 记录上一次的Y轴偏移量
  354. @State autoHideTitle: boolean = true //滚动自动隐藏标题栏
  355. // 字母表
  356. @State alphaBet: string[] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
  357. 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  358. @State alphaBetStyle: GlobalAlphabetIndexerModifier = new GlobalAlphabetIndexerModifier()
  359. @State selectAlphaBetIndex: number = 0
  360. @State isShowAlphaBet: boolean = false
  361. @State isScrolling: boolean = false
  362. @State isTouchingAlphaBet: boolean = false
  363. @State alphabetHeight: number = 0
  364. public enableShowAlphabet: boolean = true // 是否显示字母表
  365. private alphaBetHideTimer: number = 0
  366. private alphaBetRebuildTimer: number = 0
  367. private alphaBetDirty: boolean = false
  368. private alphaBetCacheKey: string = ''
  369. private alphaBetBuildVersion: number = 0
  370. @State isShowPrecious: boolean = false //播控条显示上一首按钮
  371. //背景两侧流光控制器
  372. @State sceneBgController: HdsSceneController|undefined = deviceInfo.sdkApiVersion>=20
  373. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  374. new HdsSceneController()
  375. .setSceneParams({
  376. backgroundMaskColors: [Color.Green, Color.Red],
  377. firstEdgeFlowLight: {
  378. startPos: 0,
  379. endPos: 0.5,
  380. color: Color.Red
  381. },
  382. secondEdgeFlowLight: {
  383. startPos: 0,
  384. endPos: -0.5,
  385. color: Color.Green
  386. }
  387. }) : undefined;
  388. //背景流光控制器
  389. @State bgController: hdsEffect.ShaderEffectController|undefined = deviceInfo.sdkApiVersion>=20
  390. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  391. new hdsEffect.ShaderEffectController():undefined;
  392. @State showAddSheet:boolean = false
  393. private loadingDialogId: string = ''
  394. private loadingProgressDialogId: string = ''
  395. @State isoAudioEntries: IsoArchiveAudioEntry[] = []
  396. @State selectedIsoAudioPaths: string[] = []
  397. @State isoSourceFileName: string = ''
  398. @State isIsoExtracting: boolean = false
  399. @State isoExtractProgress: number = 0
  400. @State isoExtractProgressText: string = ''
  401. @State isoExtractCurrentEntryName: string = ''
  402. private isoSourceFilePath: string = ''
  403. private isoExtractDestinationDir: string = ''
  404. private isoComponentId: number = 0
  405. private isoExtractProgressTimer: number = 0
  406. private isoExtractExpectedOutputPaths: Array<string> = []
  407. private isoExtractTotalBytes: number = 0
  408. private isoExtractDisplayedProgress: number = 0
  409. private isoExtractReceivedTaskProgress: boolean = false
  410. private isoExtractTask: taskpool.Task | undefined = undefined
  411. private isoExtractLastActivityTime: number = 0
  412. private readonly isoExtractStallTimeoutMs: number = 15000
  413. private isoExtractCanceled: boolean = false
  414. private isoExtractCancelMessage: string = ''
  415. searchController: SearchController = new SearchController()
  416. @State rightTopImage:Resource = $r('sys.symbol.sort')
  417. @State isEditAudio:boolean = false
  418. @State isExtractAcc:boolean = false
  419. @State isConverter:boolean = false
  420. @State isAIVoiceSeparation:boolean = false
  421. @State isExtractAudio:boolean = false
  422. @State isMergeAudio:boolean = false
  423. @State isCopyFileToDownLoad: boolean = false
  424. @State isChangeTone:boolean = false
  425. @State offHeight: number = 75
  426. @State currentSongList: Array<VideoItem> = []//当前歌单
  427. @Consume currentSongListName:string //当前歌单名称
  428. @Consume @Watch('onIDChange') currentSongListID:string //当前歌单ID
  429. @State currentPlaylistSongFilePaths: string[] = [] //当前歌单的歌曲路径列表(用于随机播放)
  430. @State isRefreshing: boolean = false;
  431. @State maxRefreshingHeight: number = 100.0;
  432. @State isPlayerLoading: boolean = false; // 播放器加载状态
  433. private contentNode?: ComponentContent<Object> = undefined;
  434. // WebDAV相关实例变量(现在改为从内存读取,不再需要存储)
  435. @State ratioL: number = 1;
  436. @State mediaKuCount: number = 0;
  437. @State albumCount: number = 0;
  438. @State artistCount: number = 0;
  439. @State fastForwardSeconds: string = '10'
  440. @State isShowBackFast: boolean = true//快进快退按钮
  441. @State isCanAuto:boolean = true
  442. @State opacityValueImage: number = 1;
  443. @State tipPopup:boolean = false
  444. @State preloadNextSong: boolean = PreferencesUtil.getBooleanSync('preload_next_song', true) // 是否提前缓存下一首
  445. @Consume mType: number;
  446. @StorageProp('themeColor') themeColor: string =
  447. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  448. themeMode: number = 0;
  449. @State titleName: string = '文件夹'//首页就是文件夹
  450. @State textStr: string = ''
  451. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  452. // private download_path: string = '';
  453. @Consume rootPath: string //音频根目录
  454. @Consume currentPath: string
  455. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  456. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  457. @State lockPath: string = ''
  458. @State favPath: string = ''
  459. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  460. @State historyPath: string = ''
  461. @State historyList: Array<VideoItem> = []
  462. @Consume isHistory: boolean
  463. static readonly HISTORY_MUSIC: string = 'music_historyList';
  464. private table: MediaTable = new MediaTable(getContext(this))
  465. private playlistTable: PlaylistTable | null = null
  466. private deletionWatcher: FileDeletionWatcher | null = null
  467. @State allPlaylists: Playlist[] = []
  468. @State isZero: boolean = false
  469. @State fileList: Array<string> = []
  470. @State dirList: Array<VideoItem> = []
  471. @Consume videoLocalList:VideoItem[]
  472. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  473. @State listRefreshKey: number = 0
  474. @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  475. @State artistList: Array<VideoItem> = []; //艺术家文件
  476. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  477. @State artistSongCountMap: Map<string, number> = new Map();
  478. @State albumList: Array<VideoItem> = []; //专辑文件
  479. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  480. @State albumSongCountMap: Map<string, number> = new Map();
  481. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  482. @State imageOpacities: number[] = [];
  483. @Consume isCanBack: boolean
  484. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  485. @State showSingleLyric: boolean = false
  486. @State sortType: number = 4 //默认排序方式
  487. @State isShowSimi: boolean = false //是否显示私密音频
  488. @State isShowFAV: boolean = true //是否显示我的收藏
  489. @State isShowTitleBar: boolean = true //是否显示分类导航条
  490. @State isShowAllBar: boolean = true //是否显示播放全部条
  491. @State isShowSingleLineLyric: boolean = false //是否显示单行歌词
  492. @State isEnableWordByWordLyric: boolean = true //是否开启逐字歌词
  493. @State isShowHistory: boolean = true //是否显示最近播放
  494. @State @Watch('onColorModeChange') isCustomizeBg: boolean = false //自定义背景界面
  495. @State isHomeBgFollowMusicCover: boolean = true //主页背景随当前播放封面
  496. @State isGridMusic: boolean = false //是否网格布局
  497. @State isCircleBtn: boolean = false //是否圆形播放按钮
  498. @State twoFingerType: number = 3 //双支放大缩小的类型
  499. @State isScrollHide: boolean = false //是否滚动隐藏
  500. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  501. @State isStartAutoPlay: boolean = false //启动后自动播放
  502. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  503. @State isShowHeader: boolean = true
  504. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  505. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  506. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  507. @State rectangleCoverScale: number = 1
  508. @State rectangleCoverPinchValue: number = 1
  509. @State isSwipe: boolean = false //listItem的左滑开关
  510. @State openSkipSongAnimate: boolean = true//切歌动画效果
  511. @State isPlayPageSwipeNext: boolean = true // 播放页上滑切歌
  512. @State isLightText: boolean = true //是否开启歌词发光
  513. @State customizeBgPath: string | undefined = '';
  514. @StorageProp('customizeMusicBgPath') customizeMusicBgPath: string = '';
  515. @State isDarkMode: boolean = false
  516. @State lyricTextWeight: number = 400
  517. @State lyricTextWeightPip: number = 400
  518. @State currentSwiperIndex: number = 0
  519. @State blurValue: number = 0 //背景模糊
  520. @State bgBrightness: number = 0 //背景亮度
  521. private listScroller: ListScroller = new ListScroller()
  522. private playListScroller: Scroller = new Scroller()
  523. @State isOneKeyTags:boolean = false
  524. @State isFixMessy:boolean = false
  525. // 分页相关状态
  526. @State private currentPage: number = 0 // 当前页码
  527. @State private pageSize: number = 53 // 每页数量
  528. @State private totalCount: number = 0 // 总记录数
  529. @State private hasMoreData: boolean = true // 是否还有更多数据
  530. @State private isLoadingPage: boolean = false // 是否正在加载分页数据
  531. private pageCache: Map<number, VideoItem[]> = new Map() // 页面缓存(最多保留3页)
  532. private pageHasMoreCache: Map<number, boolean> = new Map()
  533. private pageTotalCountCache: Map<number, number> = new Map()
  534. private prefetchingPages: Set<number> = new Set()
  535. private preloadStartRatio: number = 0.18
  536. private appendStartRatio: number = 0.30
  537. private earlyAppendReserveCount: number = 28
  538. private lastScrollTriggerPage: number = -1
  539. private lastVisibleEndIndex: number = -1
  540. private isPagingTransition: boolean = false
  541. private pagingScheduleTimer: number = 0
  542. private listScrollAlphaCheckAt: number = 0
  543. private listScrollPagingCheckAt: number = 0
  544. private listScrollLastAlphaStart: number = -1
  545. private listScrollLastPagingEnd: number = -1
  546. private gridScrollPagingCheckAt: number = 0
  547. private gridScrollLastPagingEnd: number = -1
  548. private waterScrollPagingCheckAt: number = 0
  549. private waterScrollLastPagingEnd: number = -1
  550. private gridWaterScrollIdleTimer: number = 0
  551. private gridWaterLastActiveTs: number = 0
  552. private listUpdateTimer: number = 0
  553. private listUpdateVersion: number = 0
  554. private detailBackTransitioning: boolean = false
  555. private mediaLibraryEnterTs: number = 0
  556. private mediaLibraryWarmupPrefetchTimer: number = 0
  557. private listVisibleStart: number = -1
  558. private listVisibleEnd: number = -1
  559. private listThumbWarmupCheckAt: number = 0
  560. private listThumbWarmupStart: number = -1
  561. private listThumbWarmupEnd: number = -1
  562. private gridThumbWarmupCheckAt: number = 0
  563. private gridThumbWarmupStart: number = -1
  564. private gridThumbWarmupEnd: number = -1
  565. private waterThumbWarmupCheckAt: number = 0
  566. private waterThumbWarmupStart: number = -1
  567. private waterThumbWarmupEnd: number = -1
  568. private gridVisibleStart: number = -1
  569. private gridVisibleEnd: number = -1
  570. private waterVisibleStart: number = -1
  571. private waterVisibleEnd: number = -1
  572. private titleBarToggleMinDelta: number = 12
  573. private titleBarLastCheckTs: number = 0
  574. @State private coverThumbVersion: number = 0
  575. private coverThumbCache: CoverThumbCache = new CoverThumbCache(1, 960)
  576. private coverThumbCacheReady: boolean = false
  577. private pendingCoverThumbRefresh: boolean = false
  578. private playQueueScope: 'view' | 'history' | 'fav' | 'playlist' | 'single' = 'view'
  579. private isHydratingPlayList: boolean = false
  580. @StorageProp('isLandscape') @Watch('onIsLandscapeChange') isLandscape: boolean = false;
  581. @StorageProp('topSafeHeight') topSafeHeight: number = 0;
  582. @StorageProp('bottomSafeHeight') bottomSafeHeight: number = 0;
  583. @StorageProp('windowWidth') windowWidth: number = 0;
  584. @StorageProp('windowHeight') windowHeight: number = 0;
  585. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  586. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  587. private UNKONWN:string = '';
  588. private listArea: Area = {
  589. width: 0,
  590. height: 0,
  591. position: {},
  592. globalPosition: {}
  593. }
  594. @State private pointLightOptions: hdsEffect.PointLightOptions | undefined = undefined
  595. @State private activePointLightItemKey: string = ''
  596. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  597. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  598. // WebDAV认证信息缓存(作为实例变量,比全局上下文更可靠)
  599. private currentWebDavAuthInfo: WebDavAuthItem | null = null;
  600. // 当前实际播放中的记忆key,避免切歌时 currentSong 已切换导致串写
  601. private activePlaybackMemoryKey: string = '';
  602. // 网盘流地址记忆恢复token,切歌后用于取消旧的延迟seek任务
  603. private remoteRestoreSeekToken: number = 0;
  604. // 本次是否需要先seek到记忆点再开始播放
  605. private waitInitialSeekBeforeStart: boolean = false;
  606. // 本次播放记忆点(毫秒)
  607. private pendingMemorySeekPosition: number = 0;
  608. // 记忆播放seek兜底,避免一直转圈
  609. private initialSeekGuardTimer: number = 0;
  610. private readonly initialSeekGuardTimeoutMs: number = 2000;
  611. private readonly remoteMemorySeekInitialDelayMs: number = 120;
  612. private readonly remoteMemorySeekRetryIntervalMs: number = 80;
  613. private readonly remoteMemorySeekMaxRetryCount: number = 6;
  614. private lastSeekRequestMs: number = -1;
  615. private lastSeekSource: string = '';
  616. private seekTraceUntilTs: number = 0;
  617. private lastSeekTraceLogTs: number = 0;
  618. private readonly seekTraceLogWindowMs: number = 4000;
  619. private readonly seekTraceLogIntervalMs: number = 400;
  620. //瀑布流的列数横竖屏动态切换
  621. onIsLandscapeChange() {
  622. if(this.isLandscape){
  623. this.columns = 4
  624. }else{
  625. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  626. }
  627. }
  628. onColorModeChange() {
  629. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  630. }
  631. //点击某个歌单id发生变化的时候回调
  632. onIDChange(){
  633. console.log('onecold 歌单id发生变化this.currentSongListID='+this.currentSongListID)
  634. console.log('onecold 歌单id发生变化this.currentSongListName='+this.currentSongListName)
  635. if(this.modeType==4){
  636. this.titleName = this.currentSongListName
  637. this.rightTopImage = $r('sys.symbol.sort')
  638. //获取缓存
  639. const cacheSongs:string =PreferencesUtil.getStringSync(this.currentSongListID+'currentSongList', '')
  640. console.log('onecold 歌单id发生变化获取缓存2 cacheSongs = '+cacheSongs)
  641. if(StrUtil.isNotEmpty(cacheSongs)){
  642. this.currentSongList = JSON.parse(cacheSongs) as VideoItem[]
  643. this.updateListData(this.currentSongList, true)
  644. }
  645. this.doSongListTask()//获取歌单信息
  646. }
  647. }
  648. async doSongListTask() {
  649. // 初始化歌单数据库
  650. const playlistTable = new PlaylistTable(this.context);
  651. // 查询歌单中的所有歌曲
  652. const playlistSongs: PlaylistSong[] = await playlistTable.queryPlaylistSongs(this.currentSongListID);
  653. console.log('onecold 歌单id发生变化获取缓存7 playlistSongs='+playlistSongs.length)
  654. if (ArrayUtil.isEmpty(playlistSongs)) {
  655. this.updateListData([], true)
  656. // 清空歌单路径列表
  657. this.currentPlaylistSongFilePaths = [];
  658. } else {
  659. this.currentSongList = await convertPlaylistSongsToVideoItems(this.context, playlistSongs);
  660. console.log('onecold 从数据库读取的歌曲为 playlistSongs='+this.currentSongList.length)
  661. this.updateListData(this.currentSongList, true)
  662. // 保存歌单的歌曲路径列表,用于随机播放
  663. this.currentPlaylistSongFilePaths = playlistSongs.map(song => song.songFilePath);
  664. Logger.info('heanup doSongListTask', `保存歌单歌曲路径列表,歌单ID=${this.currentSongListID}, 数量=${this.currentPlaylistSongFilePaths.length}`);
  665. if (ArrayUtil.isNotEmpty(this.currentSongList)&&this.currentSongList.length > 100) {
  666. // 只保存前100条记录到缓存中
  667. let canceList = this.currentSongList.slice(0, 100);
  668. PreferencesUtil.putSync(this.currentSongListID+'currentSongList',
  669. JSON.stringify(canceList))
  670. } else {
  671. PreferencesUtil.putSync(this.currentSongListID+'currentSongList', JSON.stringify(this.currentSongList));
  672. }
  673. }
  674. this.isRefreshing = false
  675. }
  676. async onModeChange(preserveList: boolean = false): Promise<void> {
  677. this.isFavMusic = false
  678. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  679. this.refreshDirVisibilitySettings()
  680. if (this.mediaLibraryWarmupPrefetchTimer) {
  681. clearTimeout(this.mediaLibraryWarmupPrefetchTimer)
  682. this.mediaLibraryWarmupPrefetchTimer = 0
  683. }
  684. Logger.info('heanup LocalMusic', `onModeChange: 切换模式 modeType=${this.modeType}`);
  685. switch (this.modeType) {
  686. case 0:
  687. // 首页模式已在 resetAndLoadFirstPage 中处理
  688. // 切换模式时加载对应的排序类型
  689. this.titleName = Utility.resourceToString(this.context,$r('app.string.home'))
  690. this.sortType = this.loadSortTypeForCurrentMode()
  691. this.mediaLibraryEnterTs = 0
  692. break
  693. case 1:
  694. this.rightTopImage = $r('sys.symbol.sort')
  695. this.titleName = Utility.resourceToString(this.context,$r('app.string.media_ku'))
  696. // 切换模式时加载对应的排序类型
  697. this.sortType = this.loadSortTypeForCurrentMode()
  698. this.mediaLibraryEnterTs = Date.now()
  699. break
  700. case 2:
  701. this.rightTopImage = $r('sys.symbol.sort')
  702. this.titleName = Utility.resourceToString(this.context,$r('app.string.artist'))
  703. // 切换到艺术家模式时,加载艺术家模式的排序类型(默认按数量降序)
  704. this.sortType = this.loadSortTypeForCurrentMode()
  705. this.mediaLibraryEnterTs = 0
  706. break
  707. case 3:
  708. this.rightTopImage = $r('sys.symbol.sort')
  709. this.titleName = Utility.resourceToString(this.context,$r('app.string.album'))
  710. // 切换到专辑模式时,加载专辑模式的排序类型(默认按数量降序)
  711. this.sortType = this.loadSortTypeForCurrentMode()
  712. this.mediaLibraryEnterTs = 0
  713. break
  714. }
  715. // 模式切换时重置分页状态并加载第一页
  716. await this.resetAndLoadFirstPage(!preserveList);
  717. Logger.info('heanup onModeChange', `doSortType: 切换排序方式 sortType=${this.sortType}, mode=${this.modeType}`);
  718. }
  719. // @Consume currentSong: VideoItem | undefined;
  720. @StorageLink('currentSong') @Watch('onHomeBgCurrentSongChange') currentSong: VideoItem | undefined = undefined;
  721. // @StorageLink('isPlay') isPlay: boolean = false;
  722. @Consume isShowPlay: boolean ;
  723. @State isShowCoverScaleGuide: boolean = false
  724. @StorageLink('songList') songList: Array<VideoItem> = [];
  725. @State translateY: number = 0;
  726. @State playDismissScale: number = 1;
  727. @State playDismissScaleY: number = 1;
  728. @State playDismissOpacity: number = 1;
  729. @State playDismissTranslateX: number = 0;
  730. @State playDismissBorderRadius: number = 0;
  731. @State playDismissProxySize: number = 0;
  732. @State playDismissProxyOpacity: number = 0;
  733. @State isShowSheet: boolean = false;
  734. @State isShowSheetView: boolean = false;
  735. @State isShowLyricCopySheet: boolean = false;
  736. @State lyricCopyLines: string[] = [];
  737. @State lyricSelectedIndexes: number[] = [];
  738. @State isShowTimeCloseView: boolean = false;
  739. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  740. private playDismissTimer: number = -1;
  741. private readonly playDismissContentDuration: number = 260;
  742. private readonly playDismissDotDuration: number = 160;
  743. private playOpenFromMiniBarPending: boolean = false;
  744. private playOpenTimer: number = -1;
  745. private readonly playOpenDotDuration: number = 120;
  746. private readonly playOpenExpandDuration: number = 320;
  747. @StorageLink('currIndex') curIndex: number = 0;
  748. @Consume isShowDrawer: boolean;
  749. @Consume offsetX: number;
  750. @State isFac: boolean = false;
  751. @State favList: Array<VideoItem> = []
  752. @Consume isFavMusic: boolean
  753. @State isClickedPLayAll: boolean = false;
  754. private scrollerForlist: ListScroller = new ListScroller();
  755. private knockController: KnockController | undefined = undefined;
  756. @StorageProp('animationState') animationState: AnimationStatus = AnimationStatus.Initial
  757. // 缓存机制
  758. private cache: Map<string, Array<VideoItem>> = new Map();
  759. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  760. // 持久化缓存
  761. private async saveCacheToStorage() {
  762. const cacheArray = Array.from(this.cache.entries());
  763. const stringCacheArray = Array.from(this.stringCache.entries());
  764. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  765. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  766. }
  767. // 载入缓存
  768. private async loadCacheFromStorage() {
  769. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  770. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  771. if (cacheString) {
  772. const parsedCache: Object | null = JSON.parse(cacheString);
  773. if (parsedCache && Array.isArray(parsedCache)) {
  774. const cacheArray: [string, Array<VideoItem>][] = parsedCache;
  775. this.cache = new Map(cacheArray);
  776. }
  777. }
  778. if (stringCacheString) {
  779. const parsedStringCache: Object | null = JSON.parse(stringCacheString);
  780. if (parsedStringCache && Array.isArray(parsedStringCache)) {
  781. const stringCacheArray: [string, string][] = parsedStringCache;
  782. this.stringCache = new Map(stringCacheArray);
  783. }
  784. }
  785. }
  786. // 查找缓存
  787. private findCache(key: string): Array<VideoItem> | undefined {
  788. return this.cache.get(key);
  789. }
  790. // 查找字符串缓存
  791. private findStringCache(key: string): string | undefined {
  792. return this.stringCache.get(key);
  793. }
  794. // 添加缓存
  795. private addCache(key: string, value: Array<VideoItem>) {
  796. this.cache.set(key, value);
  797. }
  798. // 添加字符串缓存
  799. private addStringCache(key: string, value: string) {
  800. this.stringCache.set(key, value);
  801. }
  802. // 删除缓存
  803. private deleteCache(key: string) {
  804. this.cache.delete(key);
  805. this.saveCacheToStorage()
  806. }
  807. // 删除字符串缓存
  808. private deleteStringCache(key: string) {
  809. this.stringCache.delete(key);
  810. }
  811. // 多选机制
  812. @State selectedFiles: Array<VideoItem> = [];
  813. @Consume isMultiSelect: boolean;
  814. @State isAllSelected: boolean = false;
  815. @State appName: string = ''
  816. @State isHasDir: boolean = false
  817. @State packName: string = ''
  818. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  819. doSwipBack() {
  820. if(this.isSearchMode){
  821. console.info('onecold doSwipBack = ' +this.isSearchMode)
  822. this.isSearchMode = false
  823. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  824. this.searchText = ''
  825. this.getSortedFiles(this.currentPath)
  826. return
  827. }
  828. this.onSearchInput('')
  829. return
  830. }
  831. this.isZero = false
  832. if (this.modeType !== 0 && this.isCanBack) {
  833. if (this.detailBackTransitioning) {
  834. return
  835. }
  836. this.detailBackTransitioning = true
  837. // 先设置 isCanBack=false,确保 onModeChange 读取的是列表页的排序设置
  838. this.isCanBack = false
  839. this.rightTopImage = $r('sys.symbol.sort')
  840. if (this.modeType == 2) {
  841. this.titleName = Utility.resourceToString(this.context,$r('app.string.artist'))
  842. if (ArrayUtil.isNotEmpty(this.artistList)) {
  843. this.updateListData(this.artistList, true, true)
  844. }
  845. } else if (this.modeType == 3) {
  846. this.titleName = Utility.resourceToString(this.context,$r('app.string.album'))
  847. if (ArrayUtil.isNotEmpty(this.albumList)) {
  848. this.updateListData(this.albumList, true, true)
  849. }
  850. }
  851. // 返回列表页时保留当前列表,避免先清空导致闪现
  852. void this.onModeChange(true).then(() => {
  853. if (this.modeType == 2) {
  854. if (this.isGridMusic||this.twoFingerType==4) {
  855. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  856. let lastWaterOffset = this.mScrollMap.get('lastWaterArtistScrollOffset') ?? 0
  857. if(this.twoFingerType==4){
  858. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  859. }else{
  860. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  861. }
  862. } else {
  863. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  864. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  865. }
  866. } else if (this.modeType == 3) {
  867. if (this.isGridMusic||this.twoFingerType==4) {
  868. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  869. let lastWaterOffset = this.mScrollMap.get('lastWaterAlBumScrollOffset') ?? 0
  870. if(this.twoFingerType==4){
  871. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  872. }else{
  873. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  874. }
  875. } else {
  876. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  877. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  878. }
  879. }
  880. this.detailBackTransitioning = false
  881. }).catch((error: Error) => {
  882. Logger.error('heanup LocalMusic', `doSwipBack onModeChange error: ${error.message}`)
  883. this.detailBackTransitioning = false
  884. })
  885. return
  886. }
  887. this.mediaLibraryEnterTs = 0
  888. if (this.isHistory || this.isFavMusic) {
  889. this.isHistory = false
  890. this.getSortedFiles(this.currentPath)
  891. return
  892. }
  893. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  894. animateTo({ duration: 555 }, () => {
  895. // 动画闭包内控制Image组件的出现和消失
  896. this.isShowDrawer = !this.isShowDrawer
  897. this.offsetX = 0
  898. })
  899. return
  900. }
  901. //返回上一级歌单的滚动位置
  902. setTimeout(() => {
  903. if (this.modeType == 0) {
  904. if (this.isGridMusic||this.twoFingerType==4) {
  905. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  906. let lastWaterOffset = this.mScrollMap.get('lastWaterDirScrollOffset') ?? 0
  907. if(this.twoFingerType==4){
  908. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  909. }else{
  910. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  911. }
  912. } else {
  913. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  914. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  915. }
  916. }
  917. }, 100)
  918. this.currentPath = Utility.getParentDirectory(this.currentPath)
  919. Logger.info('this.currentPath2 = ' + this.currentPath)
  920. this.getSortedFiles(this.currentPath, false, undefined, undefined, undefined, true)
  921. }
  922. private triggerSwipeBackWithAnimation(): void {
  923. animateTo({ duration: 555 }, () => {
  924. this.doSwipBack()
  925. })
  926. }
  927. // 组件生命周期
  928. aboutToAppear() {
  929. console.info('onecold aboutToAppear sdkApiVersion = '+deviceInfo.sdkApiVersion)
  930. if(ArrayUtil.isNotEmpty(this.videoLocalList)&&this.modeType==0){
  931. this.updateListData(this.videoLocalList)
  932. }
  933. // 初始化 PlaylistTable
  934. this.playlistTable = new PlaylistTable(getContext(this))
  935. this.sonTwoFingerType = PreferencesUtil.getNumberSync('sonTwoFingerType', 3);
  936. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  937. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  938. this.tipPopup = !this.tipPopup
  939. PreferencesUtil.putSync('isFirstTiped',false)
  940. }
  941. this.loadSearchHistory()
  942. this.initSetting()
  943. this.syncEqualizerUi();
  944. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  945. Utility.getAppName(getContext(this)).then((appName: string) => {
  946. this.appName = appName
  947. })
  948. this.packName = AppUtil.getBundleName()
  949. this.tabSelectedIndexes[0] = this.modeType//SegmentButton的索引
  950. this.loadCacheFromStorage(); // 加载文件夹缓存
  951. // 在首页初始化时读取媒体库,艺术家,专辑等缓存数据
  952. this.initLoadCache()
  953. this.mkDownLoadDir()
  954. let eventMusic: emitter.InnerEvent = { eventId: EventConstants.EVENT_AUDIO_OPEN }
  955. // 监听广播事件(打开其他应用处理)
  956. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  957. this.saveVideoDatas([eventData.data?.message], true)
  958. });
  959. //侧滑广播接收时间
  960. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_UPDATE }
  961. // 监听广播事件(手势返回处理)
  962. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  963. this.triggerSwipeBackWithAnimation()
  964. });
  965. //ScanFilePage广播接收时间
  966. let eventScanUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_SCAN_UPDATE }
  967. // 监听ScanFilePage广播事件(更新数据库)
  968. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  969. this.doUpdateData()
  970. });
  971. let eventEqualizerChanged: emitter.InnerEvent = { eventId: EventConstants.EVENT_EQUALIZER_CHANGED }
  972. emitter.on(eventEqualizerChanged, () => {
  973. this.syncEqualizerUi();
  974. if (this.mIjkMediaPlayer) {
  975. const equalizerManager = EqualizerManager.getInstance();
  976. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  977. this.markEqualizerApplied();
  978. }
  979. });
  980. // 监听歌单播放请求事件
  981. let eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY }
  982. emitter.on(eventPlaylistPlay, async (eventData: emitter.EventData) => {
  983. const data = eventData.data as Record<string, Object>
  984. if (!data) {
  985. Logger.error('heanup eventPlaylistPlay: eventData.data is undefined or null')
  986. return
  987. }
  988. // 检查歌单播放数据结构
  989. if (data.playlistId && data.songFilePaths && data.startIndex !== undefined) {
  990. const playlistData = new PlaylistPlayRequest(
  991. data.playlistId as string,
  992. data.playlistName as string,
  993. data.songCount as number,
  994. data.startIndex as number,
  995. data.songFilePaths as string[],
  996. data.isJump as boolean,
  997. data.playType as number
  998. )
  999. await this.dispatchPlaylistPlayRequest(playlistData)
  1000. return
  1001. }
  1002. Logger.error('heanup eventPlaylistPlay: 接收到无效的数据结构')
  1003. });
  1004. Promise.resolve().then(async (): Promise<void> => {
  1005. const pendingPlaylistRequest = consumePendingPlaylistPlay();
  1006. if (!pendingPlaylistRequest) {
  1007. return;
  1008. }
  1009. Logger.info(TAG,
  1010. `检测到待处理播放请求,准备补偿执行: ${pendingPlaylistRequest.playlistName}, startIndex=${pendingPlaylistRequest.startIndex}`);
  1011. await this.dispatchPlaylistPlayRequest(pendingPlaylistRequest);
  1012. });
  1013. let eventRefreshSort: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_REFRESH_SORT }
  1014. // 监听广播事件(通用设置配置更新)
  1015. emitter.on(eventRefreshSort, (eventData: emitter.EventData) => {
  1016. if(this.modeType ==4){
  1017. this.doSongListTask()//获取歌单信息
  1018. }
  1019. });
  1020. let eventQueueRefresh: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAY_QUEUE_REFRESH }
  1021. emitter.on(eventQueueRefresh, () => {
  1022. this.syncWebdavQueueWithoutRestart();
  1023. });
  1024. let eventOpenLocalSpecialList: emitter.InnerEvent = { eventId: EventConstants.EVENT_OPEN_LOCAL_SPECIAL_LIST }
  1025. emitter.on(eventOpenLocalSpecialList, (eventData: emitter.EventData) => {
  1026. const data = eventData.data as Record<string, Object>
  1027. const target = data?.target as string
  1028. this.openSpecialLocalList(target)
  1029. });
  1030. let eventSetting: emitter.InnerEvent = { eventId: EventConstants.EVENT_SETTING_UPDATE }
  1031. // 监听广播事件(通用设置配置更新)
  1032. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  1033. this.initSetting()
  1034. });
  1035. // 监听 WebDAV 元数据更新事件
  1036. let eventWebDavMetadata: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED }
  1037. emitter.on(eventWebDavMetadata, (eventData: emitter.EventData) => {
  1038. const payloads = eventData?.data as WebDavMetadataUpdatePayload[] | undefined;
  1039. if (!payloads || payloads.length === 0) {
  1040. Logger.info(TAG, 'LocalMusic: WebDav metadata event received but payload empty');
  1041. return;
  1042. }
  1043. Logger.info(TAG, `LocalMusic: WebDav metadata event payload count: ${payloads.length}`);
  1044. // 处理每个元数据更新
  1045. for (let i = 0; i < payloads.length; i++) {
  1046. const payload = payloads[i];
  1047. if (!payload || !payload.filePath) {
  1048. continue;
  1049. }
  1050. // 重要:只更新当前正在播放的歌曲
  1051. // 如果 filePath 不匹配,说明是其他歌曲的元数据更新,忽略不做处理
  1052. if (this.currentSong && this.currentSong.filePath === payload.filePath) {
  1053. Logger.info(TAG, `LocalMusic: 更新当前播放歌曲的元数据: ${payload.filePath}`);
  1054. if (payload.name && payload.name.length > 0) {
  1055. this.name = payload.name;
  1056. if (this.currentSong) {
  1057. this.currentSong.name = payload.name;
  1058. }
  1059. }
  1060. if (payload.artist && payload.artist.length > 0) {
  1061. this.artist = payload.artist;
  1062. if (this.currentSong) {
  1063. this.currentSong.artist = payload.artist;
  1064. }
  1065. }
  1066. if (this.currentSong) {
  1067. const coverMutated = mergeCoverWithPriority(this.currentSong, payload.pixelMapPath,
  1068. payload.isCustomCover ?? 0);
  1069. if (coverMutated && this.currentSong.pixelMapPath) {
  1070. this.cover = this.currentSong.pixelMapPath;
  1071. Logger.info(TAG, `LocalMusic: 封面已更新: ${this.currentSong.pixelMapPath}`);
  1072. }
  1073. if (payload.md5Str && payload.md5Str.length > 0) {
  1074. this.currentSong.md5Str = payload.md5Str;
  1075. }
  1076. }
  1077. // 同步更新 AppStorage
  1078. AppStorage.setOrCreate('currentSong', this.currentSong);
  1079. } else {
  1080. Logger.info(TAG, `LocalMusic: 跳过非当前播放歌曲的元数据更新: ${payload.filePath}, 当前: ${this.currentSong?.filePath}`);
  1081. }
  1082. }
  1083. });
  1084. // 监听广播事件(通用设置配置更新)
  1085. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  1086. this.doChangeSetting()
  1087. });
  1088. this.mIjkMediaPlayer.on('audioInterrupt', (event: InterruptEvent) => {
  1089. this.handleAudioInterrupt(event)
  1090. });
  1091. this.mIjkMediaPlayer.on('deviceChange', (event: InterruptEvent) => {
  1092. this.handlePlayerDeviceChange(event)
  1093. });
  1094. const eventPause: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAY_PAUSE }
  1095. // 监听广播事件(hicar断开暂停播放)
  1096. emitter.on(eventPause, (eventData: emitter.EventData) => {
  1097. console.info('heanup onecold hicar断开暂停播放, 暂停播放')
  1098. this.audioInterruptResumePending = false
  1099. this.pause();
  1100. });
  1101. let audioManager = audio.getAudioManager(); // 需要先创建AudioManager实例。
  1102. this.audioRoutingManager = audioManager.getRoutingManager(); // 再调用AudioManager的方法创建AudioRoutingManager实例。
  1103. this.outputDeviceChangeCallback = (deviceChanged: audio.DeviceChangeAction) => {
  1104. this.handleOutputDeviceChange(deviceChanged)
  1105. }
  1106. this.audioRoutingManager.on('deviceChange', audio.DeviceFlag.OUTPUT_DEVICES_FLAG, this.outputDeviceChangeCallback);
  1107. this.makeWorker()
  1108. //折叠屏的屏幕显示模式变化
  1109. display.on('foldDisplayModeChange', (data) => {
  1110. this.doChangeBarHeight()
  1111. });
  1112. display.on('foldStatusChange', (data) => {
  1113. Logger.info('onecold foldStatusChange ')
  1114. });
  1115. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  1116. this.rectangleCoverScale = PreferencesUtil.getNumberSync(SettingPage.RECTANGLE_COVER_SCALE, 1)
  1117. if (this.rectangleCoverScale < 0.7 || this.rectangleCoverScale > 1.4) {
  1118. this.rectangleCoverScale = 1
  1119. }
  1120. // 读取 themeMode 并同步 currentColorMode
  1121. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  1122. this.applyThemeMode(this.themeMode)
  1123. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  1124. AppStorage.setOrCreate('themeColor', themeColor);
  1125. this.themeColor = themeColor;
  1126. this.doChangeSetting()
  1127. this.windowClass.on('windowSizeChange', (size: window.Size) => {
  1128. LogUtil.info('onecold windowSizeChange')
  1129. this.doChangeBarHeight()
  1130. let viewWidth = px2vp(size.width);
  1131. let viewHeight = px2vp(size.height);
  1132. if(this.isPhoneLan()){
  1133. this.is_auto_hide_progress = false
  1134. if(this.isHiCar()){
  1135. return
  1136. }
  1137. setTimeout(() => {
  1138. this.is_auto_hide_progress = true
  1139. }, 6000)
  1140. }else{
  1141. this.startAutoHide()
  1142. }
  1143. });
  1144. this.eventHub.on('onStateChange', (fg: boolean) => {
  1145. this.isAppForeground = fg;
  1146. if (fg && this.curState === 'STARTED') {
  1147. this.stopPip();
  1148. this.syncLyricPositionNow();
  1149. }
  1150. });
  1151. //NewIndex的博空调收到eventHub消息控制播放
  1152. this.getUIContext().getHostContext()!.eventHub.on('playOrPause', () => {
  1153. if (ArrayUtil.isNotEmpty(this.songList)) {
  1154. this.playOrPause();
  1155. } else {
  1156. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1157. }
  1158. });
  1159. this.getUIContext().getHostContext()!.eventHub.on('playPrevious', () => {
  1160. if (ArrayUtil.isNotEmpty(this.songList)) {
  1161. this.playPrevious();
  1162. } else {
  1163. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1164. }
  1165. });
  1166. this.getUIContext().getHostContext()!.eventHub.on('playNext', () => {
  1167. if (ArrayUtil.isNotEmpty(this.songList)) {
  1168. this.playNext();
  1169. } else {
  1170. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1171. }
  1172. });
  1173. this.getUIContext().getHostContext()!.eventHub.on('showPlayerView', () => {
  1174. if (!this.isShowPlay) {
  1175. this.setShowPlayTrue()
  1176. }
  1177. this.showPlayerView();
  1178. });
  1179. this.getUIContext().getHostContext()!.eventHub.on('openPlayerViewFromMiniBar', () => {
  1180. if (ArrayUtil.isEmpty(this.songList)) {
  1181. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  1182. return
  1183. }
  1184. this.setShowPlayTrue(true)
  1185. this.showPlayerView();
  1186. });
  1187. this.getUIContext().getHostContext()!.eventHub.on('dismissPlayerView', () => {
  1188. this.setShowPlayFalse()
  1189. });
  1190. this.getUIContext().getHostContext()!.eventHub.on('openPlayList', () => {
  1191. this.openPlayList();
  1192. });
  1193. }
  1194. //载入媒体库,艺术家,专辑等缓存
  1195. initLoadCache(){
  1196. this.mediaKuCount = PreferencesUtil.getNumberSync('mediaKuCount', 0)
  1197. this.artistCount = PreferencesUtil.getNumberSync('artistCount', 0)
  1198. this.albumCount = PreferencesUtil.getNumberSync('albumCount', 0)
  1199. let cachedListStr:string = PreferencesUtil.getStringSync('mediaKuList', '[]');
  1200. let cachedList = JSON.parse(cachedListStr) as Array<VideoItem>;
  1201. if(ArrayUtil.isNotEmpty(cachedList)){
  1202. this.mediaKuList = cachedList
  1203. if(this.modeType==1){
  1204. this.updateListData(this.mediaKuList)
  1205. }
  1206. }
  1207. let artistListStr:string = PreferencesUtil.getStringSync('artistList', '[]');
  1208. let artistCachedList = JSON.parse(artistListStr) as Array<VideoItem>;
  1209. if(ArrayUtil.isNotEmpty(artistCachedList)){
  1210. this.artistList = artistCachedList
  1211. let artistMapStr:string = PreferencesUtil.getStringSync('artistMap', '[]');
  1212. const parsedArray = JSON.parse(artistMapStr) as [string, VideoItem[]][];
  1213. this.artistMap = new Map(parsedArray);
  1214. // this.artistMap = JSON.parse(artistMapStr) as Map<string, VideoItem[]>;
  1215. if(this.modeType==2){
  1216. this.updateListData(this.artistList)
  1217. }
  1218. }
  1219. let albumListStr:string = PreferencesUtil.getStringSync('albumList', '[]');
  1220. let albumCachedList = JSON.parse(albumListStr) as Array<VideoItem>;
  1221. if(ArrayUtil.isNotEmpty(albumCachedList)){
  1222. this.albumList = albumCachedList
  1223. let albumMapStr:string = PreferencesUtil.getStringSync('albumMap', '[]');
  1224. const parsedArray = JSON.parse(albumMapStr) as [string, VideoItem[]][];
  1225. this.albumMap = new Map(parsedArray);
  1226. if(this.modeType==3){
  1227. this.updateListData(this.albumList)
  1228. }
  1229. }
  1230. }
  1231. startAutoHide() {
  1232. if(this.isHiCar()){
  1233. return
  1234. }
  1235. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  1236. console.info('onecold startAutoHide')
  1237. this.is_auto_hide_progress = false
  1238. setTimeout(() => {
  1239. this.is_auto_hide_progress = true
  1240. }, 6000)
  1241. }
  1242. }
  1243. applyThemeMode(mode: number) {
  1244. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  1245. if (mode === 1) {
  1246. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  1247. } else if (mode === 2) {
  1248. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1249. }
  1250. AppStorage.setOrCreate('currentColorMode', colorMode)
  1251. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  1252. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  1253. AppStorage.setOrCreate('themeMode', mode)
  1254. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1255. // 只有强制浅色/深色时才主动设置
  1256. const context = getContext(this) as common.UIAbilityContext
  1257. context.getApplicationContext().setColorMode(colorMode)
  1258. }
  1259. private isAudioPlaybackActive(): boolean {
  1260. return this.CONTROL_PlayStatus === PlayStatus.PLAY
  1261. || this.mIjkMediaPlayer.isPlaying()
  1262. || (!!this.castControllerWrapper && this.isCastPlaying)
  1263. }
  1264. private isBluetoothOutputDeviceType(deviceType: audio.DeviceType): boolean {
  1265. return deviceType === audio.DeviceType.BLUETOOTH_A2DP || deviceType === audio.DeviceType.BLUETOOTH_SCO
  1266. }
  1267. private isWiredOutputDeviceType(deviceType: audio.DeviceType): boolean {
  1268. return deviceType === audio.DeviceType.WIRED_HEADSET
  1269. || deviceType === audio.DeviceType.WIRED_HEADPHONES
  1270. || deviceType === audio.DeviceType.USB_HEADSET
  1271. }
  1272. private handleAudioInterrupt(event: InterruptEvent): void {
  1273. console.info(`heanup onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`)
  1274. if (this.isSameTimePlay) {
  1275. Logger.info(TAG, `音频中断已忽略,当前为混音模式: ${JSON.stringify(event)}`)
  1276. return
  1277. }
  1278. const wasPlayingBeforeInterrupt = this.isAudioPlaybackActive()
  1279. switch (event.hintType) {
  1280. case InterruptHintType.INTERRUPT_HINT_PAUSE:
  1281. this.audioInterruptResumePending = wasPlayingBeforeInterrupt
  1282. if (wasPlayingBeforeInterrupt) {
  1283. this.pause(false)
  1284. }
  1285. break
  1286. case InterruptHintType.INTERRUPT_HINT_RESUME:
  1287. if (this.audioInterruptResumePending && this.CONTROL_PlayStatus === PlayStatus.PAUSE) {
  1288. console.info(`heanup onecold audioInterrupt startPlayOrResumePlay: ${JSON.stringify(event)}`)
  1289. this.audioInterruptResumePending = false
  1290. this.resumePlaybackAfterAudioInterrupt()
  1291. }
  1292. break
  1293. case InterruptHintType.INTERRUPT_HINT_STOP:
  1294. Logger.info(TAG, `收到音频中断 STOP,改为暂停等待用户手动恢复: ${JSON.stringify(event)}`)
  1295. this.audioInterruptResumePending = false
  1296. if (wasPlayingBeforeInterrupt) {
  1297. this.pause(false)
  1298. }
  1299. break
  1300. default:
  1301. Logger.info(TAG, `忽略未处理的音频中断类型: ${JSON.stringify(event)}`)
  1302. break
  1303. }
  1304. }
  1305. private resumePlaybackAfterAudioInterrupt(): void {
  1306. if (this.castControllerWrapper && this.isCastPlaying) {
  1307. this.castControllerWrapper.setPlaying().then(() => {
  1308. this.CONTROL_PlayStatus = PlayStatus.PLAY
  1309. this.setIsPlaying(true)
  1310. this.updateSessionPlayState(true)
  1311. this.playChange()
  1312. }).catch((error: BusinessError | Error) => {
  1313. Logger.error(TAG, `音频中断后恢复投播失败: ${error}`)
  1314. })
  1315. return
  1316. }
  1317. this.startPlayOrResumePlay()
  1318. }
  1319. private handlePlayerDeviceChange(event: InterruptEvent): void {
  1320. console.info(`onecold Heanup deviceChange event: ${JSON.stringify(event)}`);
  1321. if (event.reason === DeviceChangeReason.REASON_NEW_DEVICE_AVAILABLE) {
  1322. Logger.info(TAG, 'ijk deviceChange 检测到新设备接入,交由 AudioRoutingManager 处理')
  1323. } else if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) {
  1324. Logger.info(TAG, 'ijk deviceChange 检测到旧设备移除,等待 AudioRoutingManager 精确判断是否暂停')
  1325. }
  1326. }
  1327. private handleOutputDeviceChange(deviceChanged: audio.DeviceChangeAction): void {
  1328. const descriptors = deviceChanged?.deviceDescriptors ?? []
  1329. if (descriptors.length <= 0) {
  1330. Logger.warn(TAG, `音频输出设备变化缺少描述信息: ${JSON.stringify(deviceChanged)}`)
  1331. return
  1332. }
  1333. Logger.info(TAG, `音频输出设备变化: type=${deviceChanged.type}, count=${descriptors.length}`)
  1334. const outputDescriptors = descriptors.filter((descriptor) => descriptor.deviceRole === audio.DeviceRole.OUTPUT_DEVICE)
  1335. if (outputDescriptors.length <= 0) {
  1336. Logger.info(TAG, `忽略非输出设备变化: ${JSON.stringify(deviceChanged)}`)
  1337. return
  1338. }
  1339. const hasBluetoothOutput = outputDescriptors.some((descriptor) =>
  1340. this.isBluetoothOutputDeviceType(descriptor.deviceType))
  1341. const hasWiredOutput = outputDescriptors.some((descriptor) =>
  1342. this.isWiredOutputDeviceType(descriptor.deviceType))
  1343. if (deviceChanged.type === audio.DeviceChangeType.CONNECT) {
  1344. if (hasBluetoothOutput) {
  1345. this.isBluetoothConnected = true
  1346. console.info('onecold 蓝牙设备已连接')
  1347. }
  1348. return
  1349. }
  1350. if (deviceChanged.type !== audio.DeviceChangeType.DISCONNECT) {
  1351. return
  1352. }
  1353. if (hasBluetoothOutput) {
  1354. this.isBluetoothConnected = false
  1355. this.lastBluetoothLyricLine = ''
  1356. console.info('onecold 蓝牙设备已断开')
  1357. if (this.currentSong) {
  1358. this.avSessionController.restoreOriginalMetadata(
  1359. this.currentSong.name || '',
  1360. this.currentSong.artist || ''
  1361. )
  1362. }
  1363. if (this.bluetoothDisconnectPause && this.isAudioPlaybackActive()) {
  1364. this.audioInterruptResumePending = false
  1365. console.info('heanup onecold 蓝牙音响断开, 暂停播放')
  1366. this.pause()
  1367. }
  1368. return
  1369. }
  1370. if (hasWiredOutput && this.isAudioPlaybackActive()) {
  1371. this.audioInterruptResumePending = false
  1372. console.info('heanup onecold 有线/USB耳机断开, 暂停播放')
  1373. this.pause()
  1374. }
  1375. }
  1376. initSetting() {
  1377. this.default_layout = PreferencesUtil.getNumberSync('default_layout', 0)
  1378. this.isGeKongPlayNext = PreferencesUtil.getBooleanSync('isGeKongPlayNext', false)
  1379. this.bluetoothDisconnectPause = PreferencesUtil.getBooleanSync(SettingPage.BLUETOOTH_DISCONNECT_PAUSE, false)
  1380. this.bluetoothLyricEnabled = PreferencesUtil.getBooleanSync(SettingPage.BLUETOOTH_LYRIC_ENABLED, false)
  1381. this.bluetoothLyricMode = PreferencesUtil.getNumberSync(SettingPage.BLUETOOTH_LYRIC_MODE, 0)
  1382. this.isShowSpectrum = PreferencesUtil.getBooleanSync('isShowSpectrum', true)
  1383. this.spectrumModeIndex = PreferencesUtil.getNumberSync('spectrumModeIndex', 0)
  1384. this.enablePointLight = PreferencesUtil.getBooleanSync('enablePointLight', true)
  1385. AppStorage.setOrCreate('EnablePointLight', this.enablePointLight);
  1386. this.showSimple = PreferencesUtil.getBooleanSync('showSimple', true)
  1387. this.showFindLocation = PreferencesUtil.getBooleanSync('showFindLocation', true)
  1388. this.showZMIndex = PreferencesUtil.getBooleanSync('showZMIndex', false)
  1389. this.autoHideTitle = PreferencesUtil.getBooleanSync('autoHideTitle', true)
  1390. this.isShowPrecious = PreferencesUtil.getBooleanSync('isShowPrecious', false)
  1391. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1392. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  1393. this.isHomeBgFollowMusicCover = PreferencesUtil.getBooleanSync(SettingPage.IS_HOME_BG_FOLLOW_MUSIC_COVER, true)
  1394. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  1395. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, true)
  1396. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  1397. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  1398. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  1399. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  1400. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  1401. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  1402. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  1403. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  1404. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  1405. this.syncCustomizeMusicBgPath()
  1406. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 3)
  1407. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  1408. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, false)
  1409. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  1410. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  1411. this.isEnableWordByWordLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_ENABLE_WORD_BY_WORD_LYRIC, true)
  1412. this.isLightText = PreferencesUtil.getBooleanSync(SettingPage.IS_LIGHT_TEXT, true)
  1413. this.syncWordByWordLyricMode()
  1414. this.syncLyricLightTextMode()
  1415. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  1416. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  1417. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  1418. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  1419. const volumeBoostPercent = PreferencesUtil.getNumberSync(this.volumeBoostPreferenceKey, 0)
  1420. this.volumeBoostPercent = Math.max(0, Math.min(volumeBoostPercent, this.volumeBoostMaxPercent))
  1421. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  1422. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  1423. this.isPlayPageSwipeNext = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYPAGE_SWIPE_NEXT, true)
  1424. this.volumeSmall = PreferencesUtil.getBooleanSync('volumeSmall', false)
  1425. this.autoParseMusicName = PreferencesUtil.getBooleanSync('autoParseMusicName', true)
  1426. this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
  1427. this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
  1428. this.refreshDirVisibilitySettings()
  1429. this.fastForwardSeconds = PreferencesUtil.getStringSync('fastForwardSeconds', '10')
  1430. this.isShowBackFast = PreferencesUtil.getBooleanSync('isShowBackFast', false)
  1431. this.isCopyFileToDownLoad = PreferencesUtil.getBooleanSync(SettingPage.IS_COPYFILE_TO_DOWNLOAD, false)
  1432. let audioManager = audio.getAudioManager();
  1433. let audioSessionManager: audio.AudioSessionManager = audioManager.getSessionManager();
  1434. if(this.isSameTimePlay){
  1435. //与其他应用同时播放,关键代码
  1436. let strategy: audio.AudioSessionStrategy = {
  1437. concurrencyMode: audio.AudioConcurrencyMode.CONCURRENCY_MIX_WITH_OTHERS
  1438. };
  1439. audioSessionManager.activateAudioSession(strategy).then(() => {
  1440. console.info('onecold Succeeded in doing activateAudioSession.');
  1441. }).catch((err: BusinessError) => {
  1442. console.error(`Failed to activateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1443. });
  1444. }else{
  1445. let isActivated = audioSessionManager.isAudioSessionActivated();
  1446. if(isActivated){
  1447. audioSessionManager.deactivateAudioSession().then(() => {
  1448. console.info('Succeeded in doing deactivateAudioSession.');
  1449. }).catch((err: BusinessError) => {
  1450. console.error(`Failed to deactivateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1451. });
  1452. }
  1453. }
  1454. //如果是hicar连接状态,这些都是false
  1455. if(this.isHiCar()){
  1456. this.autoHideTitle = false
  1457. this.isCoverRectangle= true
  1458. this.columns=4
  1459. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  1460. {
  1461. this.isGridMusic= false//用list不用网格
  1462. this.isCoverTopBig = false
  1463. }
  1464. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  1465. }
  1466. if (this.isSavePlayMode) {
  1467. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  1468. }
  1469. }
  1470. private onHomeBgCurrentSongChange(): void {
  1471. this.syncCustomizeMusicBgPath()
  1472. }
  1473. private syncCustomizeMusicBgPath(): void {
  1474. if (!this.isHomeBgFollowMusicCover) {
  1475. return
  1476. }
  1477. const coverPath: string = this.currentSong?.pixelMapPath ?? ''
  1478. AppStorage.setOrCreate('customizeMusicBgPath', coverPath)
  1479. }
  1480. private isMusicCoverHomeBackgroundActive(): boolean {
  1481. return this.isHomeBgFollowMusicCover && this.customizeMusicBgPath.length > 0
  1482. }
  1483. doChangeSetting() {
  1484. this.initSetting()
  1485. this.deleteCache(this.currentPath)
  1486. if (this.modeType === 0) {
  1487. this.getSortedFiles(this.currentPath)
  1488. }
  1489. }
  1490. doChangeBarHeight() {
  1491. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  1492. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  1493. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  1494. this.setBarHeightNormal()
  1495. }
  1496. }
  1497. onPageShow() {
  1498. this.knockController?.immersiveListening();
  1499. app.setImageCacheCount(100);
  1500. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  1501. app.setImageRawDataCacheSize(104857600);
  1502. this.refreshDirVisibilitySettings();
  1503. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  1504. }
  1505. //开启线程查看各个数据库
  1506. makeWorker() {
  1507. setTimeout(() => {
  1508. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  1509. // ToastUtil.showToast('请到文件扫描页面导入音乐!')
  1510. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  1511. workerInstance.postMessage({
  1512. code: 1,
  1513. data1: this.context,
  1514. data2: this.rootPath,
  1515. data3: this.lockPath,
  1516. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  1517. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  1518. });
  1519. PreferencesUtil.putSync('isFirstApp', false)
  1520. } else {
  1521. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1522. workerInstance.postMessage({ code: 3, data: this.context });
  1523. workerInstance.postMessage({ code: 4, data: this.context });
  1524. this.getHistoryList(false)
  1525. }
  1526. }, 1000)
  1527. workerInstance.onmessage = (e: MessageEvents): void => {
  1528. const message = e.data as LocalMusicWorkerMessage;
  1529. switch (message.code) {
  1530. case 101: //第一次扫描文件夹入库
  1531. ToastUtil.showToast('刷新同步数据库成功!')
  1532. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  1533. this.doAllUpdateData()
  1534. break;
  1535. case 102: //查询媒体库列表
  1536. this.isRefreshing = false
  1537. this.mediaKuList = message.data // 只包含前100条
  1538. const mediaTotalCount: number = message.totalCount ?? this.mediaKuList.length;
  1539. this.mediaKuCount = mediaTotalCount;
  1540. Logger.info(`heanup 查询媒体库列表 缓存数=${this.mediaKuList.length}, 总数=${mediaTotalCount}`)
  1541. Utility.doSortListAscending(this.mediaKuList)
  1542. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  1543. // 媒体库模式下重新加载第一页(分页查询)
  1544. if (this.modeType === 1) {
  1545. this.resetAndLoadFirstPage();
  1546. }
  1547. PreferencesUtil.putSync('mediaKuCount', mediaTotalCount)
  1548. // 只保存前100条记录到缓存中
  1549. PreferencesUtil.putSync('mediaKuList', JSON.stringify(this.mediaKuList));
  1550. break;
  1551. case 103: //收到查询艺术家列表
  1552. this.isRefreshing = false
  1553. this.artistMap = message.data1; // 只包含前60个艺术家的歌曲
  1554. this.artistList = message.data2; // 只包含前100个艺术家
  1555. const artistTotalCount: number = message.totalCount ?? this.artistList.length;
  1556. this.artistCount = artistTotalCount;
  1557. const nextArtistCountMap = new Map(this.artistSongCountMap);
  1558. this.artistMap.forEach((songs, artist) => {
  1559. nextArtistCountMap.set(artist, songs.length);
  1560. });
  1561. this.artistSongCountMap = nextArtistCountMap;
  1562. Logger.info(`heanup 查询艺术家列表 缓存数=${this.artistList.length}, 总数=${artistTotalCount}`)
  1563. PreferencesUtil.putSync('artistCount', artistTotalCount)
  1564. // 艺术家模式下重新加载第一页(分页查询)
  1565. if (this.modeType === 2) {
  1566. this.resetAndLoadFirstPage();
  1567. }
  1568. // 保存前100条艺术家列表
  1569. PreferencesUtil.putSync('artistList', JSON.stringify(this.artistList));
  1570. // 保存前60条艺术家的歌曲Map
  1571. const sortedEntries = Array.from(this.artistMap.entries());
  1572. PreferencesUtil.putSync('artistMap', JSON.stringify(sortedEntries));
  1573. break;
  1574. case 104: //收到查询专辑列表
  1575. this.isRefreshing = false
  1576. this.albumMap = message.data1;
  1577. this.albumList = message.data2
  1578. const albumTotalCount: number = message.totalCount ?? this.albumList.length;
  1579. this.albumCount = albumTotalCount;
  1580. const nextAlbumCountMap = new Map(this.albumSongCountMap);
  1581. this.albumMap.forEach((songs, album) => {
  1582. nextAlbumCountMap.set(album, songs.length);
  1583. });
  1584. this.albumSongCountMap = nextAlbumCountMap;
  1585. Logger.info(`heanup 查询专辑列表 缓存数=${this.albumList.length}, 总数=${albumTotalCount}`)
  1586. // 专辑模式下重新加载第一页(分页查询)
  1587. if (this.modeType === 3) {
  1588. this.resetAndLoadFirstPage();
  1589. }
  1590. //查询完毕在启动是否自动播放
  1591. if (this.isStartAutoPlay&&this.isCanAuto) {
  1592. this.isCanAuto = false
  1593. console.info('onecold startPlayOrResumePlay 757')
  1594. this.startPlayOrResumePlay()
  1595. }
  1596. PreferencesUtil.putSync('albumCount', albumTotalCount)
  1597. // 保存前100条专辑列表(Worker已经只发送了100条)
  1598. PreferencesUtil.putSync('albumList', JSON.stringify(this.albumList));
  1599. // 保存前60条专辑Map(Worker已经只发送了60条)
  1600. const mapArrayAlbum = Array.from(this.albumMap.entries());
  1601. PreferencesUtil.putSync('albumMap', JSON.stringify(mapArrayAlbum));
  1602. break;
  1603. case 105: // 缓存完成后返回的元数据
  1604. this.handleWorkerMetadataPayload(message.data);
  1605. break;
  1606. case 106: // 编辑音乐元数据和封面完成
  1607. this.handleEditMusicResult(message.data);
  1608. break;
  1609. }
  1610. };
  1611. // 在调用terminate后,执行onexit
  1612. workerInstance.onexit = (code) => {
  1613. metadataExtractionInFlight.clear();
  1614. Logger.info(TAG, 'workerInstance 线程已退出,code: ' + code);
  1615. }
  1616. workerInstance.onerror = (err: ErrorEvent) => {
  1617. metadataExtractionInFlight.clear();
  1618. console.error('workerInstance 线程执行发生异常: ' + err.message)
  1619. }
  1620. }
  1621. private handleWorkerMetadataPayload(payload: WorkerMetadataPayload | undefined): void {
  1622. if (!payload || !payload.originFilePath) {
  1623. return;
  1624. }
  1625. metadataExtractionInFlight.delete(payload.originFilePath);
  1626. if (payload.error) {
  1627. Logger.warn(TAG, `缓存文件元数据解析失败: ${payload.error}`);
  1628. return;
  1629. }
  1630. this.applyMetadataToCollections(payload.originFilePath, payload);
  1631. }
  1632. private applyMetadataToCollections(filePath: string, payload: WorkerMetadataPayload): void {
  1633. const targets: Array<VideoItem> = [];
  1634. let mainListUpdated = false;
  1635. let playlistUpdated = false;
  1636. if (this.currentSong && this.currentSong.filePath === filePath) {
  1637. targets.push(this.currentSong);
  1638. }
  1639. const collectFromList = (list?: Array<VideoItem>, markUpdated?: () => void) => {
  1640. if (!list || list.length === 0) {
  1641. return;
  1642. }
  1643. const found = Utility.getItemByFilePath(list, filePath);
  1644. if (found) {
  1645. markUpdated?.();
  1646. targets.push(found);
  1647. }
  1648. };
  1649. collectFromList(this.videoLocalList, () => {
  1650. mainListUpdated = true;
  1651. });
  1652. collectFromList(this.songList, () => {
  1653. playlistUpdated = true;
  1654. });
  1655. collectFromList(this.historyList);
  1656. collectFromList(this.favList);
  1657. const remoteManager = RemoteDriveManager.getInstance();
  1658. collectFromList(remoteManager.webDavSongs);
  1659. const updated = new Set<VideoItem>();
  1660. const remoteMetadataUpdates: Map<string, WebDavMetadataUpdatePayload> = new Map();
  1661. for (let i = 0; i < targets.length; i++) {
  1662. const target = targets[i];
  1663. if (!target || updated.has(target)) {
  1664. continue;
  1665. }
  1666. updated.add(target);
  1667. this.mergeVideoItemWithPayload(target, payload);
  1668. if (isRemoteCloudType(target.type) && StrUtil.isNotEmpty(target.filePath)) {
  1669. remoteMetadataUpdates.set(target.filePath, {
  1670. filePath: target.filePath,
  1671. pixelMapPath: target.pixelMapPath,
  1672. isCustomCover: target.isCustomCover,
  1673. md5Str: target.md5Str,
  1674. name: target.name,
  1675. artist: target.artist
  1676. });
  1677. }
  1678. }
  1679. if (this.currentSong && this.currentSong.filePath === filePath) {
  1680. this.mergeVideoItemWithPayload(this.currentSong, payload);
  1681. if (payload.name) {
  1682. this.name = payload.name;
  1683. }
  1684. if (payload.artist) {
  1685. this.artist = payload.artist;
  1686. }
  1687. if (payload.pixelMapPath && this.currentSong?.pixelMapPath) {
  1688. this.cover = this.currentSong.pixelMapPath;
  1689. }
  1690. if (payload.lyricContent) {
  1691. this.applyInlineLyricContent(payload.lyricContent);
  1692. }
  1693. let avSessionDurationMs: number = this.duration;
  1694. if (payload.duration) {
  1695. const durationSeconds = Number(payload.duration);
  1696. if (!Number.isNaN(durationSeconds) && durationSeconds > 0) {
  1697. avSessionDurationMs = durationSeconds * 1000;
  1698. this.duration = avSessionDurationMs;
  1699. this.durationTime = Math.floor(avSessionDurationMs / 1000);
  1700. this.durationStringTime = secondToTime(this.durationTime);
  1701. }
  1702. }
  1703. if (avSessionDurationMs > 0) {
  1704. this.avSessionController.setAVMetadataMusic(this.currentSong, avSessionDurationMs, this.lyricContent);
  1705. }
  1706. this.currentSong = cloneVideoItem(this.currentSong);
  1707. AppStorage.setOrCreate('currentSong', this.currentSong);
  1708. }
  1709. const primaryTarget = targets.length > 0 ? targets[0] : undefined;
  1710. if (primaryTarget) {
  1711. this.persistRemoteMetadataToDb(primaryTarget).catch((error: Error) => {
  1712. Logger.error(TAG, `缓存元数据持久化失败: ${error.message}`);
  1713. });
  1714. }
  1715. if (remoteMetadataUpdates.size > 0) {
  1716. const eventUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
  1717. emitter.emit(eventUpdate, { data: Array.from(remoteMetadataUpdates.values()) });
  1718. }
  1719. this.refreshLazyListViews(mainListUpdated, playlistUpdated);
  1720. }
  1721. private handleEditMusicResult(result: WorkerEditMusicResult): void {
  1722. // 关闭进度条
  1723. DialogHelper.closeDialog(this.loadingDialogId)
  1724. if (result.success) {
  1725. console.log("heanup 编辑信息成功,数据库已同步");
  1726. if (result.coverResult) {
  1727. ToastUtil.showToast('内嵌封面成功');
  1728. }
  1729. ToastUtil.showToast('内嵌音乐标签成功');
  1730. this.isShowMoreView = false;
  1731. this.name = this.titleStr;
  1732. // 同步当前播放的歌曲信息
  1733. if (this.editingItem && this.currentSong && this.editingItem.filePath == this.currentSong.filePath) {
  1734. this.currentSong.name = this.titleStr;
  1735. this.artist = this.artistStr;
  1736. this.currentSong.artist = this.artistStr;
  1737. this.currentSong.album = this.ablumStr;
  1738. this.currentSong.year = this.yearStr;
  1739. this.currentSong.genre = this.genreStr;
  1740. this.currentSong.track = this.trackStr;
  1741. this.currentSong.lyricContent = this.lyricConStr;
  1742. this.currentSong.ALBUMARTIST = this.albumArtistStr;
  1743. this.currentSong.COMPOSER = this.composerStr;
  1744. this.currentSong.LYRICIST = this.lyricistStr;
  1745. this.currentSong.COMMENT = this.commentStr;
  1746. }
  1747. // if (result.needRefreshList && this.modeType == 0) {
  1748. // this.deleteCache(this.currentPath);
  1749. // this.getSortedFiles(this.currentPath);
  1750. // }
  1751. // 同步编辑字段到本地列表
  1752. if (this.editingItem) {
  1753. this.syncEditedFields(this.editingItem);
  1754. this.syncListsAfterEdit(this.editingItem.filePath);
  1755. this.doUpateEditedFields(this.editingItem);
  1756. }
  1757. // 清理临时变量
  1758. this.longItemFilePath = '';
  1759. this.tempLyricContent = '';
  1760. this.isShowEdit = false;
  1761. this.imagePathStr = '';
  1762. } else {
  1763. console.error("heanup 编辑信息失败: " + result.error);
  1764. ToastUtil.showToast('编辑失败: ' + (result.error || '未知错误'));
  1765. // 清理临时变量
  1766. this.longItemFilePath = '';
  1767. this.tempLyricContent = '';
  1768. this.isShowEdit = false;
  1769. this.imagePathStr = '';
  1770. }
  1771. }
  1772. private assignStringMetadata(target: VideoItem, key: keyof VideoItem, value?: string | null, allowEmpty = false): void {
  1773. if (value === undefined || value === null) {
  1774. return;
  1775. }
  1776. const text = value.toString();
  1777. if (!allowEmpty && text.trim().length === 0) {
  1778. return;
  1779. }
  1780. Reflect.set(target, key as string, value);
  1781. }
  1782. private assignNumberMetadata(target: VideoItem, key: keyof VideoItem, value?: number | null): void {
  1783. if (value === undefined || value === null || Number.isNaN(value)) {
  1784. return;
  1785. }
  1786. Reflect.set(target, key as string, value);
  1787. }
  1788. private mergeVideoItemWithPayload(target: VideoItem, payload: WorkerMetadataPayload): void {
  1789. if (!target || !payload) {
  1790. return;
  1791. }
  1792. this.assignStringMetadata(target, 'name', payload.name);
  1793. this.assignStringMetadata(target, 'artist', payload.artist);
  1794. this.assignStringMetadata(target, 'album', payload.album);
  1795. this.assignStringMetadata(target, 'bit_rate', payload.bit_rate);
  1796. this.assignStringMetadata(target, 'duration', payload.duration);
  1797. this.assignStringMetadata(target, 'sampleRate', payload.sampleRate);
  1798. this.assignStringMetadata(target, 'mimeType', payload.mimeType);
  1799. this.assignStringMetadata(target, 'md5Str', payload.md5Str);
  1800. this.assignStringMetadata(target, 'size', payload.size);
  1801. mergeCoverWithPriority(target, payload.pixelMapPath);
  1802. this.assignStringMetadata(target, 'lyricContent', payload.lyricContent, true);
  1803. this.assignStringMetadata(target, 'genre', payload.genre);
  1804. this.assignStringMetadata(target, 'track', payload.track);
  1805. this.assignStringMetadata(target, 'bits_per_raw_sample', payload.bits_per_raw_sample);
  1806. this.assignStringMetadata(target, 'channels', payload.channels);
  1807. this.assignStringMetadata(target, 'channel_layout', payload.channel_layout);
  1808. this.assignStringMetadata(target, 'start_time', payload.start_time);
  1809. this.assignStringMetadata(target, 'year', payload.year);
  1810. this.assignStringMetadata(target, 'disc', payload.disc);
  1811. this.assignStringMetadata(target, 'ALBUMARTIST', payload.ALBUMARTIST);
  1812. this.assignStringMetadata(target, 'COMPOSER', payload.COMPOSER);
  1813. this.assignStringMetadata(target, 'LYRICIST', payload.LYRICIST);
  1814. this.assignStringMetadata(target, 'COMMENT', payload.COMMENT, true);
  1815. this.assignNumberMetadata(target, 'videoSize', payload.videoSize);
  1816. this.assignNumberMetadata(target, 'probe_score', payload.probe_score);
  1817. this.assignNumberMetadata(target, 'nb_streams', payload.nb_streams);
  1818. this.assignNumberMetadata(target, 'nb_programs', payload.nb_programs);
  1819. }
  1820. private mergeVideoItemFromSource(target: VideoItem, source: VideoItem): void {
  1821. if (!target || !source) {
  1822. return;
  1823. }
  1824. this.assignStringMetadata(target, 'name', source.name);
  1825. this.assignStringMetadata(target, 'artist', source.artist);
  1826. this.assignStringMetadata(target, 'album', source.album);
  1827. this.assignStringMetadata(target, 'bit_rate', source.bit_rate);
  1828. this.assignStringMetadata(target, 'duration', source.duration);
  1829. this.assignStringMetadata(target, 'sampleRate', source.sampleRate);
  1830. this.assignStringMetadata(target, 'md5Str', source.md5Str);
  1831. this.assignStringMetadata(target, 'trackCount', source.trackCount);
  1832. this.assignStringMetadata(target, 'mimeType', source.mimeType);
  1833. this.assignStringMetadata(target, 'size', source.size);
  1834. mergeCoverWithPriority(target, source.pixelMapPath, source.isCustomCover ?? 0);
  1835. this.assignStringMetadata(target, 'lyricContent', source.lyricContent, true);
  1836. this.assignStringMetadata(target, 'genre', source.genre);
  1837. this.assignStringMetadata(target, 'track', source.track);
  1838. this.assignStringMetadata(target, 'bits_per_raw_sample', source.bits_per_raw_sample);
  1839. this.assignStringMetadata(target, 'channels', source.channels);
  1840. this.assignStringMetadata(target, 'channel_layout', source.channel_layout);
  1841. this.assignStringMetadata(target, 'start_time', source.start_time);
  1842. this.assignStringMetadata(target, 'year', source.year);
  1843. this.assignStringMetadata(target, 'disc', source.disc);
  1844. this.assignStringMetadata(target, 'ALBUMARTIST', source.ALBUMARTIST);
  1845. this.assignStringMetadata(target, 'COMPOSER', source.COMPOSER);
  1846. this.assignStringMetadata(target, 'LYRICIST', source.LYRICIST);
  1847. this.assignStringMetadata(target, 'COMMENT', source.COMMENT, true);
  1848. this.assignNumberMetadata(target, 'videoSize', source.videoSize);
  1849. this.assignNumberMetadata(target, 'probe_score', source.probe_score);
  1850. this.assignNumberMetadata(target, 'nb_streams', source.nb_streams);
  1851. this.assignNumberMetadata(target, 'nb_programs', source.nb_programs);
  1852. if (source.remote_rel_path && StrUtil.isEmpty(target.remote_rel_path)) {
  1853. target.remote_rel_path = source.remote_rel_path;
  1854. }
  1855. }
  1856. private async hydrateRemoteSongFromDb(item: VideoItem | undefined): Promise<void> {
  1857. if (!item || !isRemoteCloudType(item.type)) {
  1858. return;
  1859. }
  1860. const storagePath = item.remote_rel_path || WebDavUrlUtil.toStoragePath(item.filePath);
  1861. if (!storagePath) {
  1862. return;
  1863. }
  1864. try {
  1865. const cached = await this.table.queryVideoByFilePath(storagePath);
  1866. if (!cached) {
  1867. return;
  1868. }
  1869. this.mergeVideoItemFromSource(item, cached);
  1870. if (StrUtil.isEmpty(item.remote_rel_path)) {
  1871. item.remote_rel_path = storagePath;
  1872. }
  1873. if (item === this.currentSong) {
  1874. if (StrUtil.isNotEmpty(item.name)) {
  1875. this.name = item.name;
  1876. }
  1877. if (StrUtil.isNotEmpty(item.artist)) {
  1878. this.artist = item.artist!;
  1879. }
  1880. if (StrUtil.isNotEmpty(item.pixelMapPath)) {
  1881. this.cover = item.pixelMapPath!;
  1882. }
  1883. if (StrUtil.isNotEmpty(item.lyricContent) && StrUtil.isEmpty(this.lyricContent)) {
  1884. this.applyInlineLyricContent(item.lyricContent as string);
  1885. }
  1886. }
  1887. } catch (error) {
  1888. Logger.error(TAG, `hydrateRemoteSongFromDb 失败: ${(error as Error).message}`);
  1889. }
  1890. }
  1891. private applyInlineLyricContent(content: string): void {
  1892. if (StrUtil.isEmpty(content)) {
  1893. return;
  1894. }
  1895. this.lyricContent = content;
  1896. const lines: string[] = content.split('\n').map((line: string) => line.trim());
  1897. const lyric: Lyric = this.parser.parse(lines);
  1898. this.lyricController.setLyric(lyric);
  1899. this.lyricControllerXF.setLyric(lyric);
  1900. this.lyricControllerSingle.setLyric(lyric);
  1901. }
  1902. private extractParentPathFromStoragePath(path: string): string {
  1903. if (!path) {
  1904. return '';
  1905. }
  1906. const lastSlash = path.lastIndexOf('/');
  1907. if (lastSlash <= 0) {
  1908. return '';
  1909. }
  1910. return path.substring(0, lastSlash);
  1911. }
  1912. private resolveRemoteStoragePath(target: VideoItem): string | null {
  1913. if (!target || !isRemoteCloudType(target.type)) {
  1914. return null;
  1915. }
  1916. if (isWebDavType(target.type)) {
  1917. const storagePath = target.remote_rel_path || WebDavUrlUtil.toStoragePath(target.filePath);
  1918. if (storagePath) {
  1919. target.remote_rel_path = storagePath;
  1920. return storagePath;
  1921. }
  1922. return null;
  1923. }
  1924. if (target.remote_rel_path && target.remote_rel_path.length > 0) {
  1925. return target.remote_rel_path;
  1926. }
  1927. return null;
  1928. }
  1929. private async persistRemoteMetadataToDb(target: VideoItem): Promise<void> {
  1930. if (!this.context || !target || !isRemoteCloudType(target.type)) {
  1931. return;
  1932. }
  1933. const storagePath = this.resolveRemoteStoragePath(target);
  1934. if (!storagePath) {
  1935. return;
  1936. }
  1937. const table = new MediaTable(this.context);
  1938. await new Promise<void>((resolve) => {
  1939. table.getRdbStore(this.context as Context, () => resolve());
  1940. });
  1941. const cloneItem = cloneVideoItem(target);
  1942. cloneItem.filePath = storagePath;
  1943. cloneItem.remote_rel_path = storagePath;
  1944. cloneItem.parentPath = this.extractParentPathFromStoragePath(storagePath);
  1945. await table.saveOrUpdateWebDavItem(cloneItem);
  1946. }
  1947. onPageHide() {
  1948. this.knockController?.immersiveDisableListening();
  1949. }
  1950. @State isFirstStartPlay: boolean = false
  1951. private async startFileDeletionWatcher(): Promise<void> {
  1952. if (!this.rootPath) {
  1953. return;
  1954. }
  1955. if (!this.deletionWatcher) {
  1956. this.deletionWatcher = new FileDeletionWatcher(this.context, this.table);
  1957. }
  1958. try {
  1959. await this.deletionWatcher.watchDirectories([
  1960. this.rootPath,
  1961. this.lockPath,
  1962. this.favPath,
  1963. this.historyPath
  1964. ]);
  1965. } catch (error) {
  1966. Logger.error(TAG, `初始化文件删除监听失败: ${(error as Error).message}`);
  1967. }
  1968. }
  1969. //获取download_path
  1970. async mkDownLoadDir() {
  1971. const documentViewPicker = new picker.DocumentViewPicker()
  1972. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  1973. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  1974. PreferencesUtil.putSync('download_path', this.rootPath+'/')
  1975. this.currentPath = this.rootPath
  1976. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  1977. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  1978. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  1979. Logger.info('onecold rootPath = ' + this.rootPath)
  1980. if (!FileUtil.accessSync(this.favPath)) {
  1981. FileUtil.mkdirSync(this.favPath)
  1982. }
  1983. if (!FileUtil.accessSync(this.historyPath)) {
  1984. FileUtil.mkdirSync(this.historyPath)
  1985. }
  1986. // await this.startFileDeletionWatcher();
  1987. this.getSortedFiles(this.rootPath).then(async () => {
  1988. this.isFavMusic = false
  1989. //穿山甲
  1990. // this.loadBannerAd(CSJUtil.getBannerID())
  1991. this.restoreLastPlayContext();
  1992. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  1993. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  1994. if (ArrayUtil.isEmpty(this.songList)) {
  1995. this.songList = this.videoLocalList.filter(item =>
  1996. item.type === CommonConstants.TYPE_LOCAL && !this.isIsoLocalFile(item))
  1997. } else {
  1998. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  1999. }
  2000. if (ArrayUtil.isNotEmpty(this.songList)) {
  2001. this.isFirstStartPlay = true
  2002. this.sonDataSource.pushArrayData(this.songList)
  2003. if (this.currentSong === undefined) {
  2004. this.isFirstStartPlay = false
  2005. this.currentSong = this.songList[0]
  2006. }
  2007. const restoredUrl = await this.resolvePlaybackUrlForCurrentSong('restore-last-song');
  2008. if (!restoredUrl) {
  2009. return;
  2010. }
  2011. this.videoUrl = restoredUrl;
  2012. Logger.info(TAG, `WebDAV URL同步构建完成: ${this.videoUrl}`);
  2013. this.name = this.currentSong.name
  2014. this.cover = this.currentSong.pixelMapPath
  2015. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  2016. } else {
  2017. this.name = '空空如也'
  2018. }
  2019. })
  2020. this.getFavList(false)
  2021. }
  2022. getFavList(isFavRefresh: boolean) {
  2023. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  2024. this.favList = result
  2025. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  2026. this.videoLocalList = this.favList
  2027. this.updateListData(this.videoLocalList, true)
  2028. }
  2029. })
  2030. }
  2031. getHistoryList(isRefresh: boolean) {
  2032. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  2033. this.historyList = result
  2034. // for (let i = 0; i < this.historyList.length; i++) {
  2035. //
  2036. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  2037. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  2038. // }
  2039. if (isRefresh) {
  2040. this.videoLocalList = this.historyList
  2041. this.updateListData(this.videoLocalList, true)
  2042. }
  2043. })
  2044. }
  2045. // 组件消失生命周期
  2046. aboutToDisappear() {
  2047. console.info('LifeCycleComponent aboutToDisappear');
  2048. if (this.alphaBetHideTimer) {
  2049. clearTimeout(this.alphaBetHideTimer);
  2050. this.alphaBetHideTimer = 0;
  2051. }
  2052. if (this.alphaBetRebuildTimer) {
  2053. clearTimeout(this.alphaBetRebuildTimer);
  2054. this.alphaBetRebuildTimer = 0;
  2055. }
  2056. if (this.pagingScheduleTimer) {
  2057. clearTimeout(this.pagingScheduleTimer);
  2058. this.pagingScheduleTimer = 0;
  2059. }
  2060. if (this.gridWaterScrollIdleTimer) {
  2061. clearTimeout(this.gridWaterScrollIdleTimer);
  2062. this.gridWaterScrollIdleTimer = 0;
  2063. }
  2064. if (this.listUpdateTimer) {
  2065. clearTimeout(this.listUpdateTimer);
  2066. this.listUpdateTimer = 0;
  2067. }
  2068. if (this.mediaLibraryWarmupPrefetchTimer) {
  2069. clearTimeout(this.mediaLibraryWarmupPrefetchTimer);
  2070. this.mediaLibraryWarmupPrefetchTimer = 0;
  2071. }
  2072. this.clearInitialSeekGuardTimer();
  2073. this.alphaBetBuildVersion++;
  2074. this.gridWaterLastActiveTs = 0;
  2075. this.coverThumbCache.dispose();
  2076. this.coverThumbCacheReady = false;
  2077. this.pendingCoverThumbRefresh = false;
  2078. this.deletionWatcher?.stop();
  2079. this.knockController?.immersiveDisableListening();
  2080. this.curIndex = 0
  2081. this.isAppForeground = false;
  2082. emitter.off(EventConstants.EVENT_AUDIO_OPEN);
  2083. emitter.off(EventConstants.EVENT_SCAN_UPDATE);
  2084. emitter.off(EventConstants.EVENT_SWIPE_BACK_UPDATE);
  2085. emitter.off(EventConstants.EVENT_SETTING_UPDATE);
  2086. emitter.off(EventConstants.EVENT_WEBDAV_METADATA_UPDATED);
  2087. emitter.off(EventConstants.EVENT_EQUALIZER_CHANGED);
  2088. emitter.off(EventConstants.EVENT_PLAYLIST_PLAY);
  2089. emitter.off(EventConstants.EVENT_PLAYLIST_REFRESH_SORT);
  2090. emitter.off(EventConstants.EVENT_PLAY_QUEUE_REFRESH);
  2091. emitter.off(EventConstants.EVENT_OPEN_LOCAL_SPECIAL_LIST);
  2092. emitter.off(EventConstants.EVENT_PLAY_PAUSE);
  2093. this.mDestroyPage = true;
  2094. this.audioInterruptResumePending = false;
  2095. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  2096. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  2097. this.stop();
  2098. }
  2099. this.mIjkMediaPlayer.off('audioInterrupt');
  2100. this.mIjkMediaPlayer.off('deviceChange');
  2101. if (this.audioRoutingManager && this.outputDeviceChangeCallback) {
  2102. try {
  2103. this.audioRoutingManager.off('deviceChange', this.outputDeviceChangeCallback);
  2104. } catch (error) {
  2105. Logger.warn(TAG, `注销音频输出设备监听失败: ${(error as BusinessError).message ?? error}`);
  2106. }
  2107. }
  2108. this.outputDeviceChangeCallback = undefined;
  2109. this.audioRoutingManager = undefined;
  2110. if (workerInstance) {
  2111. workerInstance.terminate();
  2112. }
  2113. this.stopPip();
  2114. this.destroyPipController()
  2115. this.getUIContext().getHostContext()!.eventHub.off('playOrPause');
  2116. this.getUIContext().getHostContext()!.eventHub.off('playPrevious');
  2117. this.getUIContext().getHostContext()!.eventHub.off('playNext');
  2118. this.getUIContext().getHostContext()!.eventHub.off('showPlayerView');
  2119. this.getUIContext().getHostContext()!.eventHub.off('openPlayerViewFromMiniBar');
  2120. this.getUIContext().getHostContext()!.eventHub.off('dismissPlayerView');
  2121. this.getUIContext().getHostContext()!.eventHub.off('openPlayList');
  2122. this.eventHub.off('onStateChange');
  2123. }
  2124. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean,
  2125. openItem?: VideoItem, immediateListUpdate?: boolean, scrollTopAfterUpdate?: boolean) {
  2126. this.isFavMusic = false
  2127. console.info('onecold getSortedFiles 1 curPath '+curPath)
  2128. if (isWorkerPost) {
  2129. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  2130. }
  2131. if (this.modeType !== 0) {
  2132. // 第三方打开场景:非文件夹模式也需要继续执行自动播放
  2133. if (isOpen && destPath) {
  2134. this.openMusic(true, destPath, openItem)
  2135. }
  2136. return
  2137. }
  2138. console.info('onecold getSortedFiles 2')
  2139. this.isCanBack = false
  2140. this.currentPath = curPath
  2141. console.info('onecold getSortedFiles this.currentPath ='+this.currentPath)
  2142. this.titleName = getFileDirName(this.currentPath,this.rootPath)
  2143. if (curPath === this.rootPath) {
  2144. this.rightTopImage = $r('sys.symbol.sort')
  2145. } else {
  2146. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  2147. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  2148. this.rightTopImage = $r('sys.symbol.chevron_left')
  2149. }
  2150. }
  2151. // Get the current file list and calculate its hash
  2152. this.fileList = FileUtil.listFileSync(curPath);
  2153. const currentHash = simpleHash(this.fileList);
  2154. // Check cache
  2155. const cachedValue = this.findCache(curPath);
  2156. Logger.info('onecold cachedValue = ' + cachedValue)
  2157. const cachedHash = this.findStringCache(curPath + '_hash');
  2158. const cachedDirList = this.findCache(curPath + "_dirList");
  2159. if (cachedValue !== undefined&&!this.isRefreshing) {
  2160. // this.videoLocalList = cachedValue;
  2161. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  2162. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  2163. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  2164. }
  2165. this.isRefreshing = false
  2166. this.updateListData(cachedValue, undefined, immediateListUpdate)
  2167. if (scrollTopAfterUpdate) {
  2168. this.scrollToTopForCurrentLayout()
  2169. }
  2170. }
  2171. if (cachedDirList !== undefined) {
  2172. this.dirList = cachedDirList
  2173. }
  2174. //通过当前hash值和缓存hash判断list有没有变化
  2175. if (cachedValue && cachedHash === currentHash) {
  2176. return;
  2177. }
  2178. // this.fileList = FileUtil.listFileSync(curPath)
  2179. let directories: Array<VideoItem> = [];
  2180. let isoFiles: Array<VideoItem> = this.getLocalIsoItems(curPath, this.fileList);
  2181. let files: Array<VideoItem> = [];
  2182. for (let i = 0; i < this.fileList.length; i++) {
  2183. // console.info(`The name of file: ${this.fileList[i]}`);
  2184. let path = curPath + '/' + this.fileList[i]
  2185. if (FileUtil.isDirectory(path)) {
  2186. let item: VideoItem =
  2187. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  2188. '')
  2189. if (this.isShowDir(item.name)) {
  2190. directories.push(item);
  2191. }
  2192. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2193. // Utility.doSortListAscending(directories)
  2194. } else {
  2195. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  2196. let item: VideoItem =
  2197. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  2198. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  2199. files.push(item);
  2200. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2201. // this.doSortListAscending(files)
  2202. }
  2203. }
  2204. }
  2205. }
  2206. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  2207. if (this.currentPath !== this.lockPath) {
  2208. files = result.filter(item => !this.isIsoLocalFile(item));
  2209. }
  2210. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2211. Utility.doSortListAscending(files)
  2212. Utility.doSortListAscending(isoFiles)
  2213. if (this.currentPath === this.rootPath) {
  2214. this.dirList = directories
  2215. this.addCache(curPath + "_dirList", this.dirList);
  2216. }
  2217. //插入广告先注释掉
  2218. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  2219. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  2220. // directories.push(adItem)
  2221. // }
  2222. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  2223. this.videoLocalList = directories.concat(isoFiles).concat(files);
  2224. this.updateListData(this.videoLocalList, undefined, immediateListUpdate)
  2225. if (scrollTopAfterUpdate) {
  2226. this.scrollToTopForCurrentLayout()
  2227. }
  2228. if (ArrayUtil.isNotEmpty(files)) {
  2229. if (this.currentPath != this.rootPath) {
  2230. if (files) {
  2231. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  2232. }
  2233. }
  2234. }
  2235. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2236. this.addCache(curPath, this.videoLocalList);
  2237. await this.saveCacheToStorage();
  2238. this.addStringCache(curPath + '_hash', currentHash);
  2239. }
  2240. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  2241. for (let i = 0; i < this.videoLocalList.length; i++) {
  2242. console.info(`onecold gengxin 1: ${this.videoLocalList[i].name}`);
  2243. }
  2244. // this.setButtonStatus()
  2245. this.openMusic(isOpen, destPath,openItem)
  2246. this.isRefreshing = false
  2247. });
  2248. }
  2249. //第三方app打开天天静听导入音乐后播放
  2250. openMusic(isOpen?: boolean, destPath?: string,openItem?:VideoItem){
  2251. if (isOpen&&destPath) {
  2252. if (destPath === undefined) {
  2253. // 处理 destPath 为 undefined 的情况
  2254. return
  2255. }
  2256. if (destPath.endsWith('.lrc')) {
  2257. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  2258. if (StrUtil.isNotEmpty(this.videoUrl)) {
  2259. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  2260. this.initLyric(lyricPath);
  2261. }
  2262. return
  2263. }
  2264. if(openItem){
  2265. this.doPlay(openItem,0,false,true)
  2266. // this.isShowPlay = true
  2267. this.setShowPlayTrue()
  2268. }
  2269. }
  2270. }
  2271. //扫描文件夹入库
  2272. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  2273. const files = FileUtil.listFileSync(curPath);
  2274. let mediaItems: VideoItem[] = [];
  2275. Logger.info('onecold scanDirectory start ')
  2276. for (const file of files) {
  2277. const fPath = `${curPath}/${file}`;
  2278. if (fPath === this.lockPath) {
  2279. Logger.info(`Skipping locked path: ${fPath}`);
  2280. continue;
  2281. }
  2282. if (FileUtil.isDirectory(fPath)) {
  2283. // Recursively scan subdirectories
  2284. const subDirItems = await this.scanDirectory(fPath);
  2285. mediaItems = mediaItems.concat(subDirItems);
  2286. } else {
  2287. Logger.info('onecold scanDirectory filePath = ' + fPath)
  2288. // Process media files
  2289. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  2290. let mediaItem: VideoItem =
  2291. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2292. mediaItems.push(mediaItem);
  2293. this.table.insert(mediaItem, (id: number) => {
  2294. });
  2295. }
  2296. }
  2297. }
  2298. return mediaItems;
  2299. }
  2300. updateListData(mList: Array<VideoItem>, noSort?: boolean, immediate?: boolean) {
  2301. this.isShowTitleBar = true
  2302. const shouldAnimate = !immediate
  2303. if (this.listUpdateTimer) {
  2304. clearTimeout(this.listUpdateTimer)
  2305. this.listUpdateTimer = 0
  2306. }
  2307. const updateVersion = ++this.listUpdateVersion
  2308. if (shouldAnimate) {
  2309. this.getUIContext().animateTo({ duration: 666 }, () => {
  2310. this.opacityItem = 0.5;
  2311. });
  2312. }
  2313. const applyListData = () => {
  2314. if (updateVersion !== this.listUpdateVersion) {
  2315. return
  2316. }
  2317. this.videoLocalList = mList;
  2318. if (!noSort) {
  2319. if (this.modeType === 0 || this.modeType === 1) {
  2320. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  2321. this.doSortType(this.sortType)
  2322. }
  2323. }
  2324. this.dataSource.pushArrayData(this.videoLocalList)
  2325. if (shouldAnimate) {
  2326. this.getUIContext().animateTo({ duration: 666 }, () => {
  2327. this.opacityItem = 1;
  2328. });
  2329. } else {
  2330. this.opacityItem = 1;
  2331. }
  2332. this.setButtonStatus()
  2333. //添加到字母索引表
  2334. this.markAlphaBetDirty()
  2335. };
  2336. if (immediate) {
  2337. applyListData();
  2338. return;
  2339. }
  2340. this.listUpdateTimer = setTimeout(() => {
  2341. this.listUpdateTimer = 0
  2342. applyListData();
  2343. }, 200);
  2344. }
  2345. getCurFileList(): Array<VideoItem> {
  2346. const source = this.isSearchMode ? this.filteredList : this.videoLocalList
  2347. let files: Array<VideoItem> = [];
  2348. if (ArrayUtil.isNotEmpty(source)) {
  2349. for (let i = 0; i < source.length; i++) {
  2350. if (this.isSelectableLocalItem(source[i])) {
  2351. files.push(source[i]);
  2352. }
  2353. }
  2354. }
  2355. return files
  2356. }
  2357. private isProtectedLocalDirectory(item: VideoItem): boolean {
  2358. return item.type === CommonConstants.TYPE_IS_DIR &&
  2359. (item.name === LocalMusic.STR_LOCK_VIDEO ||
  2360. item.name === LocalMusic.STR_FAC_VIDEO ||
  2361. item.name === LocalMusic.STR_HISTORY_MUSIC)
  2362. }
  2363. private isIsoLocalFile(item?: VideoItem | null): boolean {
  2364. if (!item || item.type !== CommonConstants.TYPE_LOCAL) {
  2365. return false
  2366. }
  2367. return Utility.isIsoByExtension(item.filePath || item.fileName || item.name || '')
  2368. }
  2369. private supportsLocalAudioActions(item: VideoItem): boolean {
  2370. return !!item && item.type !== CommonConstants.TYPE_IS_DIR && !this.isIsoLocalFile(item)
  2371. }
  2372. private buildLocalIsoItem(filePath: string, fileName?: string): VideoItem {
  2373. const displayName = fileName || FileUtil.getFileName(filePath) || filePath
  2374. let fileSize = 0
  2375. try {
  2376. const stat = fs.statSync(filePath) as fs.Stat
  2377. if (typeof stat.size === 'number') {
  2378. fileSize = stat.size
  2379. }
  2380. } catch (_error) {
  2381. }
  2382. const item = new VideoItem(
  2383. displayName,
  2384. filePath,
  2385. filePath,
  2386. CommonConstants.TYPE_LOCAL,
  2387. fileSize,
  2388. Utility.getFormatDateStr(Date.now(), 'yyyy-MM-dd HH:mm'),
  2389. Utility.formatFSize(fileSize),
  2390. '',
  2391. 'ISO 镜像',
  2392. '可提取音频',
  2393. displayName
  2394. )
  2395. item.mimeType = 'application/x-iso9660-image'
  2396. item.duration = ''
  2397. return item
  2398. }
  2399. private getLocalIsoItems(curPath: string, fileNames?: Array<string>): Array<VideoItem> {
  2400. let sourceNames: Array<string> = []
  2401. if (fileNames !== undefined && fileNames.length > 0) {
  2402. sourceNames = fileNames
  2403. } else {
  2404. const listedNames = FileUtil.listFileSync(curPath)
  2405. sourceNames = listedNames ? listedNames : []
  2406. }
  2407. const isoItems: Array<VideoItem> = []
  2408. for (let i = 0; i < sourceNames.length; i++) {
  2409. const name = sourceNames[i]
  2410. const fullPath = `${curPath}/${name}`
  2411. if (FileUtil.isDirectory(fullPath) || !Utility.isIsoByExtension(fullPath)) {
  2412. continue
  2413. }
  2414. isoItems.push(this.buildLocalIsoItem(fullPath, name))
  2415. }
  2416. Utility.doSortListAscending(isoItems)
  2417. return isoItems
  2418. }
  2419. private filterOutLocalIsoItems(items: Array<VideoItem>): Array<VideoItem> {
  2420. return items.filter(item => !this.isIsoLocalFile(item))
  2421. }
  2422. private isSelectableLocalItem(item: VideoItem): boolean {
  2423. if (!item) {
  2424. return false
  2425. }
  2426. if (item.type === CommonConstants.TYPE_LOCAL) {
  2427. return true
  2428. }
  2429. if (item.type === CommonConstants.TYPE_IS_DIR) {
  2430. return !this.isProtectedLocalDirectory(item)
  2431. }
  2432. return false
  2433. }
  2434. private isLocalItemSelected(item: VideoItem): boolean {
  2435. return this.selectedFiles.some(x => x.filePath === item.filePath)
  2436. }
  2437. private hasSelectedDirectories(): boolean {
  2438. return this.selectedFiles.some(item => item.type === CommonConstants.TYPE_IS_DIR)
  2439. }
  2440. private getSelectedPlayableFiles(): Array<VideoItem> {
  2441. return this.selectedFiles.filter(item => item.type === CommonConstants.TYPE_LOCAL && !this.isIsoLocalFile(item))
  2442. }
  2443. private syncLocalSelectionState(): void {
  2444. const selectableItems = this.getCurFileList()
  2445. const selectableKeys: Set<string> = new Set(selectableItems.map(item => item.filePath))
  2446. const nextSelected = this.selectedFiles.filter(item => selectableKeys.has(item.filePath))
  2447. if (nextSelected.length !== this.selectedFiles.length) {
  2448. this.selectedFiles = [...nextSelected]
  2449. }
  2450. this.isAllSelected = nextSelected.length > 0 && nextSelected.length === selectableItems.length
  2451. }
  2452. private enterLocalMultiSelect(item: VideoItem): void {
  2453. if (!this.isSelectableLocalItem(item)) {
  2454. return
  2455. }
  2456. if (!this.isMultiSelect) {
  2457. this.isMultiSelect = true
  2458. }
  2459. if (!this.isLocalItemSelected(item)) {
  2460. this.selectedFiles = [...this.selectedFiles, item]
  2461. }
  2462. this.syncLocalSelectionState()
  2463. }
  2464. private selectSingleItemForDelete(item: VideoItem): void {
  2465. if (!this.isSelectableLocalItem(item)) {
  2466. return
  2467. }
  2468. this.selectedFiles = [item]
  2469. this.isAllSelected = false
  2470. }
  2471. setButtonStatus() {
  2472. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2473. this.isZero = false
  2474. } else {
  2475. this.isZero = true
  2476. }
  2477. if (this.currentPath !== this.rootPath &&
  2478. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  2479. this.isHasDir = true //不为空,说明有子文件夹
  2480. } else {
  2481. this.isHasDir = false
  2482. }
  2483. }
  2484. private getPlayListDisplayCount(): number {
  2485. if (this.playQueueScope === 'history') {
  2486. return this.historyList.length;
  2487. }
  2488. if (this.playQueueScope === 'fav') {
  2489. return this.favList.length;
  2490. }
  2491. if (this.playQueueScope === 'playlist') {
  2492. // 检测是否是流媒体播放(Navidrome/Jellyfin/Emby/AudioStation/Plex/道理鱼等)
  2493. // 如果是,优先返回服务端总数
  2494. const navidromeTotalCount = getNavidromeTotalCount();
  2495. Logger.info('heanup getPlayListDisplayCount', `playQueueScope=playlist, navidromeTotalCount=${navidromeTotalCount}, currentSong=${this.currentSong?.name}, type=${this.currentSong?.type}`);
  2496. if (navidromeTotalCount > 0 && this.currentSong && (
  2497. isNavidromeType(this.currentSong.type) ||
  2498. isJellyfinType(this.currentSong.type) ||
  2499. isEmbyType(this.currentSong.type) ||
  2500. isAudioStationType(this.currentSong.type) ||
  2501. isPlexType(this.currentSong.type) ||
  2502. isDaoLiYuType(this.currentSong.type)
  2503. )) {
  2504. Logger.info('heanup getPlayListDisplayCount', `返回服务端总数: ${navidromeTotalCount}`);
  2505. return navidromeTotalCount;
  2506. }
  2507. Logger.info('heanup getPlayListDisplayCount', `返回 currentSongList.length: ${this.currentSongList.length}`);
  2508. return this.currentSongList.length;
  2509. }
  2510. if (this.playQueueScope === 'view' && this.modeType === 1 && this.totalCount > 0) {
  2511. return this.totalCount;
  2512. }
  2513. Logger.info('heanup getPlayListDisplayCount', `返回 songList.length: ${this.songList.length}, playQueueScope=${this.playQueueScope}`);
  2514. return this.songList.length;
  2515. }
  2516. private restoreLastPlayContext(): void {
  2517. const scope = PreferencesUtil.getStringSync('LastPlayQueueScope', 'view') as string;
  2518. if (scope === 'history' || scope === 'fav' || scope === 'playlist' || scope === 'single') {
  2519. this.playQueueScope = scope;
  2520. } else {
  2521. this.playQueueScope = 'view';
  2522. }
  2523. const lastModeType = PreferencesUtil.getNumberSync('LastPlayModeType', this.modeType);
  2524. const lastTotalCount = PreferencesUtil.getNumberSync('LastPlayTotalCount', 0);
  2525. if (lastModeType === 1 && this.totalCount === 0 && lastTotalCount > 0) {
  2526. this.totalCount = lastTotalCount;
  2527. }
  2528. }
  2529. private async hydrateFullMediaPlayListIfNeeded(isSonList:boolean = true): Promise<void> {
  2530. if (this.isHydratingPlayList) {
  2531. return;
  2532. }
  2533. if (this.playQueueScope !== 'view' || this.modeType !== 1) {
  2534. return;
  2535. }
  2536. if (this.totalCount === 0 || this.songList.length >= this.totalCount) {
  2537. return;
  2538. }
  2539. this.isHydratingPlayList = true;
  2540. try {
  2541. const fullList: VideoItem[] = [];
  2542. let pageIndex = 0;
  2543. let hasMore = true;
  2544. while (hasMore) {
  2545. const result = await this.table.queryMediaLibraryPaged({
  2546. pageIndex,
  2547. pageSize: this.pageSize,
  2548. sortType: this.sortType,
  2549. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  2550. isShowFileName: this.isShowFileName
  2551. });
  2552. if (result.items.length === 0) {
  2553. break;
  2554. }
  2555. fullList.push(...result.items);
  2556. hasMore = result.hasMore;
  2557. pageIndex += 1;
  2558. if (fullList.length >= result.totalCount) {
  2559. hasMore = false;
  2560. }
  2561. }
  2562. if (fullList.length > 0) {
  2563. if(isSonList){
  2564. this.songList = fullList;
  2565. this.sonDataSource.pushArrayData(this.songList);
  2566. }else{
  2567. this.videoLocalList = fullList;
  2568. this.dataSource.pushArrayData(this.videoLocalList);
  2569. }
  2570. }
  2571. } finally {
  2572. this.isHydratingPlayList = false;
  2573. }
  2574. }
  2575. @Builder
  2576. SortMenuBuilder() {
  2577. Menu() {
  2578. MenuItem({
  2579. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.person')),
  2580. content: "按艺术家",
  2581. builder: this.SubSortBuilder(SortMode.ByArtist),
  2582. symbolEndIcon: this.isSortTypeInRange(SortMode.ByArtist) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2583. })
  2584. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByArtist)))
  2585. MenuItem({
  2586. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat_size_square')),
  2587. content: "按专辑",
  2588. builder: this.SubSortBuilder(SortMode.ByAlbum),
  2589. symbolEndIcon: this.isSortTypeInRange(SortMode.ByAlbum) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2590. })
  2591. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByAlbum)))
  2592. MenuItem({
  2593. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat')),
  2594. content: "按名称",
  2595. builder: this.SubSortBuilder(SortMode.ByName),
  2596. symbolEndIcon: this.isSortTypeInRange(SortMode.ByName) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2597. })
  2598. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByName)))
  2599. MenuItem({
  2600. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2601. content: $r('app.string.sort_by_time'),
  2602. builder: this.SubSortBuilder(SortMode.ByTime),
  2603. symbolEndIcon: this.isSortTypeInRange(SortMode.ByTime) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2604. })
  2605. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByTime)))
  2606. MenuItem({
  2607. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  2608. content: '按碟片音轨号',
  2609. builder: this.SubSortBuilder(SortMode.ByDiscTrack),
  2610. symbolEndIcon: this.isSortTypeInRange(SortMode.ByDiscTrack) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2611. })
  2612. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByDiscTrack)))
  2613. .visibility((this.modeType==0||(this.modeType==2&&this.isCanBack)||
  2614. (this.modeType==3&&this.isCanBack))?Visibility.Visible:Visibility.None)
  2615. }.attributeModifier(new MenuModifier())
  2616. }
  2617. @Builder
  2618. SortMenuForArtistAblumBuilder() {
  2619. Menu() {
  2620. MenuItem({
  2621. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat')),
  2622. content: "按名称",
  2623. builder: this.SubSortBuilder(SortMode.ByName),
  2624. symbolEndIcon: this.isSortTypeInRange(SortMode.ByName) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2625. })
  2626. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByName)))
  2627. MenuItem({
  2628. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2629. content: '按数量',
  2630. builder: this.SubSortBuilder(SortMode.ByCount),
  2631. symbolEndIcon: this.isSortTypeInRange(SortMode.ByCount) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2632. })
  2633. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByCount)))
  2634. }.attributeModifier(new MenuModifier())
  2635. }
  2636. @Builder SubSortBuilder(sortType: number){
  2637. Menu(){
  2638. MenuItem({
  2639. content: "升序",
  2640. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_up')),
  2641. symbolEndIcon: this.sortType === sortType ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2642. })
  2643. .backgroundColor(this.getSortOrderItemBackground(this.sortType === sortType, true))
  2644. .onClick(async () => {
  2645. await this.doSortType(sortType)
  2646. })
  2647. MenuItem({
  2648. content: "降序",
  2649. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_down')),
  2650. symbolEndIcon: this.sortType === sortType + 1 ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2651. })
  2652. .backgroundColor(this.getSortOrderItemBackground(this.sortType === sortType + 1, false))
  2653. .onClick(async () => {
  2654. await this.doSortType(sortType + 1) // 降序的sortType = 升序的sortType + 1
  2655. })
  2656. }
  2657. }
  2658. async doSortType(index: number): Promise<void> {
  2659. Logger.info('heanup LocalMusic', `doSortType: 切换排序方式 sortType=${index}, mode=${this.modeType}, isCanBack=${this.isCanBack}`);
  2660. this.sortType = index;
  2661. this.saveSortTypeForCurrentMode(index);
  2662. // 详情页模式(modeType=2/3 且 isCanBack=true): 重新查询当前项目的歌曲
  2663. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  2664. await this.reloadCurrentDetailSongs();
  2665. } else {
  2666. // 分页模式下,排序需要重新从数据库查询
  2667. await this.resetAndLoadFirstPage();
  2668. }
  2669. }
  2670. /**
  2671. * 重新加载当前详情页(专辑/艺术家)的歌曲数据
  2672. * 用于详情页切换排序方式时重新查询并排序
  2673. */
  2674. private async reloadCurrentDetailSongs(): Promise<void> {
  2675. Logger.info('heanup LocalMusic', `reloadCurrentDetailSongs: modeType=${this.modeType}, titleName=${this.titleName}, sortType=${this.sortType}`);
  2676. try {
  2677. if (this.modeType === 2) {
  2678. // 艺术家详情页: 重新查询该艺术家的歌曲
  2679. const mList = await this.table.querySongsByArtist(this.titleName, this.sortType, this.isShowFileName);
  2680. if (ArrayUtil.isNotEmpty(mList)) {
  2681. // 使用带排序类型的缓存键
  2682. const cacheKey = `${this.titleName}_sort_${this.sortType}`;
  2683. this.artistMap.set(cacheKey, mList);
  2684. this.totalCount = mList.length;
  2685. // 使用 noSort=true 避免在 updateListData 中重新排序导致死循环
  2686. this.updateListData(mList, true);
  2687. Logger.info('heanup LocalMusic', `reloadCurrentDetailSongs: 艺术家详情页重新加载完成, 歌曲数=${mList.length}`);
  2688. }
  2689. } else if (this.modeType === 3) {
  2690. // 专辑详情页: 重新查询该专辑的歌曲
  2691. const albumList = await this.table.querySongsByAlbum(this.titleName, this.sortType, this.isShowFileName);
  2692. if (ArrayUtil.isNotEmpty(albumList)) {
  2693. // 使用带排序类型的缓存键
  2694. const cacheKey = `${this.titleName}_sort_${this.sortType}`;
  2695. this.albumMap.set(cacheKey, albumList);
  2696. this.totalCount = albumList.length;
  2697. // 使用 noSort=true 避免在 updateListData 中重新排序导致死循环
  2698. this.updateListData(albumList, true);
  2699. Logger.info('heanup LocalMusic', `reloadCurrentDetailSongs: 专辑详情页重新加载完成, 歌曲数=${albumList.length}`);
  2700. }
  2701. }
  2702. } catch (err) {
  2703. const error = err as Error;
  2704. Logger.error('heanup LocalMusic', `reloadCurrentDetailSongs error: ${error.message}`);
  2705. ToastUtil.showToast('重新加载数据失败');
  2706. }
  2707. }
  2708. /**
  2709. * 根据当前模式保存排序类型到不同的存储键
  2710. * 区分列表页和详情页的排序设置
  2711. */
  2712. private saveSortTypeForCurrentMode(sortType: number): void {
  2713. let storageKey = SettingPage.SORT_TYPE;
  2714. if (this.modeType === 2) {
  2715. // 艺术家模式
  2716. if (this.isCanBack) {
  2717. storageKey = 'SORT_TYPE_ARTIST_DETAIL'; // 艺术家详情页排序
  2718. } else {
  2719. storageKey = 'SORT_TYPE_ARTIST'; // 艺术家列表页排序
  2720. }
  2721. } else if (this.modeType === 3) {
  2722. // 专辑模式
  2723. if (this.isCanBack) {
  2724. storageKey = 'SORT_TYPE_ALBUM_DETAIL'; // 专辑详情页排序
  2725. } else {
  2726. storageKey = 'SORT_TYPE_ALBUM'; // 专辑列表页排序
  2727. }
  2728. } else {
  2729. storageKey = SettingPage.SORT_TYPE;
  2730. }
  2731. PreferencesUtil.putSync(storageKey, sortType);
  2732. Logger.info('heanup LocalMusic', `saveSortTypeForCurrentMode: mode=${this.modeType}, isCanBack=${this.isCanBack}, sortType=${sortType}, key=${storageKey}`);
  2733. }
  2734. /**
  2735. * 根据当前模式加载排序类型
  2736. * 区分列表页和详情页的排序设置
  2737. */
  2738. private loadSortTypeForCurrentMode(): number {
  2739. let storageKey = SettingPage.SORT_TYPE;
  2740. let defaultSortType = 4;
  2741. if (this.modeType === 2) {
  2742. // 艺术家模式
  2743. if (this.isCanBack) {
  2744. storageKey = 'SORT_TYPE_ARTIST_DETAIL'; // 艺术家详情页排序
  2745. defaultSortType = 4; // 详情页默认按名称升序
  2746. } else {
  2747. storageKey = 'SORT_TYPE_ARTIST'; // 艺术家列表页排序
  2748. defaultSortType = 9; // 列表页默认按数量降序
  2749. }
  2750. } else if (this.modeType === 3) {
  2751. // 专辑模式
  2752. if (this.isCanBack) {
  2753. storageKey = 'SORT_TYPE_ALBUM_DETAIL'; // 专辑详情页排序
  2754. defaultSortType = 4; // 详情页默认按名称升序
  2755. } else {
  2756. storageKey = 'SORT_TYPE_ALBUM'; // 专辑列表页排序
  2757. defaultSortType = 9; // 列表页默认按数量降序
  2758. }
  2759. }
  2760. return PreferencesUtil.getNumberSync(storageKey, defaultSortType);
  2761. }
  2762. /**
  2763. * 检查当前sortType是否在指定排序类型的范围内
  2764. * 用于判断是否显示打勾图标
  2765. * @param baseSortType 基础排序类型(升序的值)
  2766. * @returns 如果当前sortType是该排序类型的升序或降序,返回true
  2767. */
  2768. private isSortTypeInRange(baseSortType: number): boolean {
  2769. return this.sortType === baseSortType || this.sortType === baseSortType + 1;
  2770. }
  2771. private getSortModeItemBackground(isSelected: boolean): ResourceColor {
  2772. if (!isSelected) {
  2773. return Color.Transparent;
  2774. }
  2775. return this.isDarkMode ? '#334967' : '#EAF2FF';
  2776. }
  2777. private getSortOrderItemBackground(isSelected: boolean, isAsc: boolean): ResourceColor {
  2778. if (!isSelected) {
  2779. return Color.Transparent;
  2780. }
  2781. if (isAsc) {
  2782. return this.isDarkMode ? '#295B8A' : '#DCEEFF';
  2783. }
  2784. return this.isDarkMode ? '#7A4D22' : '#FFE9D5';
  2785. }
  2786. showSheelDialog() {
  2787. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  2788. // this.showTips()
  2789. // return
  2790. // }
  2791. this.showAddDialog()
  2792. }
  2793. showAddDialog() {
  2794. if (this.modeType === 2 || this.modeType === 3) {
  2795. return
  2796. }
  2797. DialogHelper.showActionSheetDialog({
  2798. title: "请选择添加方式(建议歌词文件一起导入)",
  2799. sheets: [
  2800. { value: "新建文件夹", fontColor: $r('app.color.text_color') },
  2801. { value: "手动导入", fontColor: $r('app.color.text_color') },
  2802. { value: "自动导入", fontColor: $r('app.color.text_color') },
  2803. { value: "全选导入", fontColor: $r('app.color.text_color') },
  2804. ],
  2805. maskColor: Color.Transparent,
  2806. backgroundColor: $r('app.color.bg_card'),
  2807. transition: AnimationHelper.transitionInDown(555),
  2808. onAction: (index) => {
  2809. switch (index) {
  2810. case 0:
  2811. if (this.modeType === 0) {
  2812. this.showMkDialog()
  2813. } else {
  2814. ToastUtil.showToast('请切换到首页才能新建文件夹!')
  2815. }
  2816. break;
  2817. case 1:
  2818. this.callFilePickerSelectFile()
  2819. break;
  2820. case 2:
  2821. this.showTips()
  2822. break;
  2823. case 3:
  2824. this.goSelectMusic()
  2825. break;
  2826. }
  2827. }
  2828. })
  2829. }
  2830. //拉起音频
  2831. goSelectMusic() {
  2832. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  2833. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  2834. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  2835. ) {
  2836. ToastUtil.showToast('暂时不支持该设备')
  2837. return
  2838. }
  2839. try {
  2840. let documentSelectOptions = new picker.DocumentSelectOptions();
  2841. documentSelectOptions.authMode = true
  2842. documentSelectOptions.multiAuthMode = true
  2843. if( deviceInfo.sdkApiVersion>=21){//如果api大于21 ,可以支持1w首歌以上
  2844. documentSelectOptions.maxSelectNumber = 20000
  2845. }
  2846. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  2847. let documentPicker = new picker.DocumentViewPicker(this.context);
  2848. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  2849. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  2850. this.saveVideoDatas(documentSelectResult)
  2851. }
  2852. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  2853. JSON.stringify(documentSelectResult));
  2854. }).catch((err: BusinessError) => {
  2855. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  2856. });
  2857. } catch (error) {
  2858. let err: BusinessError = error as BusinessError;
  2859. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2860. }
  2861. }
  2862. async showTips() {
  2863. try {
  2864. this.getUIContext().getPromptAction().showDialog({
  2865. title: '导入指南',
  2866. message:'用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  2867. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  2868. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  2869. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后去文件扫描一下。\n',
  2870. buttons: [
  2871. {
  2872. text: '知道了',
  2873. color: '#000000'
  2874. },
  2875. ]
  2876. }, (err, data) => {
  2877. if (err) {
  2878. console.error('showDialog err: ' + err);
  2879. return;
  2880. }
  2881. console.info('showDialog success callback, click button: ' + data.index);
  2882. });
  2883. } catch (error) {
  2884. let message = (error as BusinessError).message;
  2885. let code = (error as BusinessError).code;
  2886. console.error(`showDialog args error code is ${code}, message is ${message}`);
  2887. };
  2888. }
  2889. showMkDialog() {
  2890. DialogHelper.showTextInputDialog({
  2891. title: '新建歌单',
  2892. maskColor: Color.Transparent,
  2893. text: '',
  2894. transition: AnimationHelper.transitionInDown(666),
  2895. onChange: (text) => {
  2896. console.error("onChange: " + text);
  2897. },
  2898. onAction: (action, dialogId, content) => {
  2899. // ToastUtil.showToast('content = ' +content)
  2900. if (action == DialogAction.TWO) {
  2901. const newName = content
  2902. const newPath = this.currentPath + '/' + newName
  2903. FileUtil.mkdir(newPath, true).then(() => {
  2904. this.cache.delete(this.currentPath); // 删除目标路径缓存
  2905. this.getSortedFiles(this.currentPath)
  2906. }).catch((error: BusinessError) => {
  2907. console.error(error.message);
  2908. });
  2909. }
  2910. }
  2911. })
  2912. }
  2913. @State progress: number = 0;
  2914. async saveVideoDatas(uris:string[],isOpen?:boolean){
  2915. if (ArrayUtil.isEmpty(uris)) {
  2916. return;
  2917. }
  2918. console.info('onecold this.isCopyFileToDownLoad = ' + this.isCopyFileToDownLoad);
  2919. if(this.isCopyFileToDownLoad||this.currentPath==this.lockPath||isOpen){
  2920. this.saveVideoDatasToDownLoad(uris,isOpen)
  2921. return
  2922. }
  2923. // 初始化进度条
  2924. this.progress = 0;
  2925. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  2926. progress: this.progress,
  2927. backCancel: false,
  2928. autoCancel: false,
  2929. loadColor: $r('app.color.title_bar_bg'),
  2930. fontColor: $r('app.color.title_bar_bg')
  2931. });
  2932. // 计算处理总数用于进度计算
  2933. const totalItems = uris.length;
  2934. let processedItems = 0;
  2935. for (let i = 0; i < uris.length; i++) {
  2936. let filePath = uris[i];
  2937. try {
  2938. if (this.currentPath !== this.lockPath) { // 判断不是私密音乐,才入库
  2939. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2940. let mediaItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context,
  2941. filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2942. console.info('onecold saveVideoDatas filePath = ' + filePath)
  2943. if (!filePath.includes(this.rootPath)) {
  2944. console.info('onecold saveVideoDatas mediaItem.parentPath111 = ' + mediaItem.parentPath)
  2945. mediaItem.parentPath = this.currentPath;
  2946. }
  2947. console.info('onecold saveVideoDatas mediaItem.parentPath = ' + mediaItem.parentPath)
  2948. this.table.insert(mediaItem, (id: number) => {
  2949. // 插入完成回调
  2950. });
  2951. }
  2952. }
  2953. // 更新进度
  2954. processedItems++;
  2955. this.progress = Math.floor((processedItems / totalItems) * 100);
  2956. DialogHelper.updateLoading(this.loadingProgressDialogId,` 正在处理 ${this.progress}%`, this.progress);
  2957. } catch (error) {
  2958. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2959. // 即使出错也更新进度
  2960. processedItems++;
  2961. this.progress = Math.floor((processedItems / totalItems) * 100);
  2962. DialogHelper.updateLoading(this.loadingProgressDialogId,` 正在处理 ${this.progress}%`, this.progress);
  2963. }
  2964. }
  2965. // 关闭进度条
  2966. DialogHelper.closeDialog(this.loadingProgressDialogId)
  2967. this.isZero = false
  2968. // 删除目标路径缓存
  2969. setTimeout(() => {
  2970. this.cache.delete(this.currentPath);
  2971. this.getSortedFiles(this.currentPath,false,uris[0],isOpen)
  2972. this.setButtonStatus()
  2973. }, 500);
  2974. }
  2975. async saveVideoDatasToDownLoad(uris: string[], isOpen?: boolean) {
  2976. if (ArrayUtil.isEmpty(uris)) {
  2977. return;
  2978. }
  2979. let newUris: string[] = [];
  2980. this.progress = 0
  2981. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  2982. progress: this.progress,
  2983. backCancel: false,
  2984. autoCancel: false,
  2985. loadColor: this.themeColor,
  2986. fontColor: this.themeColor
  2987. });
  2988. // 计算所有文件的总大小
  2989. let totalSize = 0;
  2990. for (let uri of uris) {
  2991. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  2992. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  2993. await fileIo.close(sourceFile.fd);
  2994. }
  2995. let totalRead = 0;
  2996. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  2997. Logger.info(TAG, 'destPath uri: ' + destPath);
  2998. for (let i = 0; i < uris.length; i++) {
  2999. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  3000. Logger.info(TAG, 'filePath uri: ' + filePath);
  3001. newUris.push(filePath);
  3002. try {
  3003. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  3004. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  3005. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  3006. const buffer = new ArrayBuffer(buffSize);
  3007. let len = await fileIo.read(sourceFile.fd, buffer);
  3008. while (len > 0) {
  3009. await fileIo.write(destFile.fd, buffer.slice(0, len));
  3010. totalRead += len;
  3011. // 计算总进度
  3012. this.progress = Math.floor((totalRead / totalSize) * 100);
  3013. DialogHelper.updateLoading( this.loadingProgressDialogId,`正在导入 ${this.progress}%`, this.progress);
  3014. len = await fileIo.read(sourceFile.fd, buffer);
  3015. }
  3016. await fileIo.close(sourceFile.fd);
  3017. await fileIo.close(destFile.fd);
  3018. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  3019. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  3020. let mediaItem: VideoItem =
  3021. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3022. this.table.insert(mediaItem, (id: number) => {
  3023. // 删除目标路径缓存
  3024. this.cache.delete(this.currentPath);
  3025. this.getSortedFiles(this.currentPath, true, destPath, isOpen,mediaItem)
  3026. });
  3027. }
  3028. }
  3029. } catch (error) {
  3030. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  3031. }
  3032. }
  3033. DialogHelper.closeDialog(this.loadingProgressDialogId);
  3034. this.isZero = false
  3035. Logger.info(TAG, 'scan select video result:' + newUris)
  3036. }
  3037. //拉起音频
  3038. // goSelectMusic(){
  3039. //
  3040. // try {
  3041. // let audioSelectOptions = new picker.AudioSelectOptions();
  3042. // let audioPicker = new picker.AudioViewPicker(this.context);
  3043. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  3044. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  3045. // this.saveVideoDatas(audioSelectResult)
  3046. // }
  3047. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  3048. // }).catch((err: BusinessError) => {
  3049. //
  3050. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  3051. // });
  3052. // } catch (error) {
  3053. // let err: BusinessError = error as BusinessError;
  3054. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  3055. // }
  3056. //
  3057. //
  3058. //
  3059. // }
  3060. async goSelectImage(item: VideoItem): Promise<string | undefined> {
  3061. if (!item) {
  3062. return undefined;
  3063. }
  3064. try {
  3065. let selectUris: Array<string> = [];
  3066. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  3067. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  3068. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  3069. photoSelectOptions.maxSelectNumber = 1;
  3070. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  3071. selectUris = photoSelectResult.photoUris;
  3072. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  3073. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  3074. console.info('file fd: ' + file.fd);
  3075. let name = await MD5.digestSync(this.videoUrl)+'.jpg'
  3076. let imagePath = this.context.filesDir + FileUtil.separator + name
  3077. imagePath = fileUri.getUriFromPath(imagePath)
  3078. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  3079. fileIo.copyFileSync(file.fd, file2.fd)
  3080. fileIo.closeSync(file);
  3081. fileIo.closeSync(file2);
  3082. if (item.filePath == this.currentSong?.filePath) {
  3083. this.cover = imagePath
  3084. if (this.currentSong) {
  3085. this.currentSong.isCustomCover = 1;
  3086. }
  3087. }
  3088. if (item) {
  3089. item.pixelMapPath = imagePath
  3090. item.isCustomCover = 1;
  3091. }
  3092. if (isRemoteCloudType(item.type)) {
  3093. return FileUtil.getFilePath(imagePath);
  3094. }
  3095. this.table.updateCustomCoverPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  3096. if (success) {
  3097. this.doUpdateData()
  3098. console.log("onecold 更新音乐封面成功,数据库已同步");
  3099. } else {
  3100. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  3101. }
  3102. });
  3103. LogUtil.debug("onecold this.cover =" + this.cover)
  3104. return FileUtil.getFilePath(imagePath); // Return the image path here
  3105. } catch (err) {
  3106. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  3107. return undefined;
  3108. }
  3109. }
  3110. private async pickCoverImageToSandbox(): Promise<string | undefined> {
  3111. try {
  3112. const photoPicker = new photoAccessHelper.PhotoViewPicker();
  3113. const photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  3114. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  3115. photoSelectOptions.maxSelectNumber = 1;
  3116. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  3117. const selectUris = photoSelectResult.photoUris;
  3118. if (!selectUris || selectUris.length === 0) {
  3119. return undefined;
  3120. }
  3121. const coverDir = this.context.filesDir + FileUtil.separator + 'ttmusic_cover';
  3122. if (!FileUtil.accessSync(coverDir)) {
  3123. FileUtil.mkdirSync(coverDir);
  3124. }
  3125. const sourceUri = selectUris[0];
  3126. const sourceName = FileUtil.getFileName(sourceUri) || '';
  3127. let suffix = '.jpg';
  3128. const dotIndex = sourceName.lastIndexOf('.');
  3129. if (dotIndex >= 0) {
  3130. suffix = sourceName.substring(dotIndex);
  3131. }
  3132. const targetName = `${Date.now()}_${await MD5.digestSync(sourceUri)}${suffix}`;
  3133. const targetPath = coverDir + FileUtil.separator + targetName;
  3134. const sourceFile = fileIo.openSync(sourceUri, fileIo.OpenMode.READ_ONLY);
  3135. const targetFile = fileIo.openSync(targetPath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
  3136. fileIo.copyFileSync(sourceFile.fd, targetFile.fd);
  3137. fileIo.closeSync(sourceFile.fd);
  3138. fileIo.closeSync(targetFile.fd);
  3139. return fileUri.getUriFromPath(targetPath);
  3140. } catch (error) {
  3141. const err = error as BusinessError;
  3142. Logger.error(TAG, `pickCoverImageToSandbox failed, code: ${err.code}, message: ${err.message}`);
  3143. return undefined;
  3144. }
  3145. }
  3146. private async replaceCurrentSongCoverByAlbum(): Promise<void> {
  3147. if (!this.currentSong || StrUtil.isEmpty(this.currentSong.filePath)) {
  3148. ToastUtil.showToast('当前歌曲无效');
  3149. return;
  3150. }
  3151. const sandboxCoverUri = await this.pickCoverImageToSandbox();
  3152. if (StrUtil.isEmpty(sandboxCoverUri)) {
  3153. return;
  3154. }
  3155. const coverUri = sandboxCoverUri as string;
  3156. this.loadingDialogId = DialogHelper.showLoadingDialog();
  3157. try {
  3158. if (isRemoteCloudType(this.currentSong.type)) {
  3159. this.cover = coverUri;
  3160. this.currentSong.pixelMapPath = coverUri;
  3161. this.currentSong.isCustomCover = 1;
  3162. this.syncRemoteManagerSong(this.currentSong);
  3163. await this.persistRemoteMetadataToDb(this.currentSong);
  3164. this.emitRemoteMetadataUpdated(this.currentSong);
  3165. this.currentSong = cloneVideoItem(this.currentSong);
  3166. AppStorage.setOrCreate('currentSong', this.currentSong);
  3167. ToastUtil.showToast('更换封面成功');
  3168. return;
  3169. }
  3170. if (this.currentSong.type !== CommonConstants.TYPE_LOCAL) {
  3171. ToastUtil.showToast('当前歌曲类型暂不支持更换封面');
  3172. return;
  3173. }
  3174. const task = new taskpool.Task(
  3175. replaceLocalMusicCoverTask,
  3176. this.context,
  3177. this.currentSong.filePath,
  3178. FileUtil.getFilePath(coverUri)
  3179. );
  3180. const result = await taskpool.execute(task, taskpool.Priority.HIGH) as boolean;
  3181. if (!result) {
  3182. ToastUtil.showToast('更换封面失败');
  3183. return;
  3184. }
  3185. this.cover = coverUri;
  3186. this.currentSong.pixelMapPath = coverUri;
  3187. this.currentSong.isCustomCover = 1;
  3188. await this.doUpateEditedFields(this.currentSong);
  3189. ToastUtil.showToast('更换封面成功');
  3190. } catch (error) {
  3191. Logger.error(TAG, `replaceCurrentSongCoverByAlbum failed: ${JSON.stringify(error)}`);
  3192. ToastUtil.showToast('更换封面失败');
  3193. } finally {
  3194. DialogHelper.closeDialog(this.loadingDialogId);
  3195. }
  3196. }
  3197. // 拉起picker选择文件管理器
  3198. async callFilePickerSelectFile(): Promise<void> {
  3199. try {
  3200. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  3201. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  3202. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  3203. } else {
  3204. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  3205. }
  3206. let documentPicker = new picker.DocumentViewPicker();
  3207. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  3208. Logger.info(TAG,
  3209. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  3210. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  3211. this.saveVideoDatas(DocumentSelectResult)
  3212. }
  3213. }).catch((err: BusinessError) => {
  3214. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  3215. });
  3216. } catch (err) {
  3217. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  3218. }
  3219. }
  3220. //重命名的对话框
  3221. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  3222. if(!item.filePath.includes(this.packName)){
  3223. ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限重命名')
  3224. return
  3225. }
  3226. DialogHelper.showTextInputDialog({
  3227. title: '重命名',
  3228. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : (item.fileName || item.name),
  3229. maskColor: Color.Transparent,
  3230. backgroundColor: Color.Grey,
  3231. transition: AnimationHelper.transitionInDown(666),
  3232. onChange: (text) => {
  3233. console.error("onChange: " + text);
  3234. },
  3235. onAction: (action, dialogId, content) => {
  3236. // ToastUtil.showToast('content = ' +content)
  3237. if (action == DialogAction.TWO) {
  3238. const newName = content
  3239. const newPath = this.currentPath + '/' + newName
  3240. console.log("onecold item = " + item.type);
  3241. this.doReName(index, newName, filePath, newPath, item)
  3242. }
  3243. }
  3244. })
  3245. }
  3246. //剪切 移动到另个文件夹的对话框
  3247. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  3248. Logger.info('onecold showCutDialog')
  3249. let mList: Array<string> = []
  3250. let rPath = this.rootPath
  3251. if (isCurrent) {
  3252. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  3253. rPath = this.currentPath
  3254. } else {
  3255. mList = Utility.getNameList(this.dirList);
  3256. rPath = this.rootPath
  3257. }
  3258. let dataBean = new BubbleBean()
  3259. dataBean.data = mList
  3260. dataBean.color = this.themeColor
  3261. dataBean.onItemClick = (i) => {
  3262. const targetName = item.fileName || item.name
  3263. const newPath = rPath + '/' + mList[i] + '/' + targetName
  3264. Logger.info('newPath = ' + newPath)
  3265. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  3266. ToastUtil.showToast('移动成功')
  3267. this.table.deleteData(item, () => {
  3268. });
  3269. if (!Utility.isIsoByExtension(newPath)) {
  3270. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  3271. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3272. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  3273. this.table.insert(newItem, (id: number) => {
  3274. //加入数据库
  3275. });
  3276. }
  3277. }
  3278. this.cache.delete(this.currentPath); // 删除原路径缓存
  3279. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  3280. this.getSortedFiles(this.currentPath, true)
  3281. }).catch((error: BusinessError) => {
  3282. console.error(error.message);
  3283. });
  3284. XPopup.dismissTop()
  3285. }
  3286. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  3287. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  3288. popupPosition = PopupPosition.TOP
  3289. }
  3290. if (index <= 3) {
  3291. popupPosition = PopupPosition.BOTTOM
  3292. }
  3293. let pup: XPopup
  3294. if (this.isDarkMode) {
  3295. pup = XPopup.Builder()
  3296. .setPopupPosition(popupPosition)
  3297. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  3298. .setBackgroundColor(Color.Black)
  3299. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3300. .show()
  3301. } else {
  3302. pup = XPopup.Builder()
  3303. .setPopupPosition(popupPosition)
  3304. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  3305. .setBackgroundColor(Color.White)
  3306. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3307. .show()
  3308. }
  3309. }
  3310. //复制 到另个文件夹的对话框
  3311. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  3312. Logger.info('onecoldv showCopyDialog')
  3313. let mList: Array<string> = []
  3314. let rPath = this.rootPath
  3315. if (isCurrent) {
  3316. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  3317. rPath = this.currentPath
  3318. } else {
  3319. mList = Utility.getNameList(this.dirList);
  3320. rPath = this.rootPath
  3321. }
  3322. let dataBean = new BubbleBean()
  3323. dataBean.data = mList
  3324. dataBean.isCopy = true
  3325. dataBean.color = this.themeColor
  3326. dataBean.onItemClick = (i) => {
  3327. const targetName = item.fileName || item.name
  3328. const newPath = rPath + '/' + mList[i] + '/' + targetName
  3329. Logger.info('newPath = ' + newPath)
  3330. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  3331. ToastUtil.showToast('复制成功')
  3332. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  3333. this.getSortedFiles(this.currentPath)
  3334. if (!Utility.isIsoByExtension(newPath)) {
  3335. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  3336. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3337. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  3338. this.table.insert(newItem, (id: number) => {
  3339. //加入数据库
  3340. });
  3341. }
  3342. }
  3343. }).catch((error: BusinessError) => {
  3344. console.error(error.message);
  3345. });
  3346. XPopup.dismissTop()
  3347. }
  3348. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  3349. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  3350. popupPosition = PopupPosition.TOP
  3351. }
  3352. if (index <= 3) {
  3353. popupPosition = PopupPosition.BOTTOM
  3354. }
  3355. let pup: XPopup
  3356. if (this.isDarkMode) {
  3357. pup = XPopup.Builder()
  3358. .setPopupPosition(popupPosition)
  3359. .atView(id)
  3360. .setMaxHeight('60%')
  3361. .setBackgroundColor(Color.Black)
  3362. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3363. .show();
  3364. } else {
  3365. pup = XPopup.Builder()
  3366. .setPopupPosition(popupPosition)
  3367. .atView(id)
  3368. .setMaxHeight('60%')
  3369. .setBackgroundColor(Color.White)
  3370. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3371. .show();
  3372. }
  3373. }
  3374. //重命名索引index的视频
  3375. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  3376. FileUtil.rename(oldPath, newPath).then(async () => {
  3377. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  3378. let refreshedItem: VideoItem = info
  3379. if (info.type === CommonConstants.TYPE_IS_DIR) {
  3380. //如果是文件夹先删除源数据,再添加新数据
  3381. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  3382. if (success) {
  3383. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  3384. } else {
  3385. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  3386. }
  3387. });
  3388. this.scanDirectory(newPath)
  3389. refreshedItem = new VideoItem(newName, newName, newPath, CommonConstants.TYPE_IS_DIR, 0, '')
  3390. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  3391. if (Utility.isIsoByExtension(oldPath) || Utility.isIsoByExtension(newPath)) {
  3392. refreshedItem = this.buildLocalIsoItem(newPath, newName)
  3393. } else {
  3394. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  3395. if (success) {
  3396. console.log(" onecold 重命名成功,数据库已同步");
  3397. } else {
  3398. console.error(" onecold 重命名数据库失败原因: " + error);
  3399. }
  3400. });
  3401. refreshedItem =
  3402. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3403. }
  3404. } else {
  3405. return
  3406. }
  3407. this.videoLocalList[index] = refreshedItem;
  3408. }
  3409. this.cache.delete(this.currentPath)
  3410. this.cache.delete(oldPath)
  3411. this.cache.delete(newPath)
  3412. this.getSortedFiles(this.currentPath, true)
  3413. }).catch((error: BusinessError) => {
  3414. console.error(error.message);
  3415. });
  3416. }
  3417. build() {
  3418. Stack() {
  3419. if (this.mType === 0) {
  3420. this.ContentBuild()
  3421. }
  3422. Stack() {
  3423. Column()
  3424. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  3425. height: '95%',
  3426. dragBar: true,
  3427. showClose: true,
  3428. blurStyle: BlurStyle.Thin,
  3429. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3430. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  3431. title: {
  3432. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  3433. + `(${this.getPlayListDisplayCount()}首)`
  3434. }
  3435. })
  3436. }
  3437. if (this.isShowPlay) {
  3438. Stack() {
  3439. this.MusicPlayBuilder()
  3440. }
  3441. .width('100%')
  3442. .height('100%')
  3443. .zIndex(99)
  3444. }
  3445. }
  3446. .alignContent(Alignment.Bottom)
  3447. .width('100%')
  3448. .height('100%')
  3449. }
  3450. @Builder
  3451. ContentBuild() {
  3452. Scroll() {
  3453. Column() {
  3454. Stack() {
  3455. //libraryname加上去后onKeyEvent监听不了,因为目前的解决方案是上面的XComponent,去掉libraryname
  3456. XComponent({ id: 'for_onKeyEvent',type: XComponentType.SURFACE,
  3457. controller: this.xcomponentController })
  3458. .onLoad(async (event?: object) => {
  3459. })
  3460. .focusable(true)
  3461. .height(0)
  3462. .focusOnTouch(true)
  3463. .defaultFocus(true) // 自动获取键盘焦点
  3464. .onKeyEvent((event?: KeyEvent) => {
  3465. console.info('onecold点击 onKeyEvent')
  3466. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  3467. if (!event || event.type !== KeyType.Down) {
  3468. return;
  3469. }
  3470. console.info('onecold点击 onKeyEvent event.keyCode: ' + event.keyCode)
  3471. //空格键 Space key controls pause/play
  3472. if (event.keyCode === KeyCode.KEYCODE_SPACE|| event.keyCode === KeyCode.KEYCODE_MEDIA_PLAY_PAUSE) {
  3473. this.playOrPause()
  3474. }
  3475. if (event.keyCode === KeyCode.KEYCODE_DPAD_UP) {
  3476. this.playPrevious()
  3477. }
  3478. if (event.keyCode === KeyCode.KEYCODE_DPAD_DOWN) {
  3479. this.playNext()
  3480. }
  3481. // Right-click to fast forward
  3482. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  3483. this.fastForward()
  3484. }
  3485. // Left-click to rewind
  3486. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  3487. this.backForward()
  3488. }
  3489. })
  3490. Column() {
  3491. XComponent({
  3492. id: 'xcomponentId',
  3493. type: 'surface',
  3494. libraryname: 'ijkplayer_napi',
  3495. controller: this.xcomponentController
  3496. })
  3497. .onLoad((event?: object) => {
  3498. if (!!event) {
  3499. this.initDelayPlay(event);
  3500. }
  3501. })
  3502. .onDestroy(() => {
  3503. })
  3504. .width('100%')// .width(this.videoWidth)
  3505. .aspectRatio(this.videoAspectRatio)
  3506. }
  3507. .aspectRatio(this.videoAspectRatio)
  3508. .justifyContent(FlexAlign.Center)
  3509. .backgroundColor(Color.Transparent)
  3510. .visibility(Visibility.Hidden)
  3511. .height(CommonConstants.FULL_PERCENT)
  3512. .width(CommonConstants.FULL_PERCENT)
  3513. .bindSheet($$this.isABSheet, this.ABLoopSheet(), {
  3514. height:this.isLandscape?'80%': '43%',
  3515. dragBar: true,
  3516. showClose: true,
  3517. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3518. blurStyle:BlurStyle.Thin,
  3519. backgroundColor:Color.Transparent,
  3520. title: { title: 'AB循环' }
  3521. })
  3522. Stack() {
  3523. Column() {
  3524. if(this.twoFingerType==4){
  3525. this.getWaterView()
  3526. }else{
  3527. if(this.isGridMusic){
  3528. this.getGridView()
  3529. }else {
  3530. this.getListView()
  3531. }
  3532. }
  3533. if (this.modeType ==0||this.modeType==4) {
  3534. Column() {
  3535. emptyView(this.themeColor)
  3536. }
  3537. .padding({ right:6 })
  3538. .onClick(()=>{
  3539. this.asyncCurrentPathOnlyFile()
  3540. })
  3541. .alignItems(HorizontalAlign.Center)
  3542. .position({ top: 200 })
  3543. .justifyContent(FlexAlign.Center)
  3544. .opacity(this.isZero ? 1 : 0)
  3545. .visibility(this.isZero&&!this.isLoadingPage && !this.isFavMusic && !this.isHistory
  3546. ? Visibility.Visible : Visibility.None)
  3547. .animation({
  3548. duration: 500,
  3549. curve: Curve.Friction // 可选动画曲线
  3550. })
  3551. .width('100%')
  3552. }
  3553. }
  3554. .layoutWeight(1)
  3555. .height('100%')
  3556. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  3557. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3558. .onDrop((event?: DragEvent) => {
  3559. try {
  3560. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3561. if (dragData !== undefined) {
  3562. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3563. if (records.length > 0) {
  3564. for (let i = 0; i < records.length; i++) {
  3565. let types = records[i].getTypes();
  3566. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3567. const fileUriUds =
  3568. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3569. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3570. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3571. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3572. this.targetFile = fileUriUds.oriUri;
  3573. this.saveVideoDatas([this.targetFile])
  3574. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3575. }
  3576. }
  3577. }
  3578. } else {
  3579. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3580. }
  3581. } else {
  3582. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3583. }
  3584. } catch (error) {
  3585. const err = error as BusinessError;
  3586. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3587. }
  3588. })
  3589. // 右侧居中的字母表索引
  3590. this.indexBuilder()
  3591. this.topTitleBar()
  3592. }
  3593. .alignContent(Alignment.Top)
  3594. .layoutWeight(1)
  3595. .height('100%')
  3596. Row() {
  3597. Button(this.isAllSelected ? '反选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  3598. .width(45)
  3599. .height(45)
  3600. .fontSize(10)
  3601. .margin({ top: 10, bottom: 10, right: 6 })
  3602. .backgroundColor(this.themeColor)
  3603. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3604. .onClick(() => {
  3605. if (this.isAllSelected) {
  3606. // 全不选
  3607. this.selectedFiles = [];
  3608. } else {
  3609. // 全选
  3610. this.selectedFiles = [...this.getCurFileList()];
  3611. }
  3612. this.syncLocalSelectionState();
  3613. })
  3614. Button('内嵌标签', { type: ButtonType.Capsule, stateEffect: true })
  3615. .width(72)
  3616. .height(45)
  3617. .fontSize(10)
  3618. .margin({ top: 10, bottom: 10, right: 6 })
  3619. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3620. .backgroundColor(this.themeColor)
  3621. .enabled(!this.hasSelectedDirectories() && this.getSelectedPlayableFiles().length > 0)
  3622. .bindContentCover($$this.isOneKeyTags, this.TagsContentCoverBuilder(), {
  3623. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3624. })
  3625. .onClick(() => {
  3626. if (this.hasSelectedDirectories()) {
  3627. ToastUtil.showToast('文件夹不支持批量内嵌标签')
  3628. return
  3629. }
  3630. this.isOneKeyTags = !this.isOneKeyTags
  3631. })
  3632. Button('合并', { type: ButtonType.Circle, stateEffect: true })
  3633. .width(45)
  3634. .height(45)
  3635. .fontSize(10)
  3636. .margin({ top: 10, bottom: 10, right: 6 })
  3637. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3638. .backgroundColor(this.themeColor)
  3639. .enabled(!this.hasSelectedDirectories() && this.getSelectedPlayableFiles().length > 0)
  3640. .bindContentCover($$this.isMergeAudio, this.MergeAudioBuilder(), {
  3641. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3642. })
  3643. .onClick(() => {
  3644. const selectedMediaFiles = this.getSelectedPlayableFiles()
  3645. if (this.hasSelectedDirectories()) {
  3646. ToastUtil.showToast('文件夹不支持合并')
  3647. return
  3648. }
  3649. if(ArrayUtil.isNotEmpty(selectedMediaFiles)&&Utility.isMerge(selectedMediaFiles,this.packName)){
  3650. this.isMergeAudio = !this.isMergeAudio
  3651. }else{
  3652. ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限合并')
  3653. }
  3654. })
  3655. Button('+歌单', { type: ButtonType.Circle, stateEffect: true })
  3656. .width(45)
  3657. .height(45)
  3658. .fontSize(10)
  3659. .margin({ top: 10, bottom: 10, right: 6 })
  3660. .backgroundColor(this.themeColor)
  3661. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3662. .enabled(!this.hasSelectedDirectories() && this.getSelectedPlayableFiles().length > 0)
  3663. .onClick(async () => {
  3664. this.longItemFilePath = ''
  3665. const selectedMediaFiles = this.getSelectedPlayableFiles()
  3666. if (ArrayUtil.isEmpty(selectedMediaFiles)) {
  3667. ToastUtil.showToast('请先选择音频文件')
  3668. return
  3669. }
  3670. await this.openAddToPlaylistDialog(selectedMediaFiles)
  3671. })
  3672. // Button('乱码', { type: ButtonType.Circle, stateEffect: true })
  3673. // .width(45)
  3674. // .height(45)
  3675. // .fontSize(10)
  3676. // .margin({ top: 10, bottom: 10, right: 6 })
  3677. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3678. // .backgroundColor(this.themeColor)
  3679. // .bindContentCover($$this.isFixMessy, this.FixMessyViewBuilder(), {
  3680. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3681. // })
  3682. // .onClick(() => {
  3683. // this.isFixMessy = !this.isFixMessy
  3684. // })
  3685. // Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  3686. // .width('35%')
  3687. // .height(60)
  3688. // .id('music_cut')
  3689. // .margin({ top: 10, bottom: 10, right: 6 })
  3690. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3691. // .backgroundColor(this.themeColor)
  3692. // .onClick(() => {
  3693. // this.showCutDialogForMultipleFiles(false, 'music_cut')
  3694. // })
  3695. //
  3696. // Button('移动', { type: ButtonType.Circle, stateEffect: true })
  3697. // .width('35%')
  3698. // .height(60)
  3699. // .id('music_cut_current')
  3700. // .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  3701. // .margin({ top: 10, bottom: 10, right: 6 })
  3702. // .backgroundColor(this.themeColor)
  3703. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3704. // .onClick(() => {
  3705. //
  3706. // this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  3707. // })
  3708. // Button('复制', { type: ButtonType.Circle, stateEffect: true })
  3709. // .width('35%')
  3710. // .height(60)
  3711. // .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  3712. // .margin({ top: 10, bottom: 10, right: 6 })
  3713. // .backgroundColor(this.themeColor)
  3714. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3715. // .onClick(() => {
  3716. // this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  3717. // })
  3718. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  3719. .width(45)
  3720. .height(45)
  3721. .fontSize(10)
  3722. .margin({ top: 10, bottom: 10, right: 6 })
  3723. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  3724. .backgroundColor(this.themeColor)
  3725. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3726. .onClick(() => {
  3727. this.showWarnIsDelete()
  3728. })
  3729. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  3730. .width(45)
  3731. .height(45)
  3732. .fontSize(10)
  3733. .margin({ top: 10, bottom: 10, right: 6 })
  3734. .backgroundColor(this.themeColor)
  3735. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3736. .onClick(() => {
  3737. this.selectedFiles = [];
  3738. this.isAllSelected = false
  3739. this.isMultiSelect = false
  3740. })
  3741. }
  3742. .width('100%')
  3743. .justifyContent(FlexAlign.Center)
  3744. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  3745. .opacity(this.isMultiSelect ? 1 : 0)
  3746. .animation({
  3747. duration: 666,
  3748. curve: 'ease-in-out' // 可选动画曲线
  3749. })
  3750. .position({ bottom: 20 }) // 将 Row 固定在底部
  3751. }
  3752. .width('100%')
  3753. .height('100%')
  3754. .alignContent(Alignment.Top)
  3755. }
  3756. .width('100%')
  3757. .height('100%')
  3758. .backgroundImage(this.isMusicCoverHomeBackgroundActive()
  3759. ? this.customizeMusicBgPath
  3760. : (this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background')))
  3761. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  3762. .backgroundImagePosition(Alignment.Center)
  3763. .backdropBlur(this.blurValue)
  3764. .backgroundBrightness({ rate: this.isMusicCoverHomeBackgroundActive() || this.isCustomizeBg ? 0.1 : 0,
  3765. lightUpDegree: this.bgBrightness })
  3766. .backgroundBlurStyle(this.isMusicCoverHomeBackgroundActive()
  3767. ? BlurStyle.BACKGROUND_ULTRA_THICK :
  3768. BlurStyle.NONE)
  3769. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  3770. }
  3771. }
  3772. //字母表索引
  3773. @Builder
  3774. indexBuilder(){
  3775. Column({space: 5}){
  3776. if(this.showZMIndex&&this.enableShowAlphabet){
  3777. if(this.isShowAlphaBet&&!(this.modeType==2&&!this.isCanBack)
  3778. &&!(this.modeType==3&&!this.isCanBack)&&(this.sortType==4||this.sortType==5)){
  3779. AlphabetIndexer({arrayValue: this.alphaBet,selected: this.selectAlphaBetIndex})
  3780. .attributeModifier(this.alphaBetStyle)
  3781. .usingPopup(this.isTouchingAlphaBet)
  3782. .onAreaChange((old_value,new_value)=>{
  3783. this.alphabetHeight = new_value.height as number
  3784. })
  3785. .popupPosition({
  3786. x: 40,
  3787. y: this.alphabetHeight / 2
  3788. })
  3789. .onSelect((index: number) => {
  3790. void this.onSelectIndexItem(this.alphaBet[index])
  3791. })
  3792. .onTouch((event: TouchEvent) =>{
  3793. this.showAlphabetIndex()
  3794. if(event.type === TouchType.Up || event.type === TouchType.Cancel){
  3795. this.isTouchingAlphaBet = false
  3796. this.hideAlphabetIndexAfterDelay(1500)
  3797. }else{
  3798. this.isTouchingAlphaBet = true
  3799. }
  3800. })
  3801. .transition(
  3802. TransitionEffect.translate({x: 10})
  3803. .combine(TransitionEffect.opacity(0.1))
  3804. .animation({
  3805. duration: 150,
  3806. curve: Curve.EaseInOut,
  3807. })
  3808. )
  3809. }
  3810. }
  3811. if(this.showFindLocation){
  3812. if(!(this.showZMIndex&&this.enableShowAlphabet)){
  3813. Blank()
  3814. .layoutWeight(1)
  3815. }
  3816. PointLightDefaultButton({
  3817. isSysBol:true,
  3818. pointColor:Color.Gray,
  3819. imageResource:$r('sys.symbol.local_fill'),
  3820. isPx: false,
  3821. builderHeight: 30,
  3822. builderWidth: 30,
  3823. })
  3824. .onClick(() =>{
  3825. void this.locateCurrentSong();
  3826. })
  3827. .clickEffect({level:ClickEffectLevel.LIGHT,scale: 0.5})
  3828. .margin({
  3829. bottom: this.bottomSafeHeight+100,right:10
  3830. })
  3831. }
  3832. }
  3833. .padding({
  3834. bottom: 0
  3835. })
  3836. .margin({right:5})
  3837. .position({x:'92%'})
  3838. .height('100%')
  3839. .justifyContent(FlexAlign.Center)
  3840. .bindSheet($$this.isEqualizerSheet, this.EqualizerSheet(), {
  3841. height: '100%',
  3842. dragBar: true,
  3843. showClose: true,
  3844. preferType: SheetType.CENTER ,
  3845. blurStyle: BlurStyle.Thin,
  3846. title: { title: '均衡器' },
  3847. onDisappear: () => {
  3848. this.isEqualizerSheet = false
  3849. }
  3850. })
  3851. }
  3852. async onSelectIndexItem(letter: string) {
  3853. await this.ensureFullListForAlphabetIndex();
  3854. const findTargetIndex = (): number => {
  3855. const songs = this.videoLocalList;
  3856. for (let i = 0; i < songs.length; i++) {
  3857. const song = songs[i];
  3858. let text = this.isShowFileName ? song.fileName :
  3859. (song.type != CommonConstants.TYPE_IS_DIR && song.pyStr) ? song.pyStr : song.name;
  3860. if (this.sortType === 0 || this.sortType == 1) {
  3861. text = song.artist;
  3862. } else if (this.sortType === 2 || this.sortType == 3) {
  3863. text = song.album;
  3864. }
  3865. if (text) {
  3866. const firstPinyin = getFirstLetter(text);
  3867. if (firstPinyin && firstPinyin === letter) {
  3868. return i;
  3869. }
  3870. }
  3871. }
  3872. return -1;
  3873. };
  3874. const targetIndex = findTargetIndex();
  3875. if (targetIndex !== -1) {
  3876. if (this.isGridMusic || this.twoFingerType == 4) {
  3877. this.scroller.scrollToIndex(targetIndex, false);
  3878. } else {
  3879. this.listScroller.scrollToIndex(targetIndex);
  3880. }
  3881. }
  3882. }
  3883. private showAlphabetIndex(): void {
  3884. this.isShowAlphaBet = true;
  3885. if (this.alphaBetHideTimer) {
  3886. clearTimeout(this.alphaBetHideTimer);
  3887. this.alphaBetHideTimer = 0;
  3888. }
  3889. }
  3890. private hideAlphabetIndexAfterDelay(delayMs: number): void {
  3891. if (this.alphaBetHideTimer) {
  3892. clearTimeout(this.alphaBetHideTimer);
  3893. }
  3894. this.alphaBetHideTimer = setTimeout(() => {
  3895. if (!this.isTouchingAlphaBet) {
  3896. this.isShowAlphaBet = false;
  3897. }
  3898. this.alphaBetHideTimer = 0;
  3899. }, delayMs) as number;
  3900. }
  3901. private scheduleAlphaBetRebuild(delayMs: number = 120): void {
  3902. if (!this.showZMIndex) {
  3903. return;
  3904. }
  3905. if (this.alphaBetRebuildTimer) {
  3906. clearTimeout(this.alphaBetRebuildTimer);
  3907. }
  3908. this.alphaBetRebuildTimer = setTimeout(() => {
  3909. this.alphaBetRebuildTimer = 0;
  3910. if (this.isScrolling) {
  3911. this.alphaBetDirty = true;
  3912. return;
  3913. }
  3914. this.alphaBetDirty = false;
  3915. void this.setAlphaBet();
  3916. }, delayMs) as number;
  3917. }
  3918. private markAlphaBetDirty(): void {
  3919. if (!this.showZMIndex) {
  3920. return;
  3921. }
  3922. if (this.isMediaLibraryWarmupWindow()) {
  3923. this.alphaBetDirty = true;
  3924. this.scheduleAlphaBetRebuild(900);
  3925. return;
  3926. }
  3927. this.alphaBetDirty = true;
  3928. if (!this.isScrolling) {
  3929. this.scheduleAlphaBetRebuild(80);
  3930. }
  3931. }
  3932. private async ensureFullListForAlphabetIndex(): Promise<void> {
  3933. if (this.isLoadingPage) {
  3934. return;
  3935. }
  3936. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  3937. return;
  3938. }
  3939. if (this.totalCount === 0 || this.videoLocalList.length >= this.totalCount) {
  3940. return;
  3941. }
  3942. if (this.modeType !== 0 && this.modeType !== 1) {
  3943. return;
  3944. }
  3945. this.isLoadingPage = true;
  3946. try {
  3947. const options: PageQueryOptions = {
  3948. pageIndex: 0,
  3949. pageSize: this.totalCount,
  3950. sortType: this.sortType,
  3951. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  3952. isShowFileName: this.isShowFileName
  3953. };
  3954. if (this.modeType === 0) {
  3955. options.parentPath = this.currentPath;
  3956. }
  3957. let result: PageQueryResult;
  3958. if (this.modeType === 0) {
  3959. result = await this.table.queryByParentPathPaged(options);
  3960. const dbItems = this.filterOutLocalIsoItems(result.items);
  3961. if (!this.isSearchMode) {
  3962. const directories: VideoItem[] = await this.loadDirectories(this.currentPath);
  3963. const isoItems: VideoItem[] = this.getLocalIsoItems(this.currentPath);
  3964. result.items = [...directories, ...isoItems, ...dbItems];
  3965. } else {
  3966. result.items = dbItems;
  3967. }
  3968. } else {
  3969. result = await this.table.queryMediaLibraryPaged(options);
  3970. }
  3971. this.videoLocalList = result.items;
  3972. this.dataSource.pushArrayData(this.videoLocalList);
  3973. this.pageCache.clear();
  3974. this.pageHasMoreCache.clear();
  3975. this.pageTotalCountCache.clear();
  3976. this.prefetchingPages.clear();
  3977. this.currentPage = 0;
  3978. this.totalCount = this.modeType === 0 ? result.items.length : result.totalCount;
  3979. this.hasMoreData = false;
  3980. this.lastScrollTriggerPage = -1;
  3981. this.lastVisibleEndIndex = -1;
  3982. this.isPagingTransition = false;
  3983. if (this.pagingScheduleTimer) {
  3984. clearTimeout(this.pagingScheduleTimer);
  3985. this.pagingScheduleTimer = 0;
  3986. }
  3987. if (this.modeType === 1) {
  3988. this.mediaKuCount = result.totalCount;
  3989. }
  3990. this.setButtonStatus();
  3991. this.markAlphaBetDirty();
  3992. } catch (err) {
  3993. const error = err as Error;
  3994. Logger.warn('heanup LocalMusic', `ensureFullListForAlphabetIndex error: ${error.message}`);
  3995. } finally {
  3996. this.isLoadingPage = false;
  3997. }
  3998. }
  3999. // 找到对应字母表的索引
  4000. findAlphaBetIndex(song: VideoItem):number{
  4001. let text = this.isShowFileName?song.fileName:
  4002. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  4003. if(this.sortType === 0||this.sortType==1){
  4004. text = song.artist
  4005. }else if(this.sortType === 2||this.sortType==3){
  4006. text = song.album
  4007. }
  4008. if(text){
  4009. let firstLetter = getFirstLetter(text)
  4010. for(let i=0;i<this.alphaBet.length;i++){
  4011. if(this.alphaBet[i] === firstLetter){
  4012. return i
  4013. }
  4014. }
  4015. }
  4016. return 0
  4017. }
  4018. private buildAlphaTaskItems(songs: Array<VideoItem>): Array<AlphaTaskItem> {
  4019. const items: Array<AlphaTaskItem> = []
  4020. for (const song of songs) {
  4021. items.push({
  4022. type: song.type,
  4023. name: song.name,
  4024. pyStr: song.pyStr,
  4025. fileName: song.fileName,
  4026. artist: song.artist,
  4027. album: song.album
  4028. })
  4029. }
  4030. return items
  4031. }
  4032. private async buildAlphaBetByTask(songs: Array<VideoItem>, version: number): Promise<void> {
  4033. const taskItems = this.buildAlphaTaskItems(songs)
  4034. const task = new taskpool.Task(buildAlphabetIndexTask, taskItems, this.sortType, this.isShowFileName)
  4035. const result = await taskpool.execute(task, taskpool.Priority.MEDIUM) as Array<string>
  4036. if (version !== this.alphaBetBuildVersion) {
  4037. return
  4038. }
  4039. this.alphaBet = result
  4040. if (this.videoLocalList.length > 0) {
  4041. this.selectAlphaBetIndex = 0
  4042. }
  4043. }
  4044. async setAlphaBet(){
  4045. if(!this.showZMIndex){
  4046. return
  4047. }
  4048. if (this.modeType === 1 && this.totalCount > this.videoLocalList.length) {
  4049. await this.refreshAlphaBetFromMediaLibrary()
  4050. return
  4051. }
  4052. try {
  4053. const songs = this.videoLocalList
  4054. if (songs.length > 40000) {
  4055. this.alphaBet = []
  4056. return
  4057. }
  4058. const version = ++this.alphaBetBuildVersion
  4059. await this.buildAlphaBetByTask(songs, version)
  4060. } catch (e) {
  4061. console.error('testTag','排序字母表出错',JSON.stringify(e))
  4062. }
  4063. }
  4064. private async refreshAlphaBetFromMediaLibrary(): Promise<void> {
  4065. if (this.totalCount <= 0) {
  4066. return
  4067. }
  4068. if (this.totalCount > 40000) {
  4069. this.alphaBet = []
  4070. return
  4071. }
  4072. const keyword = this.isSearchMode ? this.searchText : ''
  4073. const cacheKey = `${this.modeType}-${this.sortType}-${this.isShowFileName}-${keyword}-${this.totalCount}`
  4074. if (this.alphaBetCacheKey === cacheKey && this.alphaBet.length > 0) {
  4075. return
  4076. }
  4077. const result = await this.table.queryMediaLibraryPaged({
  4078. pageIndex: 0,
  4079. pageSize: this.totalCount,
  4080. sortType: this.sortType,
  4081. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  4082. isShowFileName: this.isShowFileName
  4083. })
  4084. const version = ++this.alphaBetBuildVersion
  4085. await this.buildAlphaBetByTask(result.items, version)
  4086. this.alphaBetCacheKey = cacheKey
  4087. }
  4088. @Builder
  4089. topTitleBar(){
  4090. Column() {
  4091. Row({ space: 15 }) {
  4092. if (!this.isSearchMode ) {
  4093. //左侧滑动按钮
  4094. TitleBarPointLightButton({
  4095. iconResource: this.rightTopImage,
  4096. iconSize: 25,
  4097. pointColor: this.themeColor,
  4098. clickScale: 0.6,
  4099. clickHandler: () => {
  4100. this.triggerSwipeBackWithAnimation()
  4101. }
  4102. })
  4103. }else{
  4104. //左侧搜索返回按钮
  4105. TitleBarPointLightButton({
  4106. iconResource: $r('sys.symbol.chevron_left'),
  4107. iconSize: 25,
  4108. pointColor: this.themeColor,
  4109. clickScale: 0.6,
  4110. clickHandler: () => {
  4111. this.isSearchMode = false
  4112. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  4113. this.searchText = ''
  4114. this.getSortedFiles(this.currentPath)
  4115. return
  4116. }
  4117. this.onSearchInput('')
  4118. }
  4119. })
  4120. .margin({bottom:5})
  4121. }
  4122. if (!this.isSearchMode) {
  4123. Text(this.modeType==1?`${this.titleName}(${this.mediaKuCount}首)`:this.titleName)
  4124. .margin({left:3,right:10})
  4125. .fontColor($r('app.color.text_color'))
  4126. .fontSize(this.twoFingerType==3?17:16)
  4127. .maxLines(1)
  4128. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4129. .layoutWeight(1)
  4130. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  4131. }
  4132. //搜索框
  4133. Search({ controller: this.searchController,value: this.searchText, placeholder: '搜索标题、艺术家...' })
  4134. .searchButton('搜索',{fontColor:this.themeColor})
  4135. .searchIcon({
  4136. src: $r('sys.media.ohos_ic_public_search_filled')
  4137. })
  4138. .cancelButton({
  4139. style: CancelButtonStyle.CONSTANT,
  4140. icon: {
  4141. src: $r('sys.media.ohos_ic_public_cancel_filled')
  4142. }
  4143. })
  4144. .layoutWeight(1)
  4145. .height(40)
  4146. .maxLength(20)
  4147. .backgroundColor(this.isDarkMode?Color.Black:'#F5F5F5')
  4148. .placeholderColor(Color.Grey)
  4149. .placeholderFont({ size: 14, weight: 400 })
  4150. .textFont({ size: 14, weight: 400 })
  4151. .onSubmit((value: string) => {
  4152. console.log('onecold onSubmit ='+value)
  4153. this.searchController.stopEditing()
  4154. if(this.modeType==0){
  4155. this.modeType =1//如果是首页 切换到媒体库搜索
  4156. }
  4157. this.commitSearchHistory(value)
  4158. this.onSearchInput(this.searchText);
  4159. })
  4160. .onChange((value: string) => {
  4161. console.log('onecold onChange ='+value)
  4162. if(this.modeType==0){
  4163. this.modeType =1//如果是首页 切换到媒体库搜索
  4164. }
  4165. this.onSearchInput(value);
  4166. })
  4167. .visibility(this.isSearchMode?Visibility.Visible:Visibility.None)
  4168. .animation({ duration: 300, curve: Curve.Ease })
  4169. //搜索按钮
  4170. if (!this.isSearchMode) {
  4171. TitleBarPointLightButton({
  4172. iconResource: $r('sys.symbol.magnifyingglass'),
  4173. iconSize: 25,
  4174. pointColor: this.themeColor,
  4175. clickScale: 0.6,
  4176. clickHandler: () => {
  4177. this.isSearchMode = true
  4178. this.loadSearchHistory()
  4179. }
  4180. })
  4181. //排序按钮
  4182. TitleBarPointLightButton({
  4183. iconResource: $r('sys.symbol.list_number'),
  4184. iconSize: 25,
  4185. pointColor: this.themeColor,
  4186. clickScale: 0.6,
  4187. menuBuilder: () => {
  4188. if ((this.modeType==2&&!this.isCanBack)||(this.modeType==3&&!this.isCanBack)) {
  4189. this.SortMenuForArtistAblumBuilder()
  4190. return
  4191. }
  4192. this.SortMenuBuilder()
  4193. }
  4194. })
  4195. //添加按钮
  4196. TitleBarPointLightButton({
  4197. iconResource: $r('sys.symbol.plus'),
  4198. iconSize: 25,
  4199. pointColor: this.themeColor,
  4200. clickScale: 0.6,
  4201. clickHandler: () => {
  4202. this.showAddSheet = !this.showAddSheet;
  4203. }
  4204. })
  4205. .visibility(this.modeType==0||this.modeType==1?Visibility.Visible:Visibility.None)
  4206. .bindSheet($$this.showAddSheet, this.addSheet(), {
  4207. height: SheetSize.FIT_CONTENT,
  4208. dragBar: true,
  4209. showClose: true,
  4210. preferType: SheetType.CENTER ,
  4211. title: {
  4212. title: '导入音乐'
  4213. }
  4214. })
  4215. }
  4216. }
  4217. }
  4218. .padding({ top: this.topSafeHeight+10, left: 10, right: 10 })
  4219. .width('100%')
  4220. .translate({
  4221. x: 0,
  4222. y: (this.isShowTitleBar || !this.autoHideTitle) ? 0 : -80
  4223. })
  4224. .opacity((this.isShowTitleBar || !this.autoHideTitle) ? 1 : 0)
  4225. .animation({
  4226. duration: 240,
  4227. curve: Curve.EaseInOut
  4228. })
  4229. }
  4230. @Builder
  4231. addSheet() {
  4232. Scroll() {
  4233. Column() {
  4234. Column() {
  4235. Row() {
  4236. SymbolGlyph($r('sys.symbol.info_circle'))
  4237. .fontSize(22)
  4238. .fontColor([this.themeColor])
  4239. .alignSelf(ItemAlign.Center)
  4240. .margin({ left: 8 })
  4241. Text('导入音乐复制到DownLoad目录')
  4242. .margin({ left: 8 })
  4243. .fontSize(14)
  4244. .fontColor($r('app.color.text_color'))
  4245. .fontWeight(480)
  4246. .layoutWeight(1)
  4247. Toggle({ type: ToggleType.Switch, isOn: this.isCopyFileToDownLoad })
  4248. .selectedColor(this.themeColor)
  4249. .switchPointColor(Color.White)
  4250. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  4251. .margin({ right: 2 })
  4252. .onChange((checked: boolean) => {
  4253. this.isCopyFileToDownLoad = checked;
  4254. PreferencesUtil.put(SettingPage.IS_COPYFILE_TO_DOWNLOAD, this.isCopyFileToDownLoad)
  4255. })
  4256. .width(50)
  4257. .height(30);
  4258. }
  4259. .height(72)
  4260. .padding({ left:8,right:8 })
  4261. }
  4262. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  4263. .backgroundColor($r('app.color.start_window_background'))
  4264. .borderRadius(15)
  4265. .width('85%')
  4266. .margin({
  4267. top: 10,
  4268. bottom: 10
  4269. })
  4270. .padding(0)
  4271. .border({
  4272. color: Color.White,
  4273. width: 1.8
  4274. })
  4275. Menu() {
  4276. MenuItem({
  4277. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder_badge_plus')),
  4278. content: "新建文件夹"
  4279. })
  4280. .backgroundColor($r('app.color.silvery'))
  4281. .border({
  4282. width: { bottom: 1 },
  4283. color: '#12ec5c87'
  4284. })
  4285. .margin(10)
  4286. .height(60)
  4287. .padding({left:15,right:15})
  4288. .onClick(async () => {
  4289. this.showMkDialog()
  4290. this.showAddSheet = !this.showAddSheet
  4291. })
  4292. MenuItem({
  4293. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder')),
  4294. content: $r('app.string.import_from_files')
  4295. })
  4296. .padding({left:15,right:15})
  4297. .backgroundColor($r('app.color.silvery'))
  4298. .border({
  4299. width: { bottom: 1 },
  4300. color: '#12ec5c87'
  4301. })
  4302. .margin(10)
  4303. .height(60)
  4304. .onClick(async () => {
  4305. this.callFilePickerSelectFile()
  4306. this.showAddSheet = !this.showAddSheet
  4307. })
  4308. MenuItem({
  4309. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square')),
  4310. content: '全选导入'
  4311. // content: '从下载文件夹导入(路径:Download/' +
  4312. // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
  4313. })
  4314. .padding({left:15,right:15})
  4315. .backgroundColor($r('app.color.silvery'))
  4316. .border({
  4317. width: { bottom: 1 },
  4318. color: '#12ec5c87'
  4319. })
  4320. .margin(10)
  4321. .height(60)
  4322. .onClick(async () => {
  4323. this.goSelectMusic()
  4324. this.showAddSheet = !this.showAddSheet
  4325. })
  4326. MenuItem({
  4327. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.save')),
  4328. content: '自动导入教程'
  4329. })
  4330. .padding({left:15,right:15})
  4331. .backgroundColor($r('app.color.silvery'))
  4332. .border({
  4333. width: { bottom: 1 },
  4334. color: '#12ec5c87'
  4335. })
  4336. .margin(10)
  4337. .height(60)
  4338. .onClick(async () => {
  4339. this.showTips()
  4340. this.showAddSheet = !this.showAddSheet
  4341. })
  4342. MenuItem({
  4343. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.questionmark_circle')),
  4344. content: '导入疑问'
  4345. })
  4346. .height(60)
  4347. .padding({left:15,right:15})
  4348. .backgroundColor($r('app.color.silvery'))
  4349. .border({
  4350. width: { bottom: 1 },
  4351. color: '#12ec5c87'
  4352. })
  4353. .margin(10)
  4354. .onClick(async () => {
  4355. this.showProblomTips()
  4356. this.showAddSheet = !this.showAddSheet
  4357. })
  4358. }.attributeModifier(new MenuModifier())
  4359. .margin({bottom:30})
  4360. .width('90%')
  4361. .borderRadius(15)
  4362. }
  4363. .layoutWeight(1)
  4364. }
  4365. }
  4366. async showProblomTips() {
  4367. try {
  4368. this.getUIContext().getPromptAction().showDialog({
  4369. title: '导入疑问',
  4370. message:'为什么有些歌曲导入成功后,内嵌标签或者其他功能不能用?:\n\n1、由于鸿蒙系统的安全策略,文件权限不够,请将文件移动到Download/天天静听目录下。' +
  4371. '这样内嵌标签功能就没有权限问题。\n\n2、导入可以也选择不复制,这样可以省略空间。\n\n',
  4372. buttons: [
  4373. {
  4374. text: '知道了',
  4375. color: '#000000'
  4376. },
  4377. ]
  4378. }, (err, data) => {
  4379. if (err) {
  4380. console.error('showDialog err: ' + err);
  4381. return;
  4382. }
  4383. console.info('showDialog success callback, click button: ' + data.index);
  4384. });
  4385. } catch (error) {
  4386. let message = (error as BusinessError).message;
  4387. let code = (error as BusinessError).code;
  4388. console.error(`showDialog args error code is ${code}, message is ${message}`);
  4389. };
  4390. }
  4391. @Builder
  4392. TagsContentCoverBuilder() {
  4393. Scroll() {
  4394. Column() {
  4395. TagsContentCover(
  4396. {
  4397. selectedFiles:this.selectedFiles,
  4398. isOneKeyTags:this.isOneKeyTags,
  4399. onSeePath:(path:string)=>{
  4400. this.modeType = 0
  4401. this.deleteCache(path)
  4402. this.getSortedFiles(path)
  4403. },
  4404. onTagsResult:(result: boolean,deleteCache_path?:string)=>{
  4405. this.isMultiSelect = false
  4406. if(result){//如果嵌入成功,更新数据
  4407. this.listRefreshKey++
  4408. setTimeout(()=>{
  4409. this.doUpdateData()
  4410. },500)
  4411. }
  4412. console.info('onecold onTagsResult deleteCache_path =' +deleteCache_path)
  4413. if(deleteCache_path){
  4414. this.deleteCache(deleteCache_path)
  4415. }
  4416. }
  4417. }
  4418. )
  4419. }
  4420. }
  4421. .width('100%')
  4422. .height('100%')
  4423. }
  4424. @Builder
  4425. FixMessyViewBuilder() {
  4426. Scroll() {
  4427. Column() {
  4428. FixMessyView(
  4429. {
  4430. selectedFiles:this.selectedFiles,
  4431. isFixMessy:this.isFixMessy,
  4432. onFixResult:(result: boolean)=>{
  4433. this.isMultiSelect = false
  4434. if(result){//如果嵌入成功,更新数据
  4435. this.deleteCache(this.currentPath)
  4436. this.doUpdateData()
  4437. }
  4438. }
  4439. }
  4440. )
  4441. }
  4442. }
  4443. .width('100%')
  4444. .height('100%')
  4445. }
  4446. //剪辑音频
  4447. @Builder
  4448. EditAudioBuilder(item:VideoItem) {
  4449. Scroll() {
  4450. Column() {
  4451. EditAudio(
  4452. {
  4453. mVideoItem:item,
  4454. currentPath:this.currentPath,
  4455. videoUrl:this.videoUrl,
  4456. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4457. currentTime:this.currentTime,
  4458. progressValue:this.progressValue,
  4459. onBack:()=>{
  4460. this.isEditAudio = !this.isEditAudio
  4461. },
  4462. onSeeOutputPath:(outPutPath:string)=>{
  4463. this.isEditAudio = !this.isEditAudio
  4464. this.longItemFilePath = ''
  4465. this.modeType = 0
  4466. this.isShowFileName = true
  4467. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4468. },
  4469. onPlayOrPause:()=>{
  4470. if(this.videoUrl==item.filePath){
  4471. this.playOrPause()
  4472. }else{//如果不是当前播放的,则播放该文件
  4473. this.videoUrl==item.filePath
  4474. this.doPlay(item,0,false,true)
  4475. }
  4476. },
  4477. onSliderChange:(value:number)=>{
  4478. if(this.videoUrl!=item.filePath){
  4479. this.videoUrl==item.filePath
  4480. return
  4481. }
  4482. this.isSeekTo = true;
  4483. this.mDestroyPage = false;
  4484. this.showLoadIng();
  4485. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  4486. let seekValue = value * (this.getActiveDuration() / 100);
  4487. this.seekTo(seekValue + "");
  4488. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  4489. this.isSeekTo = false;
  4490. },
  4491. onResult:(result: boolean,outPath:string)=>{
  4492. if(result){//如果剪辑成功,更新数据
  4493. this.doUpdateData()
  4494. }else{
  4495. ToastUtil.showToast('剪辑失败')
  4496. }
  4497. }
  4498. }
  4499. )
  4500. }
  4501. }
  4502. .width('100%')
  4503. .height('100%')
  4504. }
  4505. //提取伴奏
  4506. @Builder
  4507. ConverterBuilder(item:VideoItem) {
  4508. Scroll() {
  4509. Column() {
  4510. AudioFormatConverter(
  4511. {
  4512. mVideoItem:item,
  4513. videoUrl:this.videoUrl,
  4514. currentPath:this.currentPath,
  4515. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4516. currentTime:this.currentTime,
  4517. progressValue:this.progressValue,
  4518. onBack:()=>{
  4519. this.isConverter = !this.isConverter
  4520. this.longItemFilePath = ''
  4521. },
  4522. onPlayOrPause:()=>{
  4523. if(this.videoUrl==item.filePath){
  4524. this.playOrPause()
  4525. }else{//如果不是当前播放的,则播放该文件
  4526. this.videoUrl==item.filePath
  4527. this.doPlay(item,0,false,true)
  4528. }
  4529. },
  4530. onSeeOutputPath:(outPutPath:string)=>{
  4531. this.isConverter = !this.isConverter
  4532. this.longItemFilePath = ''
  4533. this.modeType = 0
  4534. this.isShowFileName = true
  4535. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4536. },
  4537. onSliderChange:(value:number)=>{
  4538. if(this.videoUrl!=item.filePath){
  4539. this.videoUrl==item.filePath
  4540. return
  4541. }
  4542. this.isSeekTo = true;
  4543. this.mDestroyPage = false;
  4544. this.showLoadIng();
  4545. let seekValue = value * (this.getActiveDuration() / 100);
  4546. this.seekTo(seekValue + "");
  4547. this.isSeekTo = false;
  4548. },
  4549. onResult:(result: boolean,outPath:string)=>{
  4550. if(result){//如果成功,更新数据
  4551. this.doUpdateData()
  4552. }else{
  4553. ToastUtil.showToast('格式转化失败')
  4554. }
  4555. }
  4556. }
  4557. )
  4558. }
  4559. }
  4560. .width('100%')
  4561. .height('100%')
  4562. }
  4563. //提取伴奏
  4564. @Builder
  4565. ExtractAccBuilder(item:VideoItem) {
  4566. Scroll() {
  4567. Column() {
  4568. ExtractAccompaniment(
  4569. {
  4570. mVideoItem:item,
  4571. currentPath:this.currentPath,
  4572. videoUrl:this.videoUrl,
  4573. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4574. currentTime:this.currentTime,
  4575. progressValue:this.progressValue,
  4576. onBack:()=>{
  4577. this.isExtractAcc = !this.isExtractAcc
  4578. this.longItemFilePath = ''
  4579. },
  4580. onPlayOrPause:()=>{
  4581. if(this.videoUrl==item.filePath){
  4582. this.playOrPause()
  4583. }else{//如果不是当前播放的,则播放该文件
  4584. this.videoUrl==item.filePath
  4585. this.doPlay(item,0,false,true)
  4586. }
  4587. },
  4588. onSeeOutputPath:(outPutPath:string)=>{
  4589. this.isExtractAcc = !this.isExtractAcc
  4590. this.longItemFilePath = ''
  4591. this.modeType = 0
  4592. this.isShowFileName = true
  4593. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4594. },
  4595. onSliderChange:(value:number)=>{
  4596. if(this.videoUrl!=item.filePath){
  4597. this.videoUrl==item.filePath
  4598. return
  4599. }
  4600. this.isSeekTo = true;
  4601. this.mDestroyPage = false;
  4602. this.showLoadIng();
  4603. let seekValue = value * (this.getActiveDuration() / 100);
  4604. this.seekTo(seekValue + "");
  4605. this.isSeekTo = false;
  4606. },
  4607. onResult:(result: boolean,outPath:string)=>{
  4608. if(result){//如果成功,更新数据
  4609. this.doUpdateData()
  4610. }else{
  4611. ToastUtil.showToast('提取伴奏失败')
  4612. }
  4613. }
  4614. }
  4615. )
  4616. }
  4617. }
  4618. .width('100%')
  4619. .height('100%')
  4620. }
  4621. //AI人声分离
  4622. @Builder
  4623. AiBuilder(item:VideoItem) {
  4624. Scroll() {
  4625. Column() {
  4626. AIVoiceSeparation(
  4627. {
  4628. mVideoItem:item,
  4629. videoUrl:this.videoUrl,
  4630. currentPath:this.currentPath,
  4631. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4632. currentTime:this.currentTime,
  4633. progressValue:this.progressValue,
  4634. onBack:()=>{
  4635. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  4636. this.longItemFilePath = ''
  4637. },
  4638. onPlayOrPause:()=>{
  4639. if(this.videoUrl==item.filePath||this.isPlaying){
  4640. this.playOrPause()
  4641. }else{//如果不是当前播放的,则播放该文件
  4642. this.videoUrl==item.filePath
  4643. this.doPlay(item,0,false,true)
  4644. }
  4645. },
  4646. onPlayPath:(path:string)=>{
  4647. this.videoUrl==path
  4648. const itemP = Utility.getItemByFilePath(this.videoLocalList,path)
  4649. if(itemP)
  4650. this.doPlay(itemP,0,false,true)
  4651. },
  4652. onSeeOutputPath:(outPutPath:string)=>{
  4653. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  4654. this.longItemFilePath = ''
  4655. this.modeType = 0
  4656. this.isShowFileName = true
  4657. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4658. },
  4659. onSliderChange:(value:number)=>{
  4660. if(this.videoUrl!=item.filePath){
  4661. this.videoUrl==item.filePath
  4662. return
  4663. }
  4664. this.isSeekTo = true;
  4665. this.mDestroyPage = false;
  4666. this.showLoadIng();
  4667. let seekValue = value * (this.getActiveDuration() / 100);
  4668. this.seekTo(seekValue + "");
  4669. this.isSeekTo = false;
  4670. },
  4671. onResult:(result: boolean,outPath:string)=>{
  4672. if(result){//如果成功,更新数据
  4673. this.doUpdateData()
  4674. }else{
  4675. ToastUtil.showToast('Ai人声分离失败')
  4676. }
  4677. }
  4678. }
  4679. )
  4680. }
  4681. }
  4682. .width('100%')
  4683. .height('100%')
  4684. }
  4685. //变速变调
  4686. @Builder
  4687. ChangeToneBuilder(item:VideoItem) {
  4688. Scroll() {
  4689. Column() {
  4690. ChangeTone(
  4691. {
  4692. mVideoItem:item,
  4693. currentPath:this.currentPath,
  4694. videoUrl:this.videoUrl,
  4695. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4696. currentTime:this.currentTime,
  4697. progressValue:this.progressValue,
  4698. onBack:()=>{
  4699. this.isChangeTone = !this.isChangeTone
  4700. this.longItemFilePath = ''
  4701. },
  4702. onPlayOrPause:()=>{
  4703. if(this.videoUrl==item.filePath){
  4704. this.playOrPause()
  4705. }else{//如果不是当前播放的,则播放该文件
  4706. this.videoUrl==item.filePath
  4707. this.doPlay(item,0,false,true)
  4708. }
  4709. },
  4710. onSeeOutputPath:(outPutPath:string)=>{
  4711. this.isChangeTone = !this.isChangeTone
  4712. this.longItemFilePath = ''
  4713. this.modeType = 0
  4714. this.isShowFileName = true
  4715. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4716. },
  4717. onSliderChange:(value:number)=>{
  4718. if(this.videoUrl!=item.filePath){
  4719. this.videoUrl==item.filePath
  4720. return
  4721. }
  4722. this.isSeekTo = true;
  4723. this.mDestroyPage = false;
  4724. this.showLoadIng();
  4725. let seekValue = value * (this.getActiveDuration() / 100);
  4726. this.seekTo(seekValue + "");
  4727. this.isSeekTo = false;
  4728. },
  4729. onResult:(result: boolean,outPath:string)=>{
  4730. if(result){//如果成功,更新数据
  4731. this.doUpdateData()
  4732. }else{
  4733. ToastUtil.showToast('变速变调失败')
  4734. }
  4735. }
  4736. }
  4737. )
  4738. }
  4739. }
  4740. .width('100%')
  4741. .height('100%')
  4742. }
  4743. //提取视频中的音频
  4744. @Builder
  4745. extractAudioFromVideoBuilder(item:VideoItem) {
  4746. Scroll() {
  4747. Column() {
  4748. ExtractAudioFromVideo(
  4749. {
  4750. mVideoItem:item,
  4751. currentPath:this.currentPath,
  4752. videoUrl:this.videoUrl,
  4753. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4754. currentTime:this.currentTime,
  4755. progressValue:this.progressValue,
  4756. onBack:()=>{
  4757. this.isExtractAudio = !this.isExtractAudio
  4758. this.longItemFilePath = ''
  4759. },
  4760. onPlayOrPause:()=>{
  4761. if(this.videoUrl==item.filePath){
  4762. this.playOrPause()
  4763. }else{//如果不是当前播放的,则播放该文件
  4764. this.videoUrl==item.filePath
  4765. this.doPlay(item,0,false,true)
  4766. }
  4767. },
  4768. onSeeOutputPath:(outPutPath:string)=>{
  4769. this.isExtractAudio = !this.isExtractAudio
  4770. this.longItemFilePath = ''
  4771. this.modeType = 0
  4772. this.isShowFileName = true
  4773. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4774. },
  4775. onSliderChange:(value:number)=>{
  4776. if(this.videoUrl!=item.filePath){
  4777. this.videoUrl==item.filePath
  4778. return
  4779. }
  4780. this.isSeekTo = true;
  4781. this.mDestroyPage = false;
  4782. this.showLoadIng();
  4783. let seekValue = value * (this.getActiveDuration() / 100);
  4784. this.seekTo(seekValue + "");
  4785. this.isSeekTo = false;
  4786. },
  4787. onResult:(result: boolean,outPath:string)=>{
  4788. if(result){//如果成功,更新数据
  4789. this.doUpdateData()
  4790. }else{
  4791. ToastUtil.showToast('提取音频失败')
  4792. }
  4793. }
  4794. }
  4795. )
  4796. }
  4797. }
  4798. .width('100%')
  4799. .height('100%')
  4800. }
  4801. //合并音频
  4802. @Builder
  4803. MergeAudioBuilder() {
  4804. Scroll() {
  4805. Column() {
  4806. MergeAudio(
  4807. {
  4808. videoUrl:this.videoUrl,
  4809. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4810. currentPath:this.currentPath,
  4811. selectedFiles:this.selectedFiles,
  4812. currentTime:this.currentTime,
  4813. progressValue:this.progressValue,
  4814. onBack:()=>{
  4815. this.isMergeAudio = !this.isMergeAudio
  4816. this.longItemFilePath = ''
  4817. },
  4818. // onPlayPath:(path:string)=>{
  4819. // if(this.videoUrl==item.filePath){
  4820. // this.playOrPause()
  4821. // }else{//如果不是当前播放的,则播放该文件
  4822. // this.videoUrl==item.filePath
  4823. // this.doPlay(item,0,false,true)
  4824. // }
  4825. //
  4826. // },
  4827. onSeeOutputPath:(outPutPath:string)=>{
  4828. this.isMergeAudio = !this.isMergeAudio
  4829. this.longItemFilePath = ''
  4830. this.modeType = 0
  4831. this.isShowFileName = true
  4832. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4833. },
  4834. onResult:(result: boolean,outPath:string)=>{
  4835. if(result){//如果成功,更新数据
  4836. this.doUpdateData()
  4837. }else{
  4838. if(this.selectedFiles.length>=3){
  4839. ToastUtil.showToast('合并数量太多导致失败')
  4840. }else{
  4841. ToastUtil.showToast('合并失败')
  4842. }
  4843. }
  4844. }
  4845. }
  4846. )
  4847. }
  4848. }
  4849. .width('100%')
  4850. .height('100%')
  4851. }
  4852. asyncCurrentPathData() {
  4853. if (this.modeType == 0) {
  4854. workerInstance.postMessage({
  4855. code: 1,
  4856. data1: this.context,
  4857. data2: this.currentPath,
  4858. data3: this.lockPath,
  4859. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  4860. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  4861. });
  4862. }
  4863. }
  4864. // 处理文件选择的函数
  4865. handleFileSelection(item: VideoItem, checked: boolean) {
  4866. if (!this.isSelectableLocalItem(item)) {
  4867. return
  4868. }
  4869. const exists = this.isLocalItemSelected(item)
  4870. if (checked) {
  4871. if (!exists) {
  4872. this.selectedFiles = [...this.selectedFiles, item];
  4873. }
  4874. } else if (exists) {
  4875. this.selectedFiles = this.selectedFiles.filter(selected => selected.filePath !== item.filePath);
  4876. if (this.selectedFiles.length === 0) {
  4877. this.isAllSelected = false
  4878. }
  4879. }
  4880. this.syncLocalSelectionState()
  4881. }
  4882. private deleteComponentId: number = 0
  4883. private closeDeleteDialog(afterClose?: () => void): void {
  4884. if (this.deleteComponentId > 0) {
  4885. try {
  4886. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  4887. } catch (_error) {
  4888. }
  4889. this.deleteComponentId = 0
  4890. }
  4891. if (afterClose) {
  4892. setTimeout(() => {
  4893. afterClose()
  4894. }, 16)
  4895. }
  4896. }
  4897. private resetDeleteSelectionState(): void {
  4898. this.isMultiSelect = false
  4899. this.selectedFiles = []
  4900. this.isAllSelected = false
  4901. }
  4902. private removeDisplayedLocalItemsByKeys(deletedKeys: Set<string>): void {
  4903. for (let index = this.dataSource.dataArray.length - 1; index >= 0; index--) {
  4904. const item = this.dataSource.dataArray[index]
  4905. if (item && deletedKeys.has(item.filePath)) {
  4906. this.dataSource.deleteData(index)
  4907. }
  4908. }
  4909. }
  4910. private async removeDeletedLocalItemsLocally(deletedItems: Array<VideoItem>): Promise<void> {
  4911. if (ArrayUtil.isEmpty(deletedItems) || this.modeType !== 0) {
  4912. return
  4913. }
  4914. const deletedKeys: Set<string> = new Set<string>()
  4915. for (let i = 0; i < deletedItems.length; i++) {
  4916. const item = deletedItems[i]
  4917. if (StrUtil.isNotEmpty(item?.filePath)) {
  4918. deletedKeys.add(item.filePath)
  4919. }
  4920. }
  4921. if (deletedKeys.size <= 0) {
  4922. return
  4923. }
  4924. const nextVideoLocalList = this.videoLocalList.filter((item: VideoItem) => !deletedKeys.has(item.filePath))
  4925. const nextDirList = this.dirList.filter((item: VideoItem) => !deletedKeys.has(item.filePath))
  4926. const nextFilteredList = this.filteredList.filter((item: VideoItem) => !deletedKeys.has(item.filePath))
  4927. const removedCount = this.videoLocalList.length - nextVideoLocalList.length
  4928. this.videoLocalList = nextVideoLocalList
  4929. this.dirList = nextDirList
  4930. this.filteredList = nextFilteredList
  4931. this.removeDisplayedLocalItemsByKeys(deletedKeys)
  4932. if (removedCount > 0 && this.totalCount > 0) {
  4933. this.totalCount = Math.max(0, this.totalCount - removedCount)
  4934. }
  4935. this.pageCache.clear()
  4936. this.pageHasMoreCache.clear()
  4937. this.pageTotalCountCache.clear()
  4938. this.setButtonStatus()
  4939. this.markAlphaBetDirty()
  4940. this.syncLocalSelectionState()
  4941. this.addCache(this.currentPath, nextVideoLocalList)
  4942. if (this.currentPath === this.rootPath) {
  4943. this.addCache(this.currentPath + '_dirList', nextDirList)
  4944. }
  4945. this.deleteStringCache(this.currentPath + '_hash')
  4946. await this.saveCacheToStorage()
  4947. }
  4948. //多选删除文件
  4949. showWarnIsDelete(){
  4950. this.getUIContext().getPromptAction().openCustomDialog({
  4951. builder: () => {
  4952. this.deleteComptentBuilder()
  4953. },
  4954. isModal:true,
  4955. showInSubWindow:false,
  4956. maskColor: Color.Transparent,
  4957. dialogTransition: // 设置弹窗内容显示的过渡效果
  4958. TransitionEffect.translate({ x: 0, y: 120, z: 0 })
  4959. .combine(TransitionEffect.opacity(0.01))
  4960. .animation({ duration: 260, curve: Curve.EaseOut }),
  4961. maskTransition: // 设置蒙层显示的过渡效果
  4962. TransitionEffect.opacity(0)
  4963. .animation({ duration: 220, curve: Curve.EaseOut })
  4964. }).then((dialogId: number) => {
  4965. this.deleteComponentId = dialogId
  4966. })
  4967. .catch((error: BusinessError) => {
  4968. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  4969. })
  4970. }
  4971. @Builder
  4972. deleteComptentBuilder(){
  4973. DeleteComptent({
  4974. selectedFiles:this.selectedFiles,
  4975. isPlaylistMode: this.modeType == 4,
  4976. playlistId: this.currentSongListID,
  4977. onCancel:()=>{
  4978. this.closeDeleteDialog(() => {
  4979. this.resetDeleteSelectionState()
  4980. })
  4981. },
  4982. onDeleteResult:(result: boolean)=>{
  4983. const deletedItems = [...this.selectedFiles]
  4984. this.closeDeleteDialog(() => {
  4985. this.resetDeleteSelectionState()
  4986. if(result){//如果删除成功,更新数据
  4987. if (this.modeType == 4) {
  4988. this.doSongListTask()
  4989. } else {
  4990. void this.removeDeletedLocalItemsLocally(deletedItems)
  4991. }
  4992. }
  4993. })
  4994. }
  4995. })
  4996. }
  4997. //多选移动文件
  4998. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  4999. Logger.info('onecold showCutDialogForMultipleFiles')
  5000. let mList: Array<string> = []
  5001. let rPath = this.rootPath
  5002. if (isCurrent) {
  5003. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  5004. rPath = this.currentPath
  5005. } else {
  5006. mList = Utility.getNameList(this.dirList);
  5007. rPath = this.rootPath
  5008. }
  5009. let dataBean = new BubbleBean();
  5010. dataBean.data = mList;
  5011. dataBean.color = this.themeColor
  5012. dataBean.onItemClick = (i) => {
  5013. const newDirPath = rPath + '/' + mList[i];
  5014. // Logger.info('newDirPath = ' + newDirPath)
  5015. this.selectedFiles.forEach((item) => {
  5016. const targetName = item.fileName || item.name;
  5017. const newPath = newDirPath + '/' + targetName;
  5018. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  5019. ToastUtil.showToast('移动成功');
  5020. this.table.deleteData(item, () => {
  5021. this.cache.delete(this.currentPath); // 删除原路径缓存
  5022. this.cache.delete(newDirPath); // 删除目标路径缓存
  5023. this.getSortedFiles(this.currentPath, true);
  5024. });
  5025. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  5026. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  5027. if (!Utility.isIsoByExtension(newPath)) {
  5028. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  5029. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  5030. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  5031. this.table.insert(newItem, (id: number) => {
  5032. //加入数据库
  5033. });
  5034. }
  5035. }
  5036. }).catch((error: Error) => {
  5037. console.error(error.message);
  5038. });
  5039. });
  5040. this.isMultiSelect = false
  5041. this.selectedFiles = [];
  5042. this.isAllSelected = false
  5043. XPopup.dismissTop();
  5044. };
  5045. let pup: XPopup
  5046. if (this.isDarkMode) {
  5047. pup = XPopup.Builder()
  5048. .setPopupPosition(PopupPosition.TOP)
  5049. .atView(viewId)
  5050. .setBackgroundColor(Color.Black)
  5051. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  5052. .show();
  5053. } else {
  5054. pup = XPopup.Builder()
  5055. .setPopupPosition(PopupPosition.TOP)
  5056. .atView(viewId)
  5057. .setBackgroundColor(Color.White)
  5058. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  5059. .show();
  5060. }
  5061. }
  5062. /**
  5063. * 加载所有歌单
  5064. */
  5065. async loadAllPlaylists() {
  5066. try {
  5067. this.allPlaylists = await this.playlistTable?.queryAllPlaylists()!
  5068. LogUtil.info('heanup Loaded playlists: ' + this.allPlaylists.length)
  5069. } catch (error) {
  5070. LogUtil.error('heaunp Failed to load playlists: ' + error.message)
  5071. }
  5072. }
  5073. /**
  5074. * 显示添加到歌单对话框
  5075. */
  5076. async openAddToPlaylistDialog(items: VideoItem | VideoItem[]) {
  5077. const songs = Array.isArray(items) ? items : [items]
  5078. const musicItems = songs.filter(song =>
  5079. song.type !== CommonConstants.TYPE_IS_DIR && !this.isIsoLocalFile(song))
  5080. if (musicItems.length === 0) {
  5081. ToastUtil.showToast('请选择要添加的歌曲')
  5082. return
  5083. }
  5084. // 加载最新的歌单列表
  5085. await this.loadAllPlaylists()
  5086. showAddToPlaylistDialog(
  5087. musicItems,
  5088. this.allPlaylists,
  5089. async (playlistId: string) => {
  5090. // 添加歌曲到歌单
  5091. const success = await this.playlistTable?.addSongsToPlaylist(playlistId,
  5092. musicItems.map(song => song.filePath))
  5093. if (success) {
  5094. const count = musicItems.length
  5095. ToastUtil.showToast(count > 1 ? `已添加 ${count} 首歌曲` : '已添加到歌单')
  5096. // 重新加载歌单列表
  5097. await this.loadAllPlaylists()
  5098. } else {
  5099. ToastUtil.showToast(musicItems.length > 1 ? '选中的歌曲已在该歌单中' : '歌曲已在该歌单中')
  5100. }
  5101. this.longItemFilePath = ''
  5102. if (this.isMultiSelect) {
  5103. this.isMultiSelect = false
  5104. this.isAllSelected = false
  5105. this.selectedFiles = []
  5106. }
  5107. },
  5108. () => {
  5109. LogUtil.info('取消添加到歌单')
  5110. },
  5111. () => {
  5112. // 创建新歌单
  5113. showCreatePlaylistDialog(
  5114. async (name: string, description: string, coverPath?: string) => {
  5115. const success = await this.playlistTable?.createPlaylist(name, description, coverPath)
  5116. if (success) {
  5117. ToastUtil.showToast('歌单创建成功')
  5118. // 重新加载歌单列表并打开添加对话框
  5119. await this.loadAllPlaylists()
  5120. await this.openAddToPlaylistDialog(musicItems)
  5121. } else {
  5122. ToastUtil.showToast('歌单创建失败')
  5123. }
  5124. },
  5125. () => {
  5126. // 取消创建歌单
  5127. }
  5128. )
  5129. }
  5130. )
  5131. }
  5132. private syncFavStateLocal(item: VideoItem, isFav: number): void {
  5133. const nextFavList = [...this.favList];
  5134. const itemFavKey = Utility.getFavMatchKey(item);
  5135. const favIndex = nextFavList.findIndex((favItem: VideoItem) => Utility.getFavMatchKey(favItem) === itemFavKey);
  5136. if (isFav === 1) {
  5137. if (favIndex >= 0) {
  5138. nextFavList[favIndex].isFav = 1;
  5139. } else {
  5140. const favItem = cloneVideoItem(item);
  5141. favItem.isFav = 1;
  5142. nextFavList.push(favItem);
  5143. }
  5144. } else if (favIndex >= 0) {
  5145. nextFavList.splice(favIndex, 1);
  5146. }
  5147. this.favList = nextFavList;
  5148. item.isFav = isFav;
  5149. if (this.currentSong && Utility.getFavMatchKey(this.currentSong) === itemFavKey) {
  5150. this.currentSong.isFav = isFav;
  5151. this.isFac = isFav === 1;
  5152. }
  5153. }
  5154. private syncFavoriteStateForPlainList(list: Array<VideoItem> | undefined, targetKey: string, isFav: number): boolean {
  5155. if (!list || ArrayUtil.isEmpty(list) || StrUtil.isEmpty(targetKey)) {
  5156. return false;
  5157. }
  5158. let changed = false;
  5159. for (let index = 0; index < list.length; index += 1) {
  5160. if (Utility.getFavMatchKey(list[index]) !== targetKey) {
  5161. continue;
  5162. }
  5163. list[index].isFav = isFav;
  5164. changed = true;
  5165. }
  5166. return changed;
  5167. }
  5168. private syncFavoriteStateForVisibleList(list: Array<VideoItem> | undefined, dataSource: LazyDataSource<VideoItem>,
  5169. targetKey: string, isFav: number, removeOnCancel: boolean): boolean {
  5170. if (!list || ArrayUtil.isEmpty(list) || StrUtil.isEmpty(targetKey)) {
  5171. return false;
  5172. }
  5173. let changed = false;
  5174. for (let index = list.length - 1; index >= 0; index -= 1) {
  5175. if (Utility.getFavMatchKey(list[index]) !== targetKey) {
  5176. continue;
  5177. }
  5178. changed = true;
  5179. if (removeOnCancel) {
  5180. list.splice(index, 1);
  5181. if (index < dataSource.dataArray.length) {
  5182. dataSource.deleteData(index);
  5183. }
  5184. } else {
  5185. list[index].isFav = isFav;
  5186. if (index < dataSource.dataArray.length) {
  5187. dataSource.dataArray[index].isFav = isFav;
  5188. dataSource.notifyDataChange(index);
  5189. }
  5190. }
  5191. }
  5192. return changed;
  5193. }
  5194. private syncFavoriteStateInCaches(targetKey: string, isFav: number): void {
  5195. if (StrUtil.isEmpty(targetKey) || this.cache.size === 0) {
  5196. return;
  5197. }
  5198. let changed = false;
  5199. this.cache.forEach((items: Array<VideoItem>) => {
  5200. for (let index = 0; index < items.length; index += 1) {
  5201. if (Utility.getFavMatchKey(items[index]) !== targetKey) {
  5202. continue;
  5203. }
  5204. items[index].isFav = isFav;
  5205. changed = true;
  5206. }
  5207. });
  5208. if (changed) {
  5209. void this.saveCacheToStorage();
  5210. }
  5211. }
  5212. private syncFavoriteStateAcrossCollections(item: VideoItem, isFav: number): void {
  5213. const targetKey = Utility.getFavMatchKey(item);
  5214. if (StrUtil.isEmpty(targetKey)) {
  5215. return;
  5216. }
  5217. const removeFromCurrentView = this.isFavMusic && isFav === 0;
  5218. const currentViewChanged = this.syncFavoriteStateForVisibleList(this.videoLocalList, this.dataSource, targetKey, isFav,
  5219. removeFromCurrentView);
  5220. this.syncFavoriteStateForVisibleList(this.songList, this.sonDataSource, targetKey, isFav, false);
  5221. this.syncFavoriteStateForPlainList(this.currentSongList, targetKey, isFav);
  5222. this.syncFavoriteStateForPlainList(this.historyList, targetKey, isFav);
  5223. this.syncFavoriteStateForPlainList(this.mediaKuList, targetKey, isFav);
  5224. this.syncFavoriteStateForPlainList(this.artistList, targetKey, isFav);
  5225. this.syncFavoriteStateForPlainList(this.albumList, targetKey, isFav);
  5226. this.syncFavoriteStateForPlainList(this.filteredList, targetKey, isFav);
  5227. this.syncFavoriteStateInCaches(targetKey, isFav);
  5228. if (this.isFavMusic) {
  5229. this.currentTitleCover = ArrayUtil.isNotEmpty(this.favList) ? Utility.getFirstCoverFromList(this.favList) :
  5230. $r('app.media.alt');
  5231. }
  5232. if (currentViewChanged) {
  5233. this.setButtonStatus();
  5234. if (removeFromCurrentView) {
  5235. this.markAlphaBetDirty();
  5236. }
  5237. }
  5238. }
  5239. private syncRemoteFavoriteState(item: VideoItem, isFav: number): void {
  5240. if (!item || !isRemoteCloudType(item.type) || StrUtil.isEmpty(item.filePath)) {
  5241. return;
  5242. }
  5243. const remoteManager = RemoteDriveManager.getInstance();
  5244. const target = Utility.getItemByFilePath(remoteManager.webDavSongs, item.filePath);
  5245. if (target) {
  5246. target.isFav = isFav;
  5247. }
  5248. }
  5249. doFav(item: VideoItem) {
  5250. LogUtil.info('onecold doFav isFav=' + item.isFav)
  5251. let isFav = 0
  5252. if (Utility.getIsFav(this.favList, item)) {
  5253. isFav = 0
  5254. } else {
  5255. isFav = 1
  5256. }
  5257. const targetFilePath = isRemoteCloudType(item.type) ? (this.resolveRemoteStoragePath(item) || item.filePath) :
  5258. item.filePath;
  5259. const onUpdateSuccess = (): void => {
  5260. this.syncFavStateLocal(item, isFav);
  5261. this.syncRemoteFavoriteState(item, isFav);
  5262. this.syncFavoriteStateAcrossCollections(item, isFav);
  5263. if (isFav === 1) {
  5264. ToastUtil.showToast('收藏成功');
  5265. } else {
  5266. ToastUtil.showToast('取消收藏成功');
  5267. }
  5268. };
  5269. const updateFavorite = (): void => {
  5270. this.table.updateIsFavByFilePath(targetFilePath, isFav, async (result: boolean, error?: string) => {
  5271. if (result) {
  5272. onUpdateSuccess();
  5273. return;
  5274. }
  5275. if (isRemoteCloudType(item.type)) {
  5276. Logger.warn(TAG, `远程歌曲收藏更新失败,准备补入库后重试: ${targetFilePath}, error=${error}`);
  5277. try {
  5278. await this.persistRemoteMetadataToDb(item);
  5279. this.table.updateIsFavByFilePath(targetFilePath, isFav, (retryResult: boolean, retryError?: string) => {
  5280. if (retryResult) {
  5281. onUpdateSuccess();
  5282. } else {
  5283. Logger.error(TAG, `远程歌曲收藏补入库后仍失败: ${targetFilePath}, error=${retryError}`);
  5284. ToastUtil.showToast(isFav === 1 ? '收藏失败' : '取消收藏失败');
  5285. }
  5286. });
  5287. } catch (persistError) {
  5288. Logger.error(TAG,
  5289. `远程歌曲收藏补入库失败: ${targetFilePath}, error=${(persistError as Error).message}`);
  5290. ToastUtil.showToast(isFav === 1 ? '收藏失败' : '取消收藏失败');
  5291. }
  5292. return;
  5293. }
  5294. ToastUtil.showToast(isFav === 1 ? '收藏失败' : '取消收藏失败');
  5295. })
  5296. };
  5297. updateFavorite()
  5298. }
  5299. //多选复制文件
  5300. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  5301. console.log('onecold showCopyDialogForMultipleFiles');
  5302. let mList: Array<string> = []
  5303. let rPath = this.rootPath
  5304. if (isCurrent) {
  5305. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  5306. rPath = this.currentPath
  5307. } else {
  5308. mList = Utility.getNameList(this.dirList);
  5309. rPath = this.rootPath
  5310. }
  5311. let dataBean = new BubbleBean();
  5312. dataBean.data = mList;
  5313. dataBean.isCopy = true
  5314. dataBean.color = this.themeColor
  5315. dataBean.onItemClick = (i) => {
  5316. const newDirPath = rPath + '/' + mList[i];
  5317. // Logger.info('newDirPath = ' + newDirPath)
  5318. this.selectedFiles.forEach((item) => {
  5319. const targetName = item.fileName || item.name;
  5320. const newPath = newDirPath + '/' + targetName;
  5321. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  5322. ToastUtil.showToast('复制成功');
  5323. this.cache.delete(newDirPath); // 删除目标路径缓存
  5324. this.getSortedFiles(this.currentPath);
  5325. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  5326. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  5327. if (!Utility.isIsoByExtension(newPath)) {
  5328. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  5329. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  5330. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  5331. this.table.insert(newItem, (id: number) => {
  5332. //加入数据库
  5333. });
  5334. }
  5335. }
  5336. }).catch((error: Error) => {
  5337. console.error(error.message);
  5338. });
  5339. });
  5340. this.isMultiSelect = false
  5341. this.selectedFiles = [];
  5342. this.isAllSelected = false
  5343. XPopup.dismissTop();
  5344. };
  5345. let pup: XPopup
  5346. if (this.isDarkMode) {
  5347. pup = XPopup.Builder()
  5348. .setPopupPosition(PopupPosition.TOP)
  5349. .atView(viewId)
  5350. .setBackgroundColor(Color.Black)
  5351. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  5352. .show();
  5353. } else {
  5354. pup = XPopup.Builder()
  5355. .setPopupPosition(PopupPosition.TOP)
  5356. .atView(viewId)
  5357. .setBackgroundColor(Color.White)
  5358. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  5359. .show();
  5360. }
  5361. }
  5362. @Builder
  5363. private DirItem(item: VideoItem, index?: number) {
  5364. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5365. Row() {
  5366. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ?
  5367. this.getListImageSource(item, index ?? -1, this.coverThumbVersion) :
  5368. $r('app.media.music_group'))
  5369. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  5370. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  5371. .fillColor(this.themeColor)// .fontSize(33)
  5372. .alt($r('app.media.music_group'))
  5373. .borderRadius(this.isCoverRectangle?9:'100%')
  5374. .clip(true)
  5375. .shadow({
  5376. radius: 2,
  5377. type: ShadowType.BLUR,
  5378. color: 'on_primary'
  5379. })
  5380. .sourceSize({width:38, height:38})
  5381. .margin({ left: 20, top: 8, bottom: 8 })
  5382. Column() {
  5383. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  5384. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5385. .maxLines(1)// .width('88%')
  5386. .textOverflow({ overflow: TextOverflow.Ellipsis })//列表模式固定省略,避免滚动跑马灯开销
  5387. .margin({ left: 10, right: 20 })
  5388. .fontColor($r('app.color.text_color'))
  5389. Row() {
  5390. Text(`${this.getArtistSongCount(item.name)}首`)
  5391. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5392. .padding({ top: 8 })
  5393. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  5394. .fontColor($r('app.color.text_color'))
  5395. .margin({ left: 10 })
  5396. Text(`${this.getAlbumSongCount(item.name)}首`)
  5397. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5398. .padding({ top: 8 })
  5399. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  5400. .fontColor($r('app.color.text_color'))
  5401. .margin({ left: 10 })
  5402. Blank()
  5403. }
  5404. }
  5405. .height('100%')
  5406. .width('100%')
  5407. .justifyContent(FlexAlign.Center)
  5408. .alignItems(HorizontalAlign.Start)
  5409. Blank()
  5410. Checkbox({ name: 'dir_checkbox' + (index ?? -1) })
  5411. .select(this.isLocalItemSelected(item))
  5412. .selectedColor(this.themeColor)
  5413. .shape(CheckBoxShape.CIRCLE)
  5414. .opacity(this.isMultiSelect && this.isSelectableLocalItem(item) ? 1 : 0)
  5415. .visibility(this.isMultiSelect && this.isSelectableLocalItem(item) ? Visibility.Visible : Visibility.None)
  5416. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5417. .margin({ left: 20, top: 8, bottom: 8, right: 18 })
  5418. .width(22)
  5419. .height(22)
  5420. Image($r('app.media.arrow_right'))
  5421. .height(25)
  5422. .alignSelf(ItemAlign.Center)
  5423. .id(item.filePath)
  5424. .visibility(this.isShowAlphaBet || (this.isMultiSelect && this.isSelectableLocalItem(item)) ?
  5425. Visibility.None : Visibility.Visible)
  5426. }
  5427. }
  5428. .backgroundColor(Color.Transparent)
  5429. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  5430. .width('98%')
  5431. .reuseId('dir_item')
  5432. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  5433. .opacity(this.opacityItem) // 绑定透明度
  5434. .onTouch((event: TouchEvent) => {
  5435. this.handlePointLightTouch(this.getPointLightItemKey('list_dir', item, index), event)
  5436. })
  5437. .visualEffect(deviceInfo.sdkApiVersion >= 20
  5438. ? new hdsEffect.HdsEffectBuilder()
  5439. .pointLight({
  5440. options: this.getPointLightOptions(this.getPointLightItemKey('list_dir', item, index)),
  5441. illuminatedType: hdsEffect.PointLightIlluminatedType.BORDER_CONTENT
  5442. })
  5443. .buildEffect()
  5444. : undefined)
  5445. }
  5446. private refreshDirVisibilitySettings(): void {
  5447. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  5448. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  5449. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  5450. }
  5451. isShowDir(dirName: string) {
  5452. if (dirName === undefined) {
  5453. return true
  5454. }
  5455. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  5456. return this.isShowSimi
  5457. }
  5458. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  5459. return this.isShowFAV
  5460. }
  5461. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  5462. return this.isShowHistory
  5463. }
  5464. return true
  5465. }
  5466. private getPointLightItemKey(prefix: string, item: VideoItem, index?: number): string {
  5467. const itemPath = StrUtil.isNotEmpty(item.filePath) ? item.filePath : `${item.name}_${index ?? -1}`
  5468. return `${prefix}_${itemPath}`
  5469. }
  5470. private handlePointLightTouch(itemKey: string, event: TouchEvent): void {
  5471. if (deviceInfo.sdkApiVersion < 20) {
  5472. return
  5473. }
  5474. if (event.type === TouchType.Down) {
  5475. this.activePointLightItemKey = itemKey
  5476. this.pointLightOptions = {
  5477. color: this.themeColor,
  5478. intensity: 1,
  5479. height: 60
  5480. }
  5481. return
  5482. }
  5483. if ((event.type === TouchType.Up || event.type === TouchType.Cancel) && this.activePointLightItemKey === itemKey) {
  5484. this.activePointLightItemKey = ''
  5485. this.pointLightOptions = undefined
  5486. }
  5487. }
  5488. private getPointLightOptions(itemKey: string): hdsEffect.PointLightOptions | undefined {
  5489. if (this.activePointLightItemKey !== itemKey) {
  5490. return undefined
  5491. }
  5492. return this.pointLightOptions
  5493. }
  5494. @State opacityItem: number = 1; // 控制透明度的状态变量
  5495. @Builder
  5496. private MusicItem(item: VideoItem, index?: number) {
  5497. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5498. Row() {
  5499. Stack() {
  5500. Image(this.getListImageSource(item, index ?? -1, this.coverThumbVersion))
  5501. .fillColor(this.themeColor)
  5502. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  5503. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  5504. .alt($r('app.media.alt'))
  5505. .borderRadius(this.isCoverRectangle?9:'100%')
  5506. .clip(true)
  5507. .draggable(false)
  5508. .sourceSize({width:38, height:38})
  5509. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  5510. // .autoResize(true) // 重采样,可减少内存占用
  5511. .opacity(this.opacityItem)// 绑定透明度
  5512. .margin({ left: 20 })
  5513. .shadow({
  5514. radius: this.isScrolling ? 0 : 10,
  5515. type: ShadowType.BLUR,
  5516. color: 'on_primary'
  5517. })
  5518. .onClick(()=>{
  5519. if (this.isMultiSelect) {
  5520. const isChecked = this.isLocalItemSelected(item);
  5521. this.handleFileSelection(item, !isChecked);
  5522. } else {
  5523. this.doPlay(item,index)
  5524. this.setShowPlayTrue()
  5525. }
  5526. })
  5527. }
  5528. Column() {
  5529. Column() {
  5530. Text(this.isShowFileName?item.fileName :item.name)
  5531. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5532. .maxLines(1)
  5533. .textOverflow({ overflow: this.isLongNameRoLL&&!this.isScrolling?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5534. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5535. $r('app.color.text_color'))
  5536. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5537. .padding({right:25})
  5538. .bindPopup(this.longItemFilePath === item.filePath, {
  5539. builder: this.MenuBuilder(item,index,item.filePath),
  5540. placement: Placement.Top,
  5541. // autoCancel: true,
  5542. mask: {color:'#33000000'},
  5543. // popupColor: Color.Yellow,
  5544. enableArrow: false,//是否显示箭头
  5545. showInSubWindow: false,
  5546. onStateChange: (e) => {
  5547. if (!e.isVisible) {
  5548. this.longItemFilePath = ''
  5549. this.tempLyricContent = ''
  5550. }
  5551. }
  5552. })
  5553. Row() {
  5554. Column(){
  5555. Text(item.md5Str?.includes('Lossless')?
  5556. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5557. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  5558. .padding({ top: 3,right:6,left:6,bottom:3 })
  5559. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5560. $r('app.color.text_color'))
  5561. .fontWeight(500)
  5562. .borderRadius(12)
  5563. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  5564. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5565. .backgroundColor('#FFC107')
  5566. }
  5567. .padding({ top: 8 })
  5568. Text(StrUtil.isEmpty(item.artist) ? item.duration
  5569. :this.twoFingerType==2? item.artist +' ' + item.duration
  5570. : item.artist + ' ' + item?.duration)
  5571. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5572. .padding({ top: 8 ,right:25})
  5573. .visibility(this.isShowFileName?Visibility.None:Visibility.Visible)
  5574. .maxLines(1)
  5575. .opacity(0.85)
  5576. .textOverflow({ overflow: TextOverflow.Ellipsis })//列表模式固定省略
  5577. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5578. $r('app.color.text_color'))
  5579. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5580. Blank()
  5581. Text(this.isShowFileName?item.duration:item.size)
  5582. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5583. .padding({ top: 8 })
  5584. .maxLines(1)
  5585. .visibility(this.isShowFileName?Visibility.Visible:StrUtil.isEmpty(item.artist)
  5586. ? Visibility.Visible : Visibility.None)
  5587. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5588. Color.Gray)
  5589. .margin({ left: StrUtil.isEmpty(item.artist) ?0:10 })
  5590. }
  5591. }
  5592. .height('100%')
  5593. .width('100%')
  5594. .margin({ right: 10 })
  5595. .justifyContent(FlexAlign.Center)
  5596. .alignItems(HorizontalAlign.Start)
  5597. }
  5598. .height('100%')
  5599. .margin({ left: 5 })
  5600. .layoutWeight(1)
  5601. Column() {
  5602. Checkbox({ name: 'checkbox' + index })
  5603. .select(this.isLocalItemSelected(item))
  5604. .selectedColor(this.themeColor)
  5605. .shape(CheckBoxShape.CIRCLE)
  5606. .opacity(this.isMultiSelect ? 1 : 0)
  5607. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  5608. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5609. .margin({ left: 20, top: 8, bottom: 8,right:18 })
  5610. .width(22)
  5611. .height(22)
  5612. PlayingIndicator({
  5613. isActive: this.videoUrl === item.filePath && !this.isMultiSelect,
  5614. indicatorSize: 18,
  5615. marginRight: 20,
  5616. marginTop: 8,
  5617. marginBottom: 8
  5618. })
  5619. }
  5620. }
  5621. }
  5622. .gesture(LongPressGesture()
  5623. .onAction(async () => {
  5624. //如果是专辑和艺术家的首页,不能长按
  5625. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  5626. return
  5627. //如果是我的收藏 最近播放等也不能长按
  5628. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5629. item.name === LocalMusic.STR_HISTORY_MUSIC
  5630. )
  5631. return
  5632. this.longItemFilePath = item.filePath
  5633. this.tempLyricContent = this.supportsLocalAudioActions(item) ? await this.getLyricContent(item) : ''
  5634. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  5635. })
  5636. .onActionEnd((event: GestureEvent) => {
  5637. }))
  5638. .backgroundColor(Color.Transparent)
  5639. .width('100%')
  5640. .reuseId('file_item')
  5641. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  5642. .onTouch((event: TouchEvent) => {
  5643. this.handlePointLightTouch(this.getPointLightItemKey('list_music', item, index), event)
  5644. })
  5645. .visualEffect(deviceInfo.sdkApiVersion >= 20
  5646. ? new hdsEffect.HdsEffectBuilder()
  5647. .pointLight({
  5648. options: this.getPointLightOptions(this.getPointLightItemKey('list_music', item, index)),
  5649. illuminatedType: hdsEffect.PointLightIlluminatedType.BORDER_CONTENT
  5650. })
  5651. .buildEffect()
  5652. : undefined)
  5653. }
  5654. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  5655. @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
  5656. buttons: [{ text: '文件夹' }, { text: '媒体库' },{ text: '艺术家' }, { text: '专辑' }],
  5657. direction: Direction.Ltr,
  5658. buttonPadding:{top:12,bottom:12},
  5659. backgroundColor: Color.Transparent,
  5660. fontSize:14,
  5661. selectedFontSize:15,
  5662. selectedFontColor:Color.White,
  5663. selectedBackgroundColor: this.themeColor,
  5664. localizedTextPadding: {
  5665. end: LengthMetrics.vp(20),
  5666. start: LengthMetrics.vp(20)
  5667. }
  5668. })
  5669. @State @Watch('capsuleSelectedIndexesChanged')tabSelectedIndexes: number[] = [0]
  5670. //当胶囊按钮的选择发生变化时调用此函数
  5671. capsuleSelectedIndexesChanged() {
  5672. this.modeType = this.tabSelectedIndexes[0]
  5673. }
  5674. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  5675. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  5676. isShowCoverHeader() {
  5677. if (!this.isShowHeader) {
  5678. return false
  5679. }
  5680. if (this.modeType == 0) {
  5681. if (this.isHistory || this.isFavMusic) {
  5682. return true
  5683. }
  5684. if (this.currentPath != this.rootPath) {
  5685. return true
  5686. }
  5687. }
  5688. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  5689. }
  5690. getCoverTitleBg(): ResourceStr | image.PixelMap {
  5691. if (this.isCustomizeBg) {
  5692. return ('rgba(255,255,255,0.2)')
  5693. }
  5694. if (this.isDarkMode) {
  5695. return $r('app.color.user_center_card_background')
  5696. }
  5697. return this.currentTitleCover
  5698. }
  5699. // 第二步:popup构造器定义弹框内容
  5700. @Builder popupBuilder() {
  5701. Column({ space: 2 }) {
  5702. Text('友情提示:双指缩放可以放大缩小列表')
  5703. .fontSize(12)
  5704. .fontWeight(FontWeight.Regular)
  5705. .fontColor($r('app.color.text_color'))
  5706. }
  5707. .justifyContent(FlexAlign.SpaceAround)
  5708. .width(220)
  5709. .height(55)
  5710. .padding(15)
  5711. }
  5712. //搜索功能的实现
  5713. @State searchText: string = ''; // 用户输入内容
  5714. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  5715. @State isSearchMode: boolean = false
  5716. @State searchHistoryItems: string[] = []
  5717. private readonly searchHistoryScope: string = 'local_music'
  5718. private loadSearchHistory(): void {
  5719. this.searchHistoryItems = SearchHistoryUtil.load(this.searchHistoryScope)
  5720. }
  5721. private saveSearchHistory(keyword: string): void {
  5722. this.searchHistoryItems = SearchHistoryUtil.save(this.searchHistoryScope, keyword)
  5723. }
  5724. private commitSearchHistory(keyword: string): void {
  5725. const normalized = keyword.trim()
  5726. if (normalized.length === 0) {
  5727. return
  5728. }
  5729. this.saveSearchHistory(normalized)
  5730. }
  5731. private applySearchHistory(keyword: string): void {
  5732. this.searchText = keyword
  5733. this.searchController.stopEditing()
  5734. void this.onSearchInput(keyword)
  5735. }
  5736. // 实时搜索逻辑(带防抖)
  5737. private async onSearchInput(value: string): Promise<void> {
  5738. this.searchText = value.trim();
  5739. Logger.info('heanup LocalMusic', `onSearchInput: keyword="${this.searchText}", mode=${this.modeType}`);
  5740. // 清空搜索文本时保持搜索态,只重置为不带关键词的结果列表
  5741. if (this.searchText === '') {
  5742. this.loadSearchHistory()
  5743. await this.resetAndLoadFirstPage();
  5744. return;
  5745. }
  5746. // 进入搜索模式
  5747. if (!this.isSearchMode) {
  5748. this.isSearchMode = true;
  5749. }
  5750. // 使用数据库分页查询(带搜索条件)
  5751. await this.resetAndLoadFirstPage();
  5752. }
  5753. @Builder
  5754. private SearchHistoryView(): void {
  5755. Column({ space: 10 }) {
  5756. Row() {
  5757. Text('搜索历史')
  5758. .fontSize(14)
  5759. .fontWeight(FontWeight.Medium)
  5760. .fontColor($r('app.color.text_color'))
  5761. Blank()
  5762. Button('清空')
  5763. .fontSize(12)
  5764. .fontColor(this.themeColor)
  5765. .backgroundColor(Color.Transparent)
  5766. .padding({ left: 8, right: 8, top: 4, bottom: 4 })
  5767. .onClick(() => {
  5768. SearchHistoryUtil.clear(this.searchHistoryScope)
  5769. this.searchHistoryItems = []
  5770. })
  5771. }
  5772. .width('100%')
  5773. Flex({ wrap: FlexWrap.Wrap }) {
  5774. ForEach(this.searchHistoryItems, (keyword: string) => {
  5775. Button(keyword)
  5776. .fontSize(12)
  5777. .fontColor($r('app.color.text_color'))
  5778. .backgroundColor(this.isDarkMode ? '#222222' : '#F2F3F5')
  5779. .borderRadius(16)
  5780. .margin({ right: 8, bottom: 8 })
  5781. .padding({ left: 12, right: 12, top: 8, bottom: 8 })
  5782. .onClick(() => {
  5783. this.applySearchHistory(keyword)
  5784. })
  5785. })
  5786. }
  5787. .width('100%')
  5788. }
  5789. .width('100%')
  5790. .padding({ left: 16, right: 16, top: 10, bottom: 10 })
  5791. }
  5792. @State dragItem: number = -1
  5793. @State scaleItem: number = -1
  5794. @State neighborItem: number = -1
  5795. @State neighborScale: number = -1
  5796. @State offsetY: number = 0
  5797. private dragRefOffset: number = 0
  5798. private ITEM_INTV: number = 78
  5799. scaleSelect(item: number): number {
  5800. if (this.scaleItem === item) {
  5801. return 1.05
  5802. } else if (this.neighborItem === item) {
  5803. return this.neighborScale
  5804. } else {
  5805. return 1
  5806. }
  5807. }
  5808. itemMove(index: number, newIndex: number): void {
  5809. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  5810. return;
  5811. }
  5812. let tmp = this.videoLocalList.splice(index, 1);
  5813. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  5814. this.dataSource.pushArrayData(this.videoLocalList)
  5815. if(this.modeType==4&&this.playlistTable){
  5816. updateAllSongsSortOrder(this.playlistTable, this.videoLocalList,this.currentSongListID)
  5817. }
  5818. }
  5819. //瀑布流布局 支持双指缩放
  5820. @State columns: number = 2;
  5821. @State waterFlowScale: number = 1;
  5822. @State imageScale: number = 1;
  5823. @State waterFlowOpacity: number = 1;
  5824. @State waterFlowSnapshot: image.PixelMap | undefined = undefined;
  5825. private columnChanged: boolean = false;
  5826. private oldColumn: number = this.columns;
  5827. private pinchTime: number = 0;
  5828. // 根据缩放阈值改变列数,触发WaterFlow重新布局
  5829. changeColumns(scale: number): void {
  5830. if (scale > (this.columns / (this.columns - 0.5)) && this.columns > 1) {
  5831. this.columns--;
  5832. this.columnChanged = true;
  5833. } else if (scale < 1 && this.columns < 4) {
  5834. this.columns++;
  5835. this.columnChanged = true;
  5836. }
  5837. }
  5838. @Builder
  5839. getWaterView(){
  5840. Scroll(this.scroller) {
  5841. Column() {
  5842. Blank().height(this.topSafeHeight + 55)
  5843. WaterFlow({
  5844. scroller:this.waterScroller,
  5845. layoutMode: WaterFlowLayoutMode.SLIDING_WINDOW
  5846. }) {
  5847. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5848. FlowItem() {
  5849. this.MusicWaterCardItem(item,index)
  5850. }
  5851. .width('100%')
  5852. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  5853. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  5854. {
  5855. preview: MenuPreviewMode.IMAGE
  5856. })
  5857. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  5858. {
  5859. preview: MenuPreviewMode.IMAGE
  5860. })
  5861. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5862. }
  5863. // .columnsTemplate('repeat(auto-fit, 160)')
  5864. .id('waterflow') // 设置id用于截图
  5865. .columnsTemplate('1fr '.repeat(this.columns)) // 动态生成列模板,如:'1fr 1fr 1fr'表示3列等宽
  5866. .columnsGap(12) // 列间距
  5867. .rowsGap(this.columns >= 4 ? 8 : (this.columns == 3 ? 10 : 14)) // 行间距
  5868. .cachedCount(this.columns >= 4 ? 2 : (this.columns == 3 ? 3 : 4))
  5869. .padding({bottom:this.bottomBarHeight+10})
  5870. .scrollBar(BarState.Off)
  5871. // .fadingEdge(true, { fadingEdgeLength: LengthMetrics.vp(38) })
  5872. // 效果:只有向上或者向下滑动到顶部时才会有弹簧回弹效果
  5873. .edgeEffect(EdgeEffect.None)
  5874. .width('90%')
  5875. .height('100%')
  5876. .opacity(this.waterFlowOpacity)
  5877. .scale({
  5878. x: this.waterFlowScale,
  5879. y: this.waterFlowScale,
  5880. centerX: 0,
  5881. centerY: 0
  5882. })
  5883. .onReachEnd(() => {
  5884. if(this.modeType === 4 )
  5885. return;
  5886. // 触底加载下一页
  5887. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  5888. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  5889. return;
  5890. }
  5891. if (this.hasMoreData && !this.isLoadingPage && !this.isPagingTransition) {
  5892. this.scheduleLoadNextPage();
  5893. }
  5894. })
  5895. .onAppear(() => {
  5896. this.scroller.scrollEdge(Edge.Top)
  5897. })
  5898. .nestedScroll({
  5899. scrollForward: NestedScrollMode.PARENT_FIRST,
  5900. scrollBackward: NestedScrollMode.SELF_FIRST
  5901. })
  5902. .priorityGesture(
  5903. PinchGesture()
  5904. .onActionStart((event: GestureEvent) => {
  5905. // 双指捏合手势识别成功时截图
  5906. this.pinchTime = event.timestamp;
  5907. this.columnChanged = false;
  5908. this.oldColumn = this.columns;
  5909. this.getUIContext().getComponentSnapshot().get('waterflow', (error: Error, pixmap: image.PixelMap) => {
  5910. if (error) {
  5911. console.info('error:' + JSON.stringify(error));
  5912. return;
  5913. }
  5914. this.waterFlowSnapshot = pixmap;
  5915. if ((this.oldColumn === 1 ) && event.scale > 1|| (this.oldColumn === 4 && event.scale < 1)) {
  5916. console.info("onecold onActionStart oldColumn:" + this.oldColumn)
  5917. if (this.oldColumn ===4) {
  5918. this.twoFingerType =3
  5919. this.isGridMusic = true
  5920. }else if (this.oldColumn ===1) {
  5921. this.twoFingerType =1
  5922. this.isGridMusic = false
  5923. }
  5924. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  5925. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5926. return;
  5927. }
  5928. })
  5929. })
  5930. .onActionUpdate((event: GestureEvent) => {
  5931. // 手势更新:处理缩放逻辑和视觉效果
  5932. // 边界限制:防止超出列数范围时继续缩放
  5933. if ((this.oldColumn === 1 && event.scale > 1) || (this.oldColumn === 4 && event.scale < 1)) {
  5934. return;
  5935. }
  5936. // 节流处理:避免过于频繁的更新,提升性能
  5937. if (event.timestamp - this.pinchTime < 10000000) {
  5938. return;
  5939. }
  5940. this.pinchTime = event.timestamp;
  5941. this.waterFlowScale = event.scale;
  5942. this.imageScale = event.scale;
  5943. // 根据缩放比例设置WaterFlow透明度
  5944. this.waterFlowOpacity = (this.waterFlowScale > 1) ? (this.waterFlowScale - 1) : (1 - this.waterFlowScale);
  5945. this.waterFlowOpacity *= 3;
  5946. if (!this.columnChanged) {
  5947. this.changeColumns(event.scale);
  5948. }
  5949. // 列数改变后的缩放比例调整:避免出现空白区域
  5950. if (this.columnChanged) {
  5951. this.waterFlowScale = this.imageScale * this.columns / this.oldColumn;
  5952. // 限制缩放范围,确保视觉效果自然
  5953. if (event.scale < 1) {
  5954. this.waterFlowScale = this.waterFlowScale > 1 ? this.waterFlowScale : 1;
  5955. } else {
  5956. this.waterFlowScale = this.waterFlowScale < 1 ? this.waterFlowScale : 1;
  5957. }
  5958. }
  5959. })
  5960. .onActionEnd((event: GestureEvent) => {
  5961. // 手势结束:执行归位动画并保存状态
  5962. // 执行归位动画:平滑过渡到正常状态
  5963. this.getUIContext()?.animateTo({ duration: 300 }, () => {
  5964. this.waterFlowScale = 1;
  5965. this.waterFlowOpacity = 1;
  5966. })
  5967. // 持久化保存当前列数:下次启动时恢复
  5968. PreferencesUtil.putSync('lastColumns', this.columns);
  5969. })
  5970. )
  5971. .onScrollFrameBegin((offset: number) => {
  5972. this.markGridWaterScrollingActive()
  5973. // 获取当前滚动偏移量
  5974. const currentOffsetY = this.waterScroller.currentOffset().yOffset;
  5975. this.tryTriggerLoadForWaterByOffset(currentOffsetY)
  5976. this.updateTitleBarByScrollOffset(currentOffsetY)
  5977. return { offsetRemain: offset };
  5978. })
  5979. }
  5980. }
  5981. .scrollBar(BarState.Off)
  5982. }
  5983. //瀑布流卡片布局
  5984. @Builder
  5985. private MusicWaterCardItem(item: VideoItem, index: number) {
  5986. Button({ type: ButtonType.Normal, stateEffect: false }) {
  5987. Stack() {
  5988. Column() {
  5989. Image(this.getGridWaterImageSource(item, index, true, this.coverThumbVersion))
  5990. .backgroundImageSize(ImageSize.Auto)
  5991. .borderRadius({
  5992. topLeft: 12,
  5993. topRight : 12,
  5994. bottomLeft: 0,
  5995. bottomRight: 0
  5996. })
  5997. .draggable(false)// 禁止长按手势拖动
  5998. .autoResize(true) // 重采样,可减少内存占用
  5999. .sourceSize({
  6000. width: this.getCoverThumbTargetSize(true),
  6001. height: this.getCoverThumbTargetSize(true)
  6002. })
  6003. .width('100%')
  6004. .height('auto')
  6005. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  6006. .objectFit(ImageFit.Cover)
  6007. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  6008. height: '99%' ,
  6009. dragBar: true,
  6010. onDisappear: () => {
  6011. this.longItemFilePath = '';
  6012. this.tempLyricContent = ''
  6013. },
  6014. showClose: true,
  6015. preferType: SheetType.CENTER ,
  6016. title: { title: '编辑标签' }
  6017. })
  6018. .draggable(false)
  6019. .opacity(this.opacityItem)// 绑定透明度
  6020. .margin({
  6021. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  6022. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  6023. })
  6024. Column() {
  6025. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  6026. .fontSize(this.columns == 4 ||this.columns==3? 12 : this.columns == 2 ? 15 : 18)
  6027. .maxLines(1)
  6028. .fontWeight(FontWeight.Bold)
  6029. .textOverflow({ overflow: this.isLongNameRoLL&&!this.isScrolling?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  6030. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  6031. height: '95%',
  6032. dragBar: true,
  6033. showClose: true,
  6034. onDisappear: () => {
  6035. this.longItemFilePathDetail = '';
  6036. },
  6037. blurStyle:BlurStyle.Thin,
  6038. backgroundColor:Color.Transparent,
  6039. preferType: SheetType.CENTER ,
  6040. title: { title: '详情' }
  6041. })
  6042. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6043. $r('app.color.text_color'))
  6044. Column() {
  6045. Text(`${this.getArtistSongCount(item.name)}首`)
  6046. .fontSize(11)
  6047. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  6048. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  6049. .fontColor($r('app.color.text_color'))
  6050. Text(`${this.getAlbumSongCount(item.name)}首`)
  6051. .fontSize(11)
  6052. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  6053. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  6054. .fontColor($r('app.color.text_color'))
  6055. Row(){
  6056. Column(){
  6057. Text(item.md5Str?.includes('Lossless')?
  6058. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  6059. .fontSize(this.columns == 4 ||this.columns==3? 8 : this.columns == 2 ? 9 : 11)
  6060. .padding({ top: 3,right:6,left:6,bottom:3 })
  6061. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6062. $r('app.color.text_color'))
  6063. .fontWeight(500)
  6064. .borderRadius(12)
  6065. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  6066. .backgroundColor('#FFC107')
  6067. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  6068. }
  6069. .margin({ top: 2 ,right:6})
  6070. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  6071. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  6072. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  6073. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 13)
  6074. .maxLines(1)
  6075. .textOverflow({ overflow: TextOverflow.Ellipsis })//瀑布流固定省略
  6076. .margin({ top: 2})
  6077. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  6078. || item.type == CommonConstants.TYPE_IS_ALBUM
  6079. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6080. .fontWeight(FontWeight.Medium)
  6081. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6082. $r('app.color.text_color'))
  6083. }
  6084. }
  6085. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  6086. }
  6087. .height(this.columns == 4 ||this.columns==3? item.type==CommonConstants.TYPE_IS_DIR?30:40
  6088. : this.columns == 2 ? (item.type==CommonConstants.TYPE_IS_DIR?38:48) :
  6089. (item.type==CommonConstants.TYPE_IS_DIR?48:58))
  6090. .width('100%')
  6091. .justifyContent(FlexAlign.Center)
  6092. .margin({
  6093. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  6094. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  6095. })
  6096. }
  6097. .width('100%')
  6098. .borderRadius(12)
  6099. .backgroundColor($r('app.color.com_bg'))
  6100. Checkbox({ name: 'checkbox' + index })
  6101. .select(this.isLocalItemSelected(item))
  6102. .selectedColor(this.themeColor)
  6103. .shape(CheckBoxShape.CIRCLE)
  6104. .opacity(this.isMultiSelect && this.isSelectableLocalItem(item) ? 1 : 0)
  6105. .visibility(this.isMultiSelect && this.isSelectableLocalItem(item) ? Visibility.Visible :
  6106. Visibility.None)
  6107. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  6108. .margin({ left: 20, top: 8, bottom: 8 })
  6109. .width(38)
  6110. .height(38)
  6111. }
  6112. }
  6113. .backgroundColor(Color.Transparent)
  6114. .width('100%')
  6115. .height('auto')
  6116. .padding({top:2})
  6117. .shadow({
  6118. radius: this.isScrolling ? 0 : 8,
  6119. type: ShadowType.BLUR,
  6120. color: 'on_primary'
  6121. })
  6122. .reuseId('card_item')
  6123. .onTouch((event: TouchEvent) => {
  6124. this.handlePointLightTouch(this.getPointLightItemKey('water_music', item, index), event)
  6125. })
  6126. .visualEffect(deviceInfo.sdkApiVersion >= 20
  6127. ? new hdsEffect.HdsEffectBuilder()
  6128. .pointLight({
  6129. options: this.getPointLightOptions(this.getPointLightItemKey('water_music', item, index)),
  6130. illuminatedType: hdsEffect.PointLightIlluminatedType.BORDER_CONTENT
  6131. })
  6132. .buildEffect()
  6133. : undefined)
  6134. .onClick(() => {
  6135. if (this.isMultiSelect) {
  6136. if (this.isSelectableLocalItem(item)) {
  6137. const isChecked = this.isLocalItemSelected(item);
  6138. this.handleFileSelection(item, !isChecked);
  6139. }
  6140. return
  6141. }
  6142. this.doPlay(item, index)
  6143. })
  6144. }
  6145. // Grid布局的开始
  6146. private dragRefOffSetX: number = 0;
  6147. private dragRefOffSetY: number = 0;
  6148. private FIX_VP_X: number = 180;
  6149. private FIX_VP_Y: number = 84;
  6150. isDraggable(index: number): boolean {
  6151. return index >= 0;
  6152. }
  6153. getRowEnd(item: number) {
  6154. if (item.toString() === '0') {
  6155. return 1;
  6156. } else {
  6157. return 0;
  6158. }
  6159. }
  6160. isInLeft(index: number) {
  6161. return index % 2 == 0;
  6162. }
  6163. down(index: number): void {
  6164. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  6165. return;
  6166. }
  6167. this.offsetY -= this.FIX_VP_Y;
  6168. this.dragRefOffSetY += this.FIX_VP_Y;
  6169. this.itemMove(index, index + 1);
  6170. }
  6171. up(index: number): void {
  6172. if (!this.isDraggable(index - 2)) {
  6173. return;
  6174. }
  6175. this.offsetY += this.FIX_VP_Y;
  6176. this.dragRefOffSetY -= this.FIX_VP_Y;
  6177. this.itemMove(index, index - 1);
  6178. }
  6179. left(index: number): void {
  6180. if (this.isInLeft(index)) {
  6181. return;
  6182. }
  6183. if (!this.isDraggable(index - 1)) {
  6184. return;
  6185. }
  6186. this.offsetX += this.FIX_VP_X;
  6187. this.dragRefOffSetX -= this.FIX_VP_X;
  6188. this.itemMove(index, index - 1)
  6189. }
  6190. right(index: number): void {
  6191. if (!this.isInLeft(index)) {
  6192. return;
  6193. }
  6194. if (!this.isDraggable(index + 1)) {
  6195. return;
  6196. }
  6197. this.offsetX -= this.FIX_VP_X;
  6198. this.dragRefOffSetX += this.FIX_VP_X;
  6199. this.itemMove(index, index + 1)
  6200. }
  6201. private scroller: Scroller = new Scroller();
  6202. private waterScroller: Scroller = new Scroller();
  6203. private startIndex: number = 0
  6204. private endIndex: number = 0
  6205. @State scaleValue: number = 1
  6206. @State pinchValue: number = 1
  6207. layoutOptionsForHeader: GridLayoutOptions = {
  6208. regularSize: [1, 1], // 只支持[1, 1]
  6209. irregularIndexes: [0], // 索引为0的GridItem占用一行
  6210. };
  6211. @Builder
  6212. getGridView() {
  6213. Grid(this.scroller, this.layoutOptionsForHeader) {
  6214. GridItem() {
  6215. Column(){
  6216. Blank().height(this.topSafeHeight + 45)
  6217. }
  6218. }
  6219. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  6220. GridItem() {
  6221. Stack() {
  6222. this.MusicItemGrid(item, index)
  6223. }
  6224. }
  6225. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  6226. {
  6227. preview: MenuPreviewMode.IMAGE
  6228. })
  6229. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  6230. {
  6231. preview: MenuPreviewMode.IMAGE
  6232. })
  6233. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.9, y: 0.9 }).animation({ duration: 300 }),
  6234. // TransitionEffect.scale({ x: 0, y: 0 })))
  6235. .clickEffect({ level: ClickEffectLevel.LIGHT })
  6236. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  6237. .zIndex(this.dragItem === index ? 1 : 0)
  6238. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  6239. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  6240. }
  6241. .width('94%')
  6242. .height('100%')
  6243. .editMode(true)
  6244. .padding({bottom:this.bottomBarHeight+this.bottomSafeHeight+10})
  6245. .reuseId('grid_item')
  6246. .layoutWeight(1)
  6247. .scrollBar(BarState.Off)
  6248. .supportAnimation(false)
  6249. .onReachEnd(() => {
  6250. if(this.modeType === 4 )
  6251. return;
  6252. // 触底加载下一页
  6253. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  6254. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  6255. return;
  6256. }
  6257. if (this.hasMoreData && !this.isLoadingPage && !this.isPagingTransition) {
  6258. this.scheduleLoadNextPage();
  6259. }
  6260. })
  6261. .cachedCount(this.twoFingerType==1?1:this.twoFingerType==2?2:2)
  6262. .columnsTemplate(
  6263. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  6264. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  6265. )
  6266. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  6267. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  6268. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  6269. .gesture(PinchGesture({ fingers: 2 })
  6270. .onActionEnd((event: GestureEvent) => {
  6271. this.setGridTwoFingers()
  6272. })
  6273. .onActionUpdate(e => {
  6274. this.scaleValue = this.pinchValue * e.scale
  6275. })
  6276. .onActionStart(e => {
  6277. }))
  6278. .enableScrollInteraction(true)
  6279. .onScrollIndex((start: number, end: number) => {
  6280. this.startIndex = start
  6281. this.endIndex = end
  6282. this.gridVisibleStart = start
  6283. this.gridVisibleEnd = end
  6284. this.lastVisibleEndIndex = end
  6285. this.warmupGridWaterVisibleThumbs(start, end, false)
  6286. const now = Date.now()
  6287. const pagingDelta = this.gridScrollLastPagingEnd >= 0 ? Math.abs(end - this.gridScrollLastPagingEnd) : 999
  6288. if (pagingDelta >= 2 || now - this.gridScrollPagingCheckAt >= 40) {
  6289. this.gridScrollPagingCheckAt = now
  6290. this.gridScrollLastPagingEnd = end
  6291. this.tryTriggerLoadNextPageByScroll(end)
  6292. }
  6293. })
  6294. .onScrollFrameBegin((offset: number) => {
  6295. this.markGridWaterScrollingActive()
  6296. const currentOffsetY = this.scroller.currentOffset().yOffset;
  6297. this.updateTitleBarByScrollOffset(currentOffsetY)
  6298. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  6299. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  6300. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  6301. if (this.isScrollHide) {
  6302. this.setBarHeightHide2(offset)
  6303. } else {
  6304. this.setBarHeightNormal()
  6305. }
  6306. } else {
  6307. this.setBarHeightHide(offset)
  6308. }
  6309. return { offsetRemain: offset };
  6310. })
  6311. }
  6312. @State targetFile: string = '';
  6313. setGridTwoFingers() {
  6314. this.pinchValue = this.scaleValue;
  6315. Logger.info('this.pinchValue = ' + this.pinchValue);
  6316. if (this.pinchValue >= 1) {
  6317. this.twoFingerType++
  6318. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  6319. if(this.twoFingerType >= 4){
  6320. this.twoFingerType = 4//切换成瀑布流
  6321. this.columns = 4
  6322. }
  6323. } else {
  6324. this.twoFingerType--
  6325. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  6326. if (this.twoFingerType < 1) {
  6327. this.twoFingerType = 3
  6328. this.isGridMusic = false
  6329. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6330. }
  6331. }
  6332. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  6333. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6334. this.pinchValue = 1;
  6335. this.scaleValue = 1;
  6336. }
  6337. @State longItemFilePath: string = ''
  6338. @State tempLyricContent: string = ''
  6339. @State editingItem: VideoItem | null = null
  6340. @Builder
  6341. private MusicItemGrid(item: VideoItem, index: number) {
  6342. Button({ type: ButtonType.Normal, stateEffect: false }) {
  6343. Stack() {
  6344. Column() {
  6345. Image(this.getGridWaterImageSource(item, index, false, this.coverThumbVersion))
  6346. .height(this.getGridHeight())
  6347. .width(this.getGridWight())
  6348. .draggable(false)
  6349. .autoResize(true) // 重采样,可减少内存占用
  6350. .sourceSize({
  6351. width: this.getCoverThumbTargetSize(false),
  6352. height: this.getCoverThumbTargetSize(false)
  6353. })
  6354. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  6355. .clip(true)
  6356. .borderRadius({
  6357. topLeft: 12,
  6358. topRight: 12,
  6359. bottomLeft: 0,
  6360. bottomRight: 0
  6361. })
  6362. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  6363. height: '99%' ,
  6364. dragBar: true,
  6365. onDisappear: () => {
  6366. this.longItemFilePath = '';
  6367. this.tempLyricContent = ''
  6368. },
  6369. showClose: true,
  6370. preferType: SheetType.CENTER ,
  6371. title: { title: '编辑标签' }
  6372. })
  6373. .draggable(false)
  6374. .opacity(this.opacityItem)// 绑定透明度
  6375. .margin({
  6376. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  6377. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  6378. })
  6379. Column() {
  6380. Text(this.isShowFileName&&this.modeType !== 2&&this.modeType !== 3&&
  6381. item.type!=CommonConstants.TYPE_IS_DIR?item.fileName :item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  6382. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  6383. .maxLines(1)
  6384. .fontWeight(FontWeight.Bold)
  6385. .textOverflow({ overflow: this.isLongNameRoLL&&!this.isScrolling?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  6386. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  6387. height: '100%',
  6388. dragBar: true,
  6389. showClose: true,
  6390. onDisappear: () => {
  6391. this.longItemFilePathDetail = '';
  6392. },
  6393. blurStyle:BlurStyle.Thin,
  6394. backgroundColor:Color.Transparent,
  6395. preferType: SheetType.CENTER ,
  6396. title: { title: '详情' }
  6397. })
  6398. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6399. $r('app.color.text_color'))
  6400. Column() {
  6401. Text(`${this.getArtistSongCount(item.name)}首`)
  6402. .fontSize(11)
  6403. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  6404. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  6405. .fontColor($r('app.color.text_color'))
  6406. Text(`${this.getAlbumSongCount(item.name)}首`)
  6407. .fontSize(11)
  6408. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  6409. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  6410. .fontColor($r('app.color.text_color'))
  6411. Row(){
  6412. Column(){
  6413. Text(item.md5Str?.includes('Lossless')?
  6414. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  6415. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  6416. .padding({ top: 3,right:6,left:6,bottom:3 })
  6417. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6418. $r('app.color.text_color'))
  6419. .fontWeight(500)
  6420. .borderRadius(12)
  6421. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  6422. .backgroundColor('#FFC107')
  6423. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  6424. }
  6425. .margin({ top: 2 ,right:6})
  6426. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  6427. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  6428. Text(this.isShowFileName?item.duration:StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  6429. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  6430. .maxLines(1)
  6431. .textOverflow({ overflow: TextOverflow.Ellipsis })//Grid固定省略
  6432. .margin({ top: 2})
  6433. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  6434. || item.type == CommonConstants.TYPE_IS_ALBUM
  6435. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6436. .fontWeight(FontWeight.Medium)
  6437. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6438. $r('app.color.text_color'))
  6439. }
  6440. }
  6441. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  6442. }
  6443. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  6444. .width(this.getGridWight())
  6445. .justifyContent(FlexAlign.Center)
  6446. .margin({
  6447. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  6448. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  6449. })
  6450. }
  6451. .width(this.getGridWight())
  6452. .borderRadius(12)
  6453. .backgroundColor($r('app.color.com_bg'))
  6454. Checkbox({ name: 'checkbox' + index })
  6455. .select(this.isLocalItemSelected(item))
  6456. .selectedColor(this.themeColor)
  6457. .shape(CheckBoxShape.CIRCLE)
  6458. .opacity(this.isMultiSelect && this.isSelectableLocalItem(item) ? 1 : 0)
  6459. .visibility(this.isMultiSelect && this.isSelectableLocalItem(item) ? Visibility.Visible :
  6460. Visibility.None)
  6461. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  6462. .margin({ left: 20, top: 8, bottom: 8 })
  6463. .width(38)
  6464. .height(38)
  6465. }
  6466. }
  6467. .backgroundColor(Color.Transparent)
  6468. .width('100%')
  6469. .padding({ top: 15 })
  6470. .height(this.getGridAllHeight())
  6471. .onTouch((event: TouchEvent) => {
  6472. this.handlePointLightTouch(this.getPointLightItemKey('grid_music', item, index), event)
  6473. })
  6474. .visualEffect(deviceInfo.sdkApiVersion >= 20
  6475. ? new hdsEffect.HdsEffectBuilder()
  6476. .pointLight({
  6477. options: this.getPointLightOptions(this.getPointLightItemKey('grid_music', item, index)),
  6478. illuminatedType: hdsEffect.PointLightIlluminatedType.BORDER_CONTENT
  6479. })
  6480. .buildEffect()
  6481. : undefined)
  6482. .onClick(() => {
  6483. if (this.isMultiSelect) {
  6484. if (this.isSelectableLocalItem(item)) {
  6485. const isChecked = this.isLocalItemSelected(item);
  6486. this.handleFileSelection(item, !isChecked);
  6487. }
  6488. return
  6489. }
  6490. this.doPlay(item, index)
  6491. })
  6492. }
  6493. getGridAllHeight() {
  6494. let heightG = 222
  6495. switch (this.twoFingerType) {
  6496. case 1:
  6497. heightG = 143
  6498. break;
  6499. case 2:
  6500. heightG = 178
  6501. break;
  6502. case 3:
  6503. heightG = 222
  6504. break;
  6505. }
  6506. return heightG
  6507. }
  6508. getGridHeight() {
  6509. let heightG = 150
  6510. switch (this.twoFingerType) {
  6511. case 1:
  6512. heightG = 80
  6513. break;
  6514. case 2:
  6515. heightG = 110
  6516. break;
  6517. case 3:
  6518. heightG = 150
  6519. break;
  6520. }
  6521. return heightG
  6522. }
  6523. getGridWight() {
  6524. let wightG = 158
  6525. switch (this.twoFingerType) {
  6526. case 1:
  6527. wightG = 80
  6528. break;
  6529. case 2:
  6530. wightG = 110
  6531. break;
  6532. case 3:
  6533. wightG = 158
  6534. break;
  6535. }
  6536. return wightG
  6537. }
  6538. @State isShowDetail:boolean = false
  6539. @State longItemFilePathDetail:string =''
  6540. @Builder
  6541. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  6542. if(
  6543. ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  6544. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  6545. item.name === LocalMusic.STR_HISTORY_MUSIC)
  6546. ){
  6547. //如果是专辑和艺术家的首页,不能长按
  6548. //如果是我的收藏 最近播放等也不能长按
  6549. }else{
  6550. Scroll() {
  6551. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  6552. Menu() {
  6553. MenuItem({
  6554. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  6555. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  6556. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  6557. })
  6558. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6559. .onClick(() => {
  6560. if (item) {
  6561. this.doFav(item)
  6562. }
  6563. this.longItemFilePath = ''
  6564. })
  6565. MenuItem({
  6566. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  6567. content: '下一首播放'
  6568. })
  6569. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6570. .onClick(() => {
  6571. this.addToNextPlay(item);
  6572. this.longItemFilePath = ''
  6573. })
  6574. MenuItem({
  6575. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  6576. content: '添加到歌单'
  6577. })
  6578. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6579. .onClick(async () => {
  6580. this.longItemFilePath = ''
  6581. await this.openAddToPlaylistDialog(item)
  6582. })
  6583. MenuItem({
  6584. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  6585. content: '编辑标签'
  6586. })
  6587. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  6588. height: '99%',
  6589. dragBar: true,
  6590. showClose: true,
  6591. preferType: SheetType.CENTER ,
  6592. title: { title: '编辑标签' }
  6593. })
  6594. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6595. .onClick(async() => {
  6596. this.initEditFields(item)
  6597. this.tempLyricContent = await this.getLyricContent(item);
  6598. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  6599. this.lyricConStr = this.tempLyricContent
  6600. }
  6601. if(this.isGridMusic||this.twoFingerType==4){
  6602. this.longItemFilePath = item.filePath
  6603. }else{
  6604. this.isShowEdit = !this.isShowEdit;
  6605. }
  6606. })
  6607. MenuItem({
  6608. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  6609. content: $r('app.string.select_all')
  6610. })
  6611. .onClick(() => {
  6612. this.longItemFilePath = ''
  6613. this.enterLocalMultiSelect(item)
  6614. })
  6615. MenuItem({
  6616. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  6617. content: '提取ISO文件'
  6618. })
  6619. .visibility(this.isIsoLocalFile(item) ? Visibility.Visible : Visibility.None)
  6620. .onClick(async () => {
  6621. this.longItemFilePath = ''
  6622. await this.openIsoArchiveDialog(item)
  6623. })
  6624. MenuItem({
  6625. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.cut')),
  6626. content: $r('app.string.edit_audio')
  6627. })
  6628. .bindContentCover($$this.isEditAudio, this.EditAudioBuilder(item), {
  6629. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6630. })
  6631. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6632. .onClick(() => {
  6633. this.isEditAudio = !this.isEditAudio
  6634. })
  6635. MenuItem({
  6636. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  6637. content: $r('app.string.extract_accompaniment')
  6638. })
  6639. .bindContentCover($$this.isExtractAcc, this.ExtractAccBuilder(item), {
  6640. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6641. })
  6642. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6643. .onClick(() => {
  6644. if (!Utility.isNoble()) {
  6645. this.showVipDialog()
  6646. return
  6647. }
  6648. this.isExtractAcc = !this.isExtractAcc
  6649. })
  6650. MenuItem({
  6651. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.repeat')),
  6652. content: $r('app.string.converter_audio')
  6653. })
  6654. .bindContentCover($$this.isConverter, this.ConverterBuilder(item), {
  6655. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6656. })
  6657. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6658. .onClick(() => {
  6659. if (!Utility.isNoble()) {
  6660. this.showVipDialog()
  6661. return
  6662. }
  6663. this.isConverter = !this.isConverter
  6664. })
  6665. // MenuItem({
  6666. // symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.ai_edit')),
  6667. // content: $r('app.string.vocal_separation')
  6668. // })
  6669. // .bindContentCover($$this.isAIVoiceSeparation, this.AiBuilder(item), {
  6670. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6671. // })
  6672. // .onClick(() => {
  6673. // this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  6674. // })
  6675. MenuItem({
  6676. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_counterclockwise_clock')),
  6677. content: $r('app.string.change_tone')
  6678. })
  6679. .bindContentCover($$this.isChangeTone, this.ChangeToneBuilder(item), {
  6680. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6681. })
  6682. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6683. .onClick(() => {
  6684. this.isChangeTone = !this.isChangeTone
  6685. })
  6686. if(Utility.isVideoByExtension(item.filePath)){
  6687. MenuItem({
  6688. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.identify_song')),
  6689. content: $r('app.string.extract_audio')
  6690. })
  6691. .bindContentCover($$this.isExtractAudio, this.extractAudioFromVideoBuilder(item), {
  6692. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6693. })
  6694. .onClick(() => {
  6695. this.isExtractAudio = !this.isExtractAudio
  6696. })
  6697. }
  6698. MenuItem({
  6699. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.phone')),
  6700. content: $r('app.string.set_ring')
  6701. })
  6702. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6703. .onClick(async () => {
  6704. await PermissionUtil.activatePermission(item.filePath)
  6705. // if(item.filePath.includes(this.packName)){
  6706. setRingTone(this.context, item.filePath,item.name)
  6707. // }else{
  6708. // ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限设置铃声')
  6709. // }
  6710. this.longItemFilePath = ''
  6711. })
  6712. MenuItem({
  6713. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  6714. content: $r('app.string.rename')
  6715. })
  6716. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  6717. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  6718. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  6719. .onClick(() => {
  6720. this.showReNameDialog(item, index + '', filePath)
  6721. this.longItemFilePath = ''
  6722. })
  6723. MenuItem({
  6724. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  6725. content: $r('app.string.delete')
  6726. })
  6727. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  6728. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  6729. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  6730. .onClick(() => {
  6731. this.selectSingleItemForDelete(item)
  6732. this.showWarnIsDelete()
  6733. this.longItemFilePath = ''
  6734. })
  6735. MenuItem({
  6736. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  6737. content: $r('app.string.detail')
  6738. })
  6739. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  6740. height:'100%',
  6741. dragBar: true,
  6742. showClose: true,
  6743. blurStyle:BlurStyle.Thin,
  6744. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6745. backgroundColor:Color.Transparent,
  6746. title: { title: '详情信息' }
  6747. })
  6748. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6749. .onClick(() => {
  6750. if(this.isGridMusic||this.twoFingerType==4){
  6751. this.longItemFilePathDetail = item.filePath
  6752. }else{
  6753. this.isShowDetail = !this.isShowDetail
  6754. }
  6755. })
  6756. MenuItem({
  6757. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  6758. content: $r('app.string.share')
  6759. })
  6760. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6761. .onClick(() => {
  6762. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  6763. this.longItemFilePath = ''
  6764. })
  6765. }
  6766. .font({ size: 14, weight: FontWeight.Normal })
  6767. }
  6768. .width(180)
  6769. }
  6770. .height('auto')
  6771. .enableScrollInteraction(true)
  6772. .scrollBar(this.isGridMusic?BarState.On:BarState.Off)
  6773. }
  6774. }
  6775. private listMaxScrollOffsetY: number = 0
  6776. private selectedIndex: number = -1
  6777. setlistTwoFingers() {
  6778. this.pinchValue = this.scaleValue;
  6779. Logger.info('this.pinchValue = ' + this.pinchValue);
  6780. if (this.pinchValue >= 1) {
  6781. this.twoFingerType++
  6782. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  6783. if (this.twoFingerType > 3) {
  6784. this.twoFingerType = 1
  6785. this.isGridMusic = true
  6786. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6787. }
  6788. } else {
  6789. this.twoFingerType--
  6790. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  6791. if (this.twoFingerType < 1) {
  6792. this.twoFingerType = 4
  6793. this.columns = 1
  6794. }
  6795. }
  6796. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  6797. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6798. this.pinchValue = 1;
  6799. this.scaleValue = 1;
  6800. }
  6801. @Builder
  6802. getList(){
  6803. Stack() {
  6804. Refresh({ refreshing: $$this.isRefreshing, refreshingContent: this.contentNode }) {
  6805. this.getListView()
  6806. }
  6807. .pullDownRatio(this.ratioL)
  6808. .pullToRefresh(true)
  6809. .refreshOffset(0)
  6810. .onOffsetChange((offset: number) => {
  6811. // 越接近最大距离,下拉跟手系数越小。
  6812. this.ratioL = 1 - Math.pow((offset / this.maxRefreshingHeight), 3);
  6813. })
  6814. .onStateChange((refreshStatus: RefreshStatus) => {
  6815. console.info('onecold Refresh onStatueChange state is ' + refreshStatus);
  6816. })
  6817. .onRefreshing(async () => {
  6818. if(this.modeType==0){
  6819. this.getHistoryList(false)
  6820. this.asyncCurrentPathOnlyFile()
  6821. }else if(this.modeType == 1){
  6822. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6823. }else if(this.modeType == 2){
  6824. workerInstance.postMessage({ code: 3, data: this.context });
  6825. }else if(this.modeType == 3){
  6826. workerInstance.postMessage({ code: 4, data: this.context });
  6827. }else if(this.modeType == 4){
  6828. this.doSongListTask()
  6829. }
  6830. console.log('onRefreshing test');
  6831. })
  6832. if (this.isLoadingPage) {
  6833. Row() {
  6834. LoadingProgress()
  6835. .width(24)
  6836. .height(24)
  6837. .color(this.themeColor)
  6838. Text('加载中...')
  6839. .margin({ left: 8 })
  6840. .fontSize(13)
  6841. .fontColor($r('app.color.text_color'))
  6842. }
  6843. .padding({ left: 12, right: 12, top: 6, bottom: 6 })
  6844. .backgroundColor(this.isDarkMode ? '#66000000' : '#66FFFFFF')
  6845. .borderRadius(16)
  6846. .align(Alignment.Bottom)
  6847. .margin({ bottom: this.bottomBarHeight + this.bottomSafeHeight + 14 })
  6848. }
  6849. }
  6850. }
  6851. // 扫描当前目录下的文件,不扫描子目录
  6852. asyncCurrentPathOnlyFile(){
  6853. if(this.modeType==0){
  6854. const task = new taskpool.Task(scanCurrentDirectoryTask, getContext(this), this.currentPath,
  6855. this.lockPath,PreferencesUtil.getStringSync('COVER_API',''));
  6856. taskpool.execute(task, taskpool.Priority.HIGH).then(()=>{
  6857. if(this.modeType==0){
  6858. setTimeout(()=>{
  6859. this.isRefreshing =false
  6860. this.deleteCache(this.currentPath)
  6861. this.getSortedFiles(this.currentPath)
  6862. },500)
  6863. }
  6864. }).catch((e:object)=>{
  6865. this.isRefreshing =false
  6866. console.info("onecold task1 catch e: " + e);
  6867. })
  6868. }
  6869. }
  6870. @Builder
  6871. getListView() {
  6872. List({ scroller: this.listScroller }) {
  6873. // ListItemGroup({ header: this.coverHeader() }) {
  6874. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  6875. ListItem() {
  6876. Column() {
  6877. if (item.type === CommonConstants.TYPE_IS_DIR
  6878. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  6879. this.DirItem(item, index)
  6880. } else {
  6881. this.MusicItem(item, index)
  6882. }
  6883. }
  6884. }
  6885. .clickEffect({ level: ClickEffectLevel.LIGHT })
  6886. .swipeAction((
  6887. ((this.isSwipe && !this.isScrolling) &&
  6888. (this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack)))
  6889. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  6890. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath),
  6891. edgeEffect: SwipeEdgeEffect.None } : {}) //左滑
  6892. .onClick(() => {
  6893. if (this.isMultiSelect) {
  6894. if (this.isSelectableLocalItem(item)) {
  6895. const isChecked = this.isLocalItemSelected(item);
  6896. this.handleFileSelection(item, !isChecked);
  6897. }
  6898. return
  6899. }
  6900. this.doPlay(item, index)
  6901. })
  6902. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  6903. }
  6904. .onScrollStart(() => {
  6905. this.isScrolling = true
  6906. this.listVisibleStart = -1
  6907. this.listVisibleEnd = -1
  6908. this.listScrollAlphaCheckAt = 0
  6909. this.listScrollPagingCheckAt = 0
  6910. this.listScrollLastAlphaStart = -1
  6911. this.listScrollLastPagingEnd = -1
  6912. if (this.alphaBetRebuildTimer) {
  6913. clearTimeout(this.alphaBetRebuildTimer)
  6914. this.alphaBetRebuildTimer = 0
  6915. }
  6916. this.showAlphabetIndex()
  6917. })
  6918. .onScrollIndex((start: number,center:number,end:number) => {
  6919. this.selectedIndex = start
  6920. this.listVisibleStart = start
  6921. this.listVisibleEnd = end
  6922. this.lastVisibleEndIndex = end
  6923. if (!this.isMediaLibraryWarmupWindow()) {
  6924. this.warmupListVisibleThumbs(start, end)
  6925. }
  6926. const now = Date.now()
  6927. const alphaDelta = this.listScrollLastAlphaStart >= 0 ? Math.abs(start - this.listScrollLastAlphaStart) : 999
  6928. if (!this.isMediaLibraryWarmupWindow() &&
  6929. start >= 0 && start < this.videoLocalList.length &&
  6930. (alphaDelta >= 2 || now - this.listScrollAlphaCheckAt >= 48)) {
  6931. this.listScrollAlphaCheckAt = now
  6932. this.listScrollLastAlphaStart = start
  6933. const nextAlphaIndex = this.findAlphaBetIndex(this.videoLocalList[start])
  6934. if (nextAlphaIndex !== this.selectAlphaBetIndex) {
  6935. this.selectAlphaBetIndex = nextAlphaIndex
  6936. }
  6937. }
  6938. const pagingDelta = this.listScrollLastPagingEnd >= 0 ? Math.abs(end - this.listScrollLastPagingEnd) : 999
  6939. if (pagingDelta >= 2 || now - this.listScrollPagingCheckAt >= 32) {
  6940. this.listScrollPagingCheckAt = now
  6941. this.listScrollLastPagingEnd = end
  6942. this.tryTriggerLoadNextPageByScroll(end)
  6943. }
  6944. })
  6945. .onScrollStop(() => {
  6946. if(this.isScrolling){
  6947. this.isScrolling = false
  6948. }
  6949. this.flushPendingCoverThumbRefresh()
  6950. if (this.alphaBetDirty) {
  6951. this.scheduleAlphaBetRebuild(0)
  6952. }
  6953. this.hideAlphabetIndexAfterDelay(1500)
  6954. })
  6955. .onReachEnd(() => {
  6956. if(this.modeType === 4 )//歌单不能加载下一页
  6957. return;
  6958. // 触底加载下一页
  6959. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  6960. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  6961. return;
  6962. }
  6963. if (this.hasMoreData && !this.isLoadingPage && !this.isPagingTransition) {
  6964. this.scheduleLoadNextPage();
  6965. }
  6966. })
  6967. .scrollBar(BarState.Off)
  6968. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  6969. .gesture(PinchGesture({ fingers: 2 })
  6970. .onActionEnd((event: GestureEvent) => {
  6971. this.setlistTwoFingers()
  6972. })
  6973. .onActionUpdate(e => {
  6974. this.scaleValue = this.pinchValue * e.scale
  6975. })
  6976. .onActionStart(e => {
  6977. }))
  6978. .contentStartOffset(this.topSafeHeight + 55)
  6979. .scrollBar(BarState.Off)
  6980. .contentEndOffset(this.bottomBarHeight+this.bottomSafeHeight)
  6981. .cachedCount(this.modeType == 1 ? 4 : 8)
  6982. // .reuseId('list_item')
  6983. .borderRadius(20)
  6984. .layoutWeight(1)
  6985. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  6986. .lanes(
  6987. new BreakpointType<number>({
  6988. sm: 1,
  6989. md: 2,
  6990. lg: 2,
  6991. xl: 3,
  6992. xxl: 4
  6993. }).getValue(this.currentBreakpoint),
  6994. new BreakpointType<number>({
  6995. sm: 0,
  6996. md: 12,
  6997. lg: 12,
  6998. xl: 16,
  6999. xxl: 20
  7000. }).getValue(this.currentBreakpoint)
  7001. )
  7002. .onAreaChange((oldValue: Area, newValue: Area) => {
  7003. this.listArea = newValue
  7004. if (this.twoFingerType == 3) {
  7005. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  7006. } else if (this.twoFingerType == 2) {
  7007. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  7008. } else if (this.twoFingerType == 1) {
  7009. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  7010. }
  7011. })
  7012. .onScrollFrameBegin((offset: number) => {
  7013. const currentOffsetY = this.listScroller.currentOffset().yOffset;
  7014. this.updateTitleBarByScrollOffset(currentOffsetY)
  7015. return { offsetRemain: offset };
  7016. })
  7017. }
  7018. setBarHeightNormal() {
  7019. this.hideDone = false;
  7020. this.getUIContext().animateTo({
  7021. duration: 300
  7022. }, () => {
  7023. this.bottomBarHeight = 68 + 0;
  7024. this.topBarHeight = 50 + 0;
  7025. this.barOpacity = 1;
  7026. this.barBottomOpacity = 1
  7027. this.currentYOffset = 0;
  7028. this.isHiding = false;
  7029. });
  7030. }
  7031. setBarHeightHide(offset: number) {
  7032. if (offset > 0 && !this.hideDone) {
  7033. this.currentYOffset += offset;
  7034. if (this.currentYOffset <= 100) {
  7035. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  7036. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  7037. this.barOpacity = 1 - this.currentYOffset / 100;
  7038. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  7039. } else {
  7040. this.topBarHeight = 0;
  7041. this.bottomBarHeight = 0;
  7042. this.barBottomOpacity = 0
  7043. this.barOpacity = 0;
  7044. this.hideDone = true;
  7045. }
  7046. this.isHiding = true;
  7047. }
  7048. if (offset < 0 && this.isHiding) {
  7049. this.hideDone = false;
  7050. this.getUIContext().animateTo({
  7051. duration: 300
  7052. }, () => {
  7053. this.bottomBarHeight = 68 + 0;
  7054. this.topBarHeight = 50 + 0;
  7055. this.barOpacity = 1;
  7056. this.barBottomOpacity = 1
  7057. this.currentYOffset = 0;
  7058. this.isHiding = false;
  7059. });
  7060. }
  7061. }
  7062. //这个方法没隐藏bottomBar,只隐藏topbar
  7063. setBarHeightHide2(offset: number) {
  7064. if (offset > 0 && !this.hideDone) {
  7065. this.currentYOffset += offset;
  7066. if (this.currentYOffset <= 100) {
  7067. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  7068. this.barOpacity = 1 - this.currentYOffset / 100;
  7069. } else {
  7070. this.topBarHeight = 0;
  7071. this.barOpacity = 0;
  7072. this.hideDone = true;
  7073. }
  7074. this.isHiding = true;
  7075. }
  7076. if (offset < 0 && this.isHiding) {
  7077. this.hideDone = false;
  7078. this.getUIContext().animateTo({
  7079. duration: 300
  7080. }, () => {
  7081. this.topBarHeight = 50 + 0;
  7082. this.barOpacity = 1;
  7083. this.currentYOffset = 0;
  7084. this.isHiding = false;
  7085. });
  7086. }
  7087. }
  7088. private async doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean,isOpen?:boolean) {
  7089. Logger.info(`heanup doPlay被调用 - 歌曲: ${item.name}, 文件路径: ${item.filePath}, 索引: ${index}, 类型: ${item.type}, isFromSonPlayList: ${isFromSonPlayList}`)
  7090. switch (item.type) {
  7091. case CommonConstants.TYPE_IS_DIR:
  7092. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  7093. let shouldScrollTopNow = true
  7094. let offsetB = 0
  7095. if(this.twoFingerType==4){
  7096. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  7097. let cur = this.waterScroller.currentOffset()
  7098. if (cur && typeof cur.yOffset === 'number') {
  7099. offsetB = cur.yOffset
  7100. }
  7101. }
  7102. this.mScrollMap.set('lastWaterDirScrollOffset', offsetB)
  7103. }else
  7104. if (this.isGridMusic) {
  7105. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  7106. let cur = this.scroller.currentOffset()
  7107. if (cur && typeof cur.yOffset === 'number') {
  7108. offsetB = cur.yOffset
  7109. }
  7110. }
  7111. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  7112. } else {
  7113. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  7114. let cur = this.listScroller.currentOffset()
  7115. if (cur && typeof cur.yOffset === 'number') {
  7116. offsetB = cur.yOffset
  7117. }
  7118. }
  7119. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  7120. }
  7121. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  7122. this.showVerifyDialog()
  7123. this.currentTitleName = '私密音频'
  7124. this.currentTitleCover = $r('app.media.alt')
  7125. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  7126. this.titleName = '最近播放'
  7127. this.currentTitleCover = $r('app.media.alt')
  7128. this.currentTitleName = '最近播放'
  7129. //加载动画效果
  7130. this.updateListData(this.historyList, true)
  7131. // this.videoLocalList = this.historyList
  7132. if (ArrayUtil.isEmpty(this.historyList)) {
  7133. ToastUtil.showToast('最近播放记录空空如也')
  7134. } else {
  7135. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  7136. }
  7137. this.isHistory = true
  7138. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  7139. this.titleName = '我的收藏'
  7140. this.currentTitleName = '我的收藏'
  7141. this.currentTitleCover = $r('app.media.alt')
  7142. //加载动画效果
  7143. this.updateListData(this.favList, true)
  7144. if (ArrayUtil.isEmpty(this.favList)) {
  7145. ToastUtil.showToast('无音乐收藏记录')
  7146. } else {
  7147. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  7148. }
  7149. this.isFavMusic = true
  7150. } else {
  7151. this.currentTitleName = item.name
  7152. this.currentPath = item.filePath
  7153. this.currentTitleCover = $r('app.media.alt')
  7154. shouldScrollTopNow = false
  7155. this.getSortedFiles(this.currentPath, false, undefined, undefined, undefined, true, true)
  7156. }
  7157. //进入歌单的时候的滚动位置在顶部
  7158. if (shouldScrollTopNow) {
  7159. if(this.twoFingerType==4){
  7160. setTimeout(() => {
  7161. this.waterScroller.scrollEdge(Edge.Top)
  7162. this.scroller.scrollEdge(Edge.Top)
  7163. }, 200)
  7164. }else{
  7165. if (this.isGridMusic) {
  7166. this.scroller.scrollToIndex(0,false)
  7167. }else{
  7168. this.listScroller.scrollToIndex(0,false)
  7169. }
  7170. }
  7171. }
  7172. this.rightTopImage = $r('sys.symbol.chevron_left')
  7173. break;
  7174. case CommonConstants.TYPE_IS_ARTIST:
  7175. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  7176. let offsetA = 0
  7177. if(this.twoFingerType==4){
  7178. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  7179. let cur = this.waterScroller.currentOffset()
  7180. if (cur && typeof cur.yOffset === 'number') {
  7181. offsetA = cur.yOffset
  7182. }
  7183. }
  7184. this.mScrollMap.set('lastWaterArtistScrollOffset', offsetA)
  7185. }else
  7186. if (this.isGridMusic) {
  7187. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  7188. let cur = this.scroller.currentOffset()
  7189. if (cur && typeof cur.yOffset === 'number') {
  7190. offsetA = cur.yOffset
  7191. }
  7192. }
  7193. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  7194. } else {
  7195. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  7196. let cur = this.listScroller.currentOffset()
  7197. if (cur && typeof cur.yOffset === 'number') {
  7198. offsetA = cur.yOffset
  7199. }
  7200. }
  7201. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  7202. }
  7203. // 进入艺术家详情页前,先加载详情页的排序类型
  7204. // 注意:需要临时设置isCanBack=true,以便loadSortTypeForCurrentMode读取详情页的排序设置
  7205. const artistOriginalIsCanBack = this.isCanBack;
  7206. this.isCanBack = true;
  7207. const artistDetailSortType = this.loadSortTypeForCurrentMode();
  7208. this.isCanBack = artistOriginalIsCanBack; // 恢复原值
  7209. Logger.info('heanup LocalMusic', `进入艺术家详情页: 加载详情页排序 sortType=${artistDetailSortType}`);
  7210. // 缓存键需要包含排序类型,因为不同的排序类型会产生不同的数据
  7211. const artistCacheKey = `${item.name}_sort_${artistDetailSortType}`;
  7212. let mList = this.artistMap.get(artistCacheKey)
  7213. if (mList === undefined || ArrayUtil.isEmpty(mList)) {
  7214. // 使用详情页的排序类型查询
  7215. mList = await this.table.querySongsByArtist(item.name, artistDetailSortType, this.isShowFileName);
  7216. if (ArrayUtil.isNotEmpty(mList)) {
  7217. this.artistMap.set(artistCacheKey, mList);
  7218. }
  7219. }
  7220. // 设置当前排序类型为详情页排序
  7221. this.sortType = artistDetailSortType;
  7222. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  7223. // 注意:不再调用 Utility.doSortListAscending,因为数据已经按 artistDetailSortType 排序了
  7224. const nextArtistCountMap = new Map(this.artistSongCountMap);
  7225. nextArtistCountMap.set(item.name, mList.length);
  7226. this.artistSongCountMap = nextArtistCountMap;
  7227. this.isCanBack = true
  7228. this.hasMoreData = false
  7229. this.isLoadingPage = false
  7230. this.pageCache.clear()
  7231. this.pageHasMoreCache.clear()
  7232. this.pageTotalCountCache.clear()
  7233. this.prefetchingPages.clear()
  7234. this.lastScrollTriggerPage = -1
  7235. this.lastVisibleEndIndex = -1
  7236. this.isPagingTransition = false
  7237. if (this.pagingScheduleTimer) {
  7238. clearTimeout(this.pagingScheduleTimer)
  7239. this.pagingScheduleTimer = 0
  7240. }
  7241. this.totalCount = mList.length
  7242. this.titleName = item.name
  7243. this.currentTitleName = '艺术家:' + item.name
  7244. if (item.pixelMapPath) {
  7245. this.currentTitleCover = item.pixelMapPath
  7246. }
  7247. this.updateListData(mList, true, true) // 详情页立即替换列表,避免旧列表顶部闪现
  7248. } else {
  7249. ToastUtil.showToast('未找到该艺术家的歌曲');
  7250. return;
  7251. }
  7252. this.rightTopImage = $r('sys.symbol.chevron_left')
  7253. //进入歌单的时候的滚动位置在顶部
  7254. if(this.twoFingerType==4){
  7255. setTimeout(() => {
  7256. this.waterScroller.scrollEdge(Edge.Top)
  7257. this.scroller.scrollEdge(Edge.Top)
  7258. }, 380)
  7259. }else{
  7260. if (this.isGridMusic) {
  7261. this.scroller.scrollEdge(Edge.Top)
  7262. }else{
  7263. this.listScroller.scrollEdge(Edge.Top)
  7264. }
  7265. }
  7266. break;
  7267. case CommonConstants.TYPE_IS_ALBUM:
  7268. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  7269. let offset = 0
  7270. if(this.twoFingerType==4){
  7271. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  7272. let cur = this.waterScroller.currentOffset()
  7273. if (cur && typeof cur.yOffset === 'number') {
  7274. offset = cur.yOffset
  7275. }
  7276. }
  7277. this.mScrollMap.set('lastWaterAlBumScrollOffset', offset)
  7278. }else
  7279. if (this.isGridMusic) {
  7280. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  7281. let cur = this.scroller.currentOffset()
  7282. if (cur && typeof cur.yOffset === 'number') {
  7283. offset = cur.yOffset
  7284. }
  7285. }
  7286. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  7287. } else {
  7288. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  7289. let cur = this.listScroller.currentOffset()
  7290. if (cur && typeof cur.yOffset === 'number') {
  7291. offset = cur.yOffset
  7292. }
  7293. }
  7294. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  7295. }
  7296. // 进入专辑详情页前,先加载详情页的排序类型
  7297. // 注意:需要临时设置isCanBack=true,以便loadSortTypeForCurrentMode读取详情页的排序设置
  7298. const albumOriginalIsCanBack = this.isCanBack;
  7299. this.isCanBack = true;
  7300. const albumDetailSortType = this.loadSortTypeForCurrentMode();
  7301. this.isCanBack = albumOriginalIsCanBack; // 恢复原值
  7302. Logger.info('heanup LocalMusic', `进入专辑详情页: 加载详情页排序 sortType=${albumDetailSortType}`);
  7303. // 缓存键需要包含排序类型,因为不同的排序类型会产生不同的数据
  7304. const albumCacheKey = `${item.name}_sort_${albumDetailSortType}`;
  7305. let albumList = this.albumMap.get(albumCacheKey)
  7306. if (albumList === undefined || ArrayUtil.isEmpty(albumList)) {
  7307. // 使用详情页的排序类型查询
  7308. albumList = await this.table.querySongsByAlbum(item.name, albumDetailSortType, this.isShowFileName);
  7309. if (ArrayUtil.isNotEmpty(albumList)) {
  7310. this.albumMap.set(albumCacheKey, albumList);
  7311. }
  7312. }
  7313. // 设置当前排序类型为详情页排序
  7314. this.sortType = albumDetailSortType;
  7315. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  7316. // 注意:不再调用 Utility.doSortListAscending,因为数据已经按 albumDetailSortType 排序了
  7317. const nextAlbumCountMap = new Map(this.albumSongCountMap);
  7318. nextAlbumCountMap.set(item.name, albumList.length);
  7319. this.albumSongCountMap = nextAlbumCountMap;
  7320. this.isCanBack = true
  7321. this.hasMoreData = false
  7322. this.isLoadingPage = false
  7323. this.pageCache.clear()
  7324. this.pageHasMoreCache.clear()
  7325. this.pageTotalCountCache.clear()
  7326. this.prefetchingPages.clear()
  7327. this.lastScrollTriggerPage = -1
  7328. this.lastVisibleEndIndex = -1
  7329. this.isPagingTransition = false
  7330. if (this.pagingScheduleTimer) {
  7331. clearTimeout(this.pagingScheduleTimer)
  7332. this.pagingScheduleTimer = 0
  7333. }
  7334. this.totalCount = albumList.length
  7335. this.titleName = item.name
  7336. this.currentTitleName = '专辑:' + item.name
  7337. if (item.pixelMapPath) {
  7338. this.currentTitleCover = item.pixelMapPath
  7339. }
  7340. this.updateListData(albumList, true, true) // 详情页立即替换列表,避免旧列表顶部闪现
  7341. this.mScrollMap.set(item.name, this.selectedIndex)
  7342. this.rightTopImage = $r('sys.symbol.chevron_left')
  7343. } else {
  7344. ToastUtil.showToast('未找到该专辑的歌曲');
  7345. return;
  7346. }
  7347. //进入歌单的时候的滚动位置在顶部
  7348. if(this.twoFingerType==4){
  7349. setTimeout(() => {
  7350. this.waterScroller.scrollEdge(Edge.Top)
  7351. this.scroller.scrollEdge(Edge.Top)
  7352. }, 380)
  7353. }else{
  7354. if (this.isGridMusic) {
  7355. this.scroller.scrollEdge(Edge.Top)
  7356. }else{
  7357. this.listScroller.scrollEdge(Edge.Top)
  7358. }
  7359. }
  7360. break;
  7361. case CommonConstants.TYPE_IS_CSJAD:
  7362. return
  7363. break;
  7364. case CommonConstants.TYPE_LOCAL:
  7365. if (this.isIsoLocalFile(item)) {
  7366. await this.openIsoArchiveDialog(item)
  7367. return
  7368. }
  7369. if(item&&item.filePath.toLowerCase().endsWith('.cue')){
  7370. const cueinfo:CueInfo = await parseCueFile(item.filePath)
  7371. const cueTracks:CueTrack[] = cueinfo.tracks
  7372. console.log('onecold cue cueTracks =', JSON.stringify(cueTracks));
  7373. if(ArrayUtil.isNotEmpty(cueTracks)){
  7374. this.showCueDialog(cueTracks,cueinfo)
  7375. }
  7376. // this.showCueSheet = !this.showCueSheet
  7377. return
  7378. }
  7379. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  7380. this.stop();
  7381. }
  7382. if (isOpen) {
  7383. this.currentSong = item
  7384. if (index !== undefined) {
  7385. this.curIndex = index
  7386. }
  7387. this.songList = []
  7388. this.songList.push(item)
  7389. this.sonDataSource.pushArrayData(this.songList)
  7390. this.playQueueScope = 'single'
  7391. }else if(isFromSonPlayList){ //点击来自右下角的播放列表
  7392. this.currentSong = item
  7393. if (index !== undefined) {
  7394. this.curIndex = index
  7395. }
  7396. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  7397. Logger.info(`heanup isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  7398. this.playQueueScope = 'playlist'
  7399. // 确保歌单路径列表已设置(从songList重新构建,以防被清空)
  7400. if (this.currentPlaylistSongFilePaths.length === 0 && this.songList.length > 0) {
  7401. this.currentPlaylistSongFilePaths = this.songList.map(song => song.filePath);
  7402. Logger.info(`heanup isFromSonPlayList - 重新构建歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  7403. }
  7404. }else {
  7405. const globalVideoList = this.buildPlayQueueFromView();
  7406. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  7407. if (this.curIndex < 0) {
  7408. globalVideoList.push(item);
  7409. this.curIndex = globalVideoList.length - 1;
  7410. }
  7411. this.songList = globalVideoList
  7412. this.sonDataSource.pushArrayData(this.songList)
  7413. this.currentSong = this.songList[this.curIndex]
  7414. // 只在非歌单模式下清空歌单路径列表
  7415. if (this.modeType !== 4) {
  7416. this.currentPlaylistSongFilePaths = [];
  7417. Logger.info(`heanup doPlay设置播放列表 - 总歌曲数: ${this.songList.length}, 当前索引: ${this.curIndex}, 当前歌曲: ${this.currentSong?.name}, 已清空歌单路径列表(modeType=${this.modeType})`)
  7418. } else {
  7419. // 歌单模式:确保歌单路径列表已设置
  7420. if (this.currentPlaylistSongFilePaths.length === 0 && this.songList.length > 0) {
  7421. this.currentPlaylistSongFilePaths = this.songList.map(song => song.filePath);
  7422. Logger.info(`heanup doPlay设置播放列表 - 从songList重新构建歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  7423. } else {
  7424. Logger.info(`heanup doPlay设置播放列表 - 歌单模式,保持歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  7425. }
  7426. }
  7427. }
  7428. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  7429. try {
  7430. const localUrl = await this.resolvePlaybackUrlForCurrentSong('doPlay-local');
  7431. this.videoUrl = localUrl || this.currentSong.filePath
  7432. } catch (error) {
  7433. Logger.error(TAG, `本地歌曲构建播放地址失败: ${(error as Error).message}`);
  7434. this.videoUrl = this.currentSong.filePath
  7435. }
  7436. this.name = this.currentSong.name
  7437. this.cover = this.currentSong.pixelMapPath
  7438. this.artist = this.currentSong.artist
  7439. LogUtil.info('onecold this.currentSong.cover =' + this.currentSong.pixelMapPath)
  7440. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  7441. this.startPlayOrResumePlay()
  7442. break;
  7443. case CommonConstants.TYPE_WEBDAV:
  7444. case CommonConstants.TYPE_SMB:
  7445. case CommonConstants.TYPE_NAVIDROME:
  7446. case CommonConstants.TYPE_FTP:
  7447. case CommonConstants.TYPE_BAIDU:
  7448. case CommonConstants.TYPE_JELLYFIN:
  7449. case CommonConstants.TYPE_EMBY:
  7450. case CommonConstants.TYPE_AUDIOSTATION:
  7451. case CommonConstants.TYPE_PLEX:
  7452. case CommonConstants.TYPE_DAOLIYU:
  7453. // 处理网络音频播放(WebDAV/SMB/Navidrome/Jellyfin/Emby/AudioStation/Plex/道理鱼/Baidu)
  7454. Logger.info(`heanup 处理云端音频播放: ${item.name}, URL: ${item.filePath}`)
  7455. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  7456. this.stop();
  7457. }
  7458. if (isOpen) {
  7459. this.currentSong = item
  7460. if (index !== undefined) {
  7461. this.curIndex = index
  7462. }
  7463. this.songList = []
  7464. this.songList.push(item)
  7465. this.sonDataSource.pushArrayData(this.songList)
  7466. } else if (isFromSonPlayList) {
  7467. // 点击来自右下角的播放列表
  7468. this.currentSong = item
  7469. if (index !== undefined) {
  7470. this.curIndex = index
  7471. }
  7472. // 设置播放队列作用域为歌单
  7473. this.playQueueScope = 'playlist'
  7474. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  7475. Logger.info(`heanup 网络音频 isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}, playQueueScope=${this.playQueueScope}`)
  7476. } else {
  7477. // 从全局网络音频列表中查找
  7478. let globalVideoList = this.videoLocalList.filter(video => isRemoteCloudType(video.type)) as VideoItem[];
  7479. this.curIndex = globalVideoList.findIndex(video => video.filePath === item.filePath);
  7480. if (this.curIndex === -1 && index !== undefined) {
  7481. this.curIndex = index;
  7482. }
  7483. this.songList = globalVideoList.length > 0 ? globalVideoList : [item];
  7484. this.currentSong = this.songList[this.curIndex];
  7485. this.sonDataSource.pushArrayData(this.songList)
  7486. }
  7487. await this.hydrateRemoteSongFromDb(this.currentSong);
  7488. await this.hydrateRemoteSongFromDb(this.currentSong);
  7489. AppStorage.setOrCreate('currentSong', this.currentSong);
  7490. const remotePlayLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  7491. const playbackUrl = await this.resolvePlaybackUrlForCurrentSong('doPlay-remote');
  7492. if (!playbackUrl) {
  7493. if (remotePlayLoading) {
  7494. this.hideLoadIng();
  7495. }
  7496. return;
  7497. }
  7498. this.videoUrl = playbackUrl;
  7499. Logger.info(TAG, `WebDAV URL同步构建完成(分支2): ${this.videoUrl}`);
  7500. this.name = this.currentSong.name
  7501. this.cover = this.currentSong.pixelMapPath
  7502. this.artist = this.currentSong.artist
  7503. Logger.info(`heanup 准备播放网络音频 - 歌名: ${this.name}, 艺术家: ${this.artist}, 完整URL: ${this.videoUrl}`)
  7504. this.startPlayOrResumePlay()
  7505. break;
  7506. }
  7507. }
  7508. private async openIsoArchiveDialog(item: VideoItem): Promise<void> {
  7509. if (!item || StrUtil.isEmpty(item.filePath)) {
  7510. Logger.error(TAG, `heanup ISO open dialog invalid path=${item ? item.filePath : ''}`)
  7511. ToastUtil.showToast('ISO 文件无效')
  7512. return
  7513. }
  7514. if (this.isIsoExtracting) {
  7515. if (ArrayUtil.isNotEmpty(this.isoAudioEntries)) {
  7516. if (this.isoSourceFilePath !== item.filePath) {
  7517. ToastUtil.showToast('当前有 ISO 提取任务正在后台执行,已打开提取进度窗口')
  7518. }
  7519. this.presentIsoArchiveDialog()
  7520. return
  7521. }
  7522. ToastUtil.showToast('当前有 ISO 提取任务正在后台执行')
  7523. return
  7524. }
  7525. Logger.info(TAG, `heanup ISO open dialog path=${item.filePath}, name=${item.fileName || item.name}`)
  7526. this.closeIsoDialog()
  7527. this.isoSourceFilePath = item.filePath
  7528. this.isoSourceFileName = item.fileName || item.name
  7529. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  7530. progress: 0,
  7531. backCancel: false,
  7532. autoCancel: false,
  7533. loadColor: this.themeColor,
  7534. fontColor: this.themeColor
  7535. })
  7536. try {
  7537. const task = new taskpool.Task(listIsoAudioEntriesTask, item.filePath)
  7538. const entries = await taskpool.execute(task, taskpool.Priority.HIGH) as IsoArchiveAudioEntry[]
  7539. this.isoAudioEntries = Array.isArray(entries) ? entries : []
  7540. Logger.info(TAG, `heanup ISO list entries done count=${this.isoAudioEntries.length}, path=${item.filePath}`)
  7541. if (ArrayUtil.isEmpty(this.isoAudioEntries)) {
  7542. Logger.error(TAG, `heanup ISO list entries empty path=${item.filePath}`)
  7543. ToastUtil.showToast('ISO 内未发现可提取的媒体文件')
  7544. this.closeIsoDialog()
  7545. return
  7546. }
  7547. this.selectedIsoAudioPaths = []
  7548. } catch (error) {
  7549. Logger.error(TAG, `heanup 解析 ISO 失败: ${(error as Error).message}`)
  7550. ToastUtil.showToast('解析 ISO 失败')
  7551. this.closeIsoDialog()
  7552. return
  7553. } finally {
  7554. if (this.loadingProgressDialogId) {
  7555. DialogHelper.closeDialog(this.loadingProgressDialogId)
  7556. this.loadingProgressDialogId = ''
  7557. }
  7558. }
  7559. this.presentIsoArchiveDialog()
  7560. }
  7561. private presentIsoArchiveDialog(): void {
  7562. if (this.isoComponentId > 0) {
  7563. return
  7564. }
  7565. this.getUIContext().getPromptAction().openCustomDialog({
  7566. builder: () => {
  7567. this.isoComptentBuilder()
  7568. },
  7569. isModal: true,
  7570. showInSubWindow: false,
  7571. maskColor: Color.Transparent,
  7572. dialogTransition: TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  7573. .animation({ duration: 600, curve: Curve.Smooth }),
  7574. maskTransition: TransitionEffect.opacity(0.5)
  7575. .animation({ duration: 600, curve: Curve.Smooth })
  7576. }).then((dialogId: number) => {
  7577. this.isoComponentId = dialogId
  7578. }).catch((error: BusinessError) => {
  7579. Logger.error(TAG, `heanup 打开 ISO 弹窗失败: ${error.message}`)
  7580. this.closeIsoDialog()
  7581. })
  7582. }
  7583. private toggleIsoEntrySelection(path: string, checked: boolean): void {
  7584. const selectedPathSet: Set<string> = new Set<string>(this.selectedIsoAudioPaths)
  7585. if (checked) {
  7586. selectedPathSet.add(path)
  7587. } else {
  7588. selectedPathSet.delete(path)
  7589. }
  7590. this.selectedIsoAudioPaths = this.isoAudioEntries
  7591. .filter((entry: IsoArchiveAudioEntry) => selectedPathSet.has(entry.path))
  7592. .map((entry: IsoArchiveAudioEntry) => entry.path)
  7593. Logger.info(TAG,
  7594. `heanup ISO toggle selection path=${path}, checked=${checked}, total=${this.selectedIsoAudioPaths.length}`)
  7595. }
  7596. private toggleIsoEntrySelectAll(): void {
  7597. if (this.selectedIsoAudioPaths.length === this.isoAudioEntries.length) {
  7598. this.selectedIsoAudioPaths = []
  7599. Logger.info(TAG, 'heanup ISO toggle select all cleared')
  7600. return
  7601. }
  7602. this.selectedIsoAudioPaths = this.isoAudioEntries.map((entry: IsoArchiveAudioEntry) => entry.path)
  7603. Logger.info(TAG, `heanup ISO toggle select all count=${this.selectedIsoAudioPaths.length}`)
  7604. }
  7605. private startIsoExtractProgressWatcher(entries: Array<IsoArchiveAudioEntry>, destinationDir: string): void {
  7606. this.stopIsoExtractProgressWatcher()
  7607. this.isoExtractExpectedOutputPaths = this.buildIsoExtractExpectedOutputPaths(entries, destinationDir)
  7608. this.isoExtractTotalBytes = entries.reduce((total: number, entry: IsoArchiveAudioEntry) => {
  7609. const size = entry && entry.size > 0 ? entry.size : 0
  7610. return total + size
  7611. }, 0)
  7612. this.isoExtractReceivedTaskProgress = false
  7613. this.isoExtractDisplayedProgress = 0
  7614. this.isoExtractLastActivityTime = Date.now()
  7615. if (this.isoExtractTotalBytes <= 0 || ArrayUtil.isEmpty(this.isoExtractExpectedOutputPaths)) {
  7616. return
  7617. }
  7618. this.isoExtractProgressTimer = setInterval(() => {
  7619. this.updateIsoExtractProgressFromFiles()
  7620. }, 500)
  7621. }
  7622. private stopIsoExtractProgressWatcher(): void {
  7623. if (this.isoExtractProgressTimer) {
  7624. clearInterval(this.isoExtractProgressTimer)
  7625. this.isoExtractProgressTimer = 0
  7626. }
  7627. this.isoExtractExpectedOutputPaths = []
  7628. this.isoExtractTotalBytes = 0
  7629. this.isoExtractReceivedTaskProgress = false
  7630. this.isoExtractLastActivityTime = 0
  7631. }
  7632. private markIsoExtractActivity(): void {
  7633. this.isoExtractLastActivityTime = Date.now()
  7634. }
  7635. private updateIsoExtractProgressFromFiles(): void {
  7636. if (this.isoExtractTotalBytes <= 0 || ArrayUtil.isEmpty(this.isoExtractExpectedOutputPaths) ||
  7637. this.isoExtractReceivedTaskProgress) {
  7638. return
  7639. }
  7640. let writtenBytes = 0
  7641. let existingCount = 0
  7642. for (let i = 0; i < this.isoExtractExpectedOutputPaths.length; i++) {
  7643. const outputPath = this.isoExtractExpectedOutputPaths[i]
  7644. if (!FileUtil.accessSync(outputPath)) {
  7645. continue
  7646. }
  7647. existingCount++
  7648. try {
  7649. const stat = fs.statSync(outputPath) as fs.Stat
  7650. if (typeof stat.size === 'number' && stat.size > 0) {
  7651. writtenBytes += stat.size
  7652. }
  7653. } catch (_error) {
  7654. }
  7655. }
  7656. let progress = 0
  7657. if (writtenBytes > 0) {
  7658. progress = Math.ceil((writtenBytes / this.isoExtractTotalBytes) * 100)
  7659. if (progress > 99) {
  7660. progress = 99
  7661. }
  7662. this.markIsoExtractActivity()
  7663. } else if (existingCount > 0) {
  7664. progress = 1
  7665. this.markIsoExtractActivity()
  7666. }
  7667. if (progress > 0) {
  7668. this.updateIsoExtractProgressState(progress,
  7669. `正在提取 ${progress}% (${existingCount}/${this.isoExtractExpectedOutputPaths.length})`)
  7670. return
  7671. }
  7672. if (this.isoExtractTask && this.isoExtractLastActivityTime > 0 &&
  7673. Date.now() - this.isoExtractLastActivityTime > this.isoExtractStallTimeoutMs) {
  7674. Logger.warn(TAG, `heanup ISO 提取进度长时间无变化: timeout=${this.isoExtractStallTimeoutMs}`)
  7675. this.markIsoExtractActivity()
  7676. this.updateIsoExtractProgressState(1, '准备提取 1%')
  7677. }
  7678. }
  7679. private updateIsoExtractProgressState(progress: number, message: string, currentName: string = '',
  7680. force: boolean = false): void {
  7681. let safeProgress = progress
  7682. if (safeProgress < 0) {
  7683. safeProgress = 0
  7684. }
  7685. if (safeProgress > 100) {
  7686. safeProgress = 100
  7687. }
  7688. if (!force && safeProgress < this.isoExtractDisplayedProgress) {
  7689. return
  7690. }
  7691. this.isoExtractDisplayedProgress = safeProgress
  7692. this.isoExtractProgress = safeProgress
  7693. this.isoExtractProgressText = message
  7694. if (force || StrUtil.isNotEmpty(currentName)) {
  7695. this.isoExtractCurrentEntryName = currentName
  7696. }
  7697. }
  7698. private resetIsoExtractProgressState(): void {
  7699. this.isoExtractProgress = 0
  7700. this.isoExtractProgressText = ''
  7701. this.isoExtractCurrentEntryName = ''
  7702. this.isoExtractDisplayedProgress = 0
  7703. }
  7704. private buildIsoExtractExpectedOutputPaths(entries: Array<IsoArchiveAudioEntry>, destinationDir: string): Array<string> {
  7705. const outputPaths: Array<string> = []
  7706. const occupiedPaths: Set<string> = new Set<string>()
  7707. for (let i = 0; i < entries.length; i++) {
  7708. const entry = entries[i]
  7709. const fileName = entry.name || this.getIsoLastPathSegment(entry.path)
  7710. const outputPath = this.buildIsoExpectedOutputPath(destinationDir, fileName, occupiedPaths)
  7711. occupiedPaths.add(outputPath)
  7712. outputPaths.push(outputPath)
  7713. }
  7714. return outputPaths
  7715. }
  7716. private buildIsoExpectedOutputPath(destinationDir: string, fileName: string, occupiedPaths: Set<string>): string {
  7717. const cleanName = this.sanitizeIsoOutputFileName(fileName)
  7718. const extension = this.getIsoOutputFileExtension(cleanName)
  7719. const baseName = extension.length > 0 ? cleanName.substring(0, cleanName.length - extension.length) : cleanName
  7720. let candidatePath = `${this.trimIsoOutputTrailingSeparator(destinationDir)}/${cleanName}`
  7721. let suffix = 0
  7722. while (occupiedPaths.has(candidatePath) || FileUtil.accessSync(candidatePath)) {
  7723. suffix++
  7724. candidatePath = `${this.trimIsoOutputTrailingSeparator(destinationDir)}/${baseName} (${suffix})${extension}`
  7725. }
  7726. return candidatePath
  7727. }
  7728. private sanitizeIsoOutputFileName(fileName: string): string {
  7729. const lastSegment = this.getIsoLastPathSegment(fileName)
  7730. let sanitized = ''
  7731. for (let i = 0; i < lastSegment.length; i++) {
  7732. const char = lastSegment[i]
  7733. if (char === '/' || char === '\\' || char === ':' || char === '*' || char === '?' || char === '"' ||
  7734. char === '<' || char === '>' || char === '|') {
  7735. sanitized += '_'
  7736. } else {
  7737. sanitized += char
  7738. }
  7739. }
  7740. if (sanitized.trim().length === 0) {
  7741. return 'iso_audio.bin'
  7742. }
  7743. return sanitized
  7744. }
  7745. private getIsoLastPathSegment(path: string): string {
  7746. const normalizedPath = path.replace(/\\/g, '/')
  7747. const lastSeparator = normalizedPath.lastIndexOf('/')
  7748. if (lastSeparator < 0) {
  7749. return normalizedPath
  7750. }
  7751. return normalizedPath.substring(lastSeparator + 1)
  7752. }
  7753. private getIsoOutputFileExtension(fileName: string): string {
  7754. const lastDot = fileName.lastIndexOf('.')
  7755. if (lastDot < 0) {
  7756. return ''
  7757. }
  7758. return fileName.substring(lastDot)
  7759. }
  7760. private trimIsoOutputTrailingSeparator(path: string): string {
  7761. if (path.endsWith('/')) {
  7762. return path.substring(0, path.length - 1)
  7763. }
  7764. return path
  7765. }
  7766. private cancelIsoExtraction(reason?: string): void {
  7767. const currentTask = this.isoExtractTask
  7768. Logger.info(TAG,
  7769. `heanup ISO cancel request reason=${reason || ''}, hasTask=${currentTask ? 'true' : 'false'}`)
  7770. this.isoExtractCanceled = true
  7771. this.isoExtractCancelMessage = reason ? reason : ''
  7772. this.isoExtractTask = undefined
  7773. this.updateIsoExtractProgressState(this.isoExtractProgress, '正在停止提取...', this.isoExtractCurrentEntryName, true)
  7774. if (currentTask) {
  7775. try {
  7776. taskpool.terminateTask(currentTask)
  7777. } catch (error) {
  7778. Logger.error(TAG, `heanup 终止 ISO 提取任务失败: ${(error as Error).message}`)
  7779. }
  7780. }
  7781. }
  7782. private moveIsoExtractionToBackground(): void {
  7783. this.closeIsoDialog(false)
  7784. ToastUtil.showToast('ISO 提取已转入后台')
  7785. }
  7786. private async extractSelectedIsoAudioFiles(): Promise<void> {
  7787. if (this.isIsoExtracting) {
  7788. return
  7789. }
  7790. if (ArrayUtil.isEmpty(this.selectedIsoAudioPaths)) {
  7791. ToastUtil.showToast('请先选择要提取的文件')
  7792. return
  7793. }
  7794. const selectedPathSet: Set<string> = new Set<string>(this.selectedIsoAudioPaths)
  7795. const selectedEntries = this.isoAudioEntries
  7796. .filter((entry: IsoArchiveAudioEntry) => selectedPathSet.has(entry.path))
  7797. if (ArrayUtil.isEmpty(selectedEntries)) {
  7798. ToastUtil.showToast('未找到要提取的文件')
  7799. return
  7800. }
  7801. const hasSacdTrack: boolean = selectedEntries.some((entry: IsoArchiveAudioEntry) => entry.entryType === 'sacd_track')
  7802. const destinationDir: string = this.currentPath
  7803. this.isIsoExtracting = true
  7804. this.isoExtractCanceled = false
  7805. this.isoExtractCancelMessage = ''
  7806. this.isoExtractDestinationDir = destinationDir
  7807. Logger.info(TAG,
  7808. `heanup ISO extract start file=${this.isoSourceFilePath}, selected=${selectedEntries.length}, ` +
  7809. `hasSacd=${hasSacdTrack}, destinationDir=${destinationDir}`)
  7810. Logger.info(TAG,
  7811. `heanup ISO selected entries: ${selectedEntries.map((entry: IsoArchiveAudioEntry) => entry.path).join(', ')}`)
  7812. this.resetIsoExtractProgressState()
  7813. this.updateIsoExtractProgressState(1, '准备提取 1%', '', true)
  7814. this.startIsoExtractProgressWatcher(selectedEntries, destinationDir)
  7815. try {
  7816. const extractStartedAt = Date.now()
  7817. const outputPaths: string[] = this.buildIsoExtractExpectedOutputPaths(selectedEntries, destinationDir)
  7818. const payloadJson = JSON.stringify({
  7819. isoPath: this.isoSourceFilePath,
  7820. destinationDir,
  7821. entries: selectedEntries,
  7822. outputPaths
  7823. })
  7824. const task = new taskpool.Task(extractIsoAudioEntriesTask, payloadJson)
  7825. this.isoExtractTask = task
  7826. task.onReceiveData((progressData: IsoExtractProgressMessage) => {
  7827. this.markIsoExtractActivity()
  7828. const progress = typeof progressData.progress === 'number' ? Math.floor(progressData.progress) : 0
  7829. Logger.info(TAG,
  7830. `heanup ISO task receive stage=${progressData.stage || ''}, progress=${progress}, name=${progressData.name || ''}`)
  7831. if (progress > 1 && !this.isoExtractReceivedTaskProgress) {
  7832. this.isoExtractReceivedTaskProgress = true
  7833. if (this.isoExtractProgressTimer) {
  7834. clearInterval(this.isoExtractProgressTimer)
  7835. this.isoExtractProgressTimer = 0
  7836. }
  7837. Logger.info(TAG, `heanup ISO 提取切换为任务进度: progress=${progress}, stage=${progressData.stage || ''}`)
  7838. }
  7839. const stageText = progressData.stage === 'prepare' ? '准备提取' :
  7840. (progressData.stage === 'done' ? '提取完成' : (progressData.stage === 'error' ? '提取异常' : '正在提取'))
  7841. if (progress > this.isoExtractDisplayedProgress || progressData.stage !== 'extract') {
  7842. Logger.info(TAG,
  7843. `heanup ISO 提取任务进度: stage=${progressData.stage || ''}, progress=${progress}, ` +
  7844. `name=${progressData.name || ''}`)
  7845. }
  7846. this.updateIsoExtractProgressState(progress, `${stageText} ${progress}%`, progressData.name || '')
  7847. })
  7848. const result = await taskpool.execute(task, taskpool.Priority.HIGH) as IsoExtractTaskResult
  7849. const extractElapsedMs = Date.now() - extractStartedAt
  7850. this.isoExtractTask = undefined
  7851. Logger.info(TAG, `heanup ISO extract task completed canceled=${this.isoExtractCanceled}, elapsedMs=${extractElapsedMs}`)
  7852. if (this.isoExtractCanceled) {
  7853. return
  7854. }
  7855. const extractedPaths = result?.extractedPaths || []
  7856. const failedEntries = result?.failedEntries || []
  7857. const failureDetails = result?.failureDetails || []
  7858. Logger.info(TAG,
  7859. `heanup ISO extract result extracted=${extractedPaths.length}, failed=${failedEntries.length}, details=${failureDetails.length}`)
  7860. let importErrorMessage: string = ''
  7861. let importedCount: number = 0
  7862. if (ArrayUtil.isNotEmpty(extractedPaths)) {
  7863. const importStartedAt = Date.now()
  7864. try {
  7865. await this.postProcessExtractedIsoFiles(extractedPaths, selectedEntries, outputPaths)
  7866. importedCount = await this.importExtractedFilesToDirectory(extractedPaths, destinationDir)
  7867. Logger.info(TAG,
  7868. `heanup ISO import extracted files success elapsedMs=${Date.now() - importStartedAt}, ` +
  7869. `importedCount=${importedCount}`)
  7870. } catch (importError) {
  7871. importErrorMessage = (importError as Error).message || '导入媒体库失败'
  7872. Logger.error(TAG,
  7873. `heanup ISO import extracted files failed elapsedMs=${Date.now() - importStartedAt}, ` +
  7874. `message=${importErrorMessage}`)
  7875. }
  7876. }
  7877. if (extractedPaths.length > 0 && failedEntries.length > 0) {
  7878. if (StrUtil.isNotEmpty(importErrorMessage)) {
  7879. ToastUtil.showToast(`提取完成,成功 ${extractedPaths.length} 个,失败 ${failedEntries.length} 个,导入失败`)
  7880. } else if (importedCount > 0) {
  7881. ToastUtil.showToast(`提取完成,成功 ${extractedPaths.length} 个,失败 ${failedEntries.length} 个,已入库 ${importedCount} 个音频文件`)
  7882. } else {
  7883. ToastUtil.showToast(`提取完成,成功 ${extractedPaths.length} 个,失败 ${failedEntries.length} 个`)
  7884. }
  7885. } else if (extractedPaths.length > 0) {
  7886. if (StrUtil.isNotEmpty(importErrorMessage)) {
  7887. ToastUtil.showToast(`提取完成,但导入媒体库失败: ${importErrorMessage}`)
  7888. } else if (importedCount > 0) {
  7889. ToastUtil.showToast(`提取完成,已提取 ${extractedPaths.length} 个文件,入库 ${importedCount} 个音频文件`)
  7890. } else {
  7891. ToastUtil.showToast(`提取完成,已提取 ${extractedPaths.length} 个文件`)
  7892. }
  7893. } else if (ArrayUtil.isNotEmpty(failureDetails)) {
  7894. const firstFailure: IsoExtractFailureDetail = failureDetails[0]
  7895. const reasonText = firstFailure.reason && firstFailure.reason.length > 0 ? firstFailure.reason : '提取失败'
  7896. ToastUtil.showToast(reasonText)
  7897. } else if (hasSacdTrack) {
  7898. ToastUtil.showToast('SACD ISO 轨道提取失败')
  7899. } else {
  7900. ToastUtil.showToast('提取失败')
  7901. }
  7902. } catch (error) {
  7903. this.isoExtractTask = undefined
  7904. if (this.isoExtractCanceled) {
  7905. return
  7906. }
  7907. Logger.error(TAG, `heanup 提取 ISO 文件失败: ${(error as Error).message}`)
  7908. ToastUtil.showToast('提取 ISO 文件失败')
  7909. } finally {
  7910. const shouldResetDialogState: boolean = this.isoComponentId <= 0
  7911. this.stopIsoExtractProgressWatcher()
  7912. this.isoExtractTask = undefined
  7913. this.isIsoExtracting = false
  7914. Logger.info(TAG,
  7915. `heanup ISO extract finally canceled=${this.isoExtractCanceled}, cancelMessage=${this.isoExtractCancelMessage}`)
  7916. if (this.isoExtractCanceled && this.isoExtractCancelMessage.length > 0) {
  7917. ToastUtil.showToast(this.isoExtractCancelMessage)
  7918. }
  7919. this.isoExtractCanceled = false
  7920. this.isoExtractCancelMessage = ''
  7921. if (shouldResetDialogState) {
  7922. this.resetIsoDialogState()
  7923. } else {
  7924. this.selectedIsoAudioPaths = []
  7925. this.resetIsoExtractProgressState()
  7926. }
  7927. }
  7928. }
  7929. private async postProcessExtractedIsoFiles(extractedPaths: Array<string>, selectedEntries: Array<IsoArchiveAudioEntry>,
  7930. outputPaths: Array<string>): Promise<void> {
  7931. if (ArrayUtil.isEmpty(extractedPaths) || ArrayUtil.isEmpty(selectedEntries) || ArrayUtil.isEmpty(outputPaths)) {
  7932. return
  7933. }
  7934. const entryByOutputPath: Map<string, IsoArchiveAudioEntry> = new Map<string, IsoArchiveAudioEntry>()
  7935. for (let i = 0; i < outputPaths.length && i < selectedEntries.length; i++) {
  7936. entryByOutputPath.set(outputPaths[i], selectedEntries[i])
  7937. }
  7938. for (let i = 0; i < extractedPaths.length; i++) {
  7939. const extractedPath = extractedPaths[i]
  7940. const entry = entryByOutputPath.get(extractedPath)
  7941. if (!entry) {
  7942. continue
  7943. }
  7944. await this.postProcessExtractedIsoEntry(extractedPath, entry)
  7945. }
  7946. }
  7947. private async postProcessExtractedIsoEntry(filePath: string, entry: IsoArchiveAudioEntry): Promise<void> {
  7948. if (!Utility.isMusicByExtension(filePath)) {
  7949. return
  7950. }
  7951. const hasEmbeddedMetadata: boolean = StrUtil.isNotEmpty(entry.title) || StrUtil.isNotEmpty(entry.album) ||
  7952. StrUtil.isNotEmpty(entry.artist) || StrUtil.isNotEmpty(entry.albumArtist) || StrUtil.isNotEmpty(entry.comment) ||
  7953. !!(entry.trackNumber && entry.trackNumber > 0)
  7954. if (entry.entryType !== 'sacd_track' && !hasEmbeddedMetadata) {
  7955. return
  7956. }
  7957. const tags: FFMpegTags = this.buildIsoExtractedMetadata(entry)
  7958. if (Object.keys(tags).length > 0) {
  7959. try {
  7960. const metadataResult = await repairAudioMetadata(filePath, '', tags, true, '')
  7961. Logger.info(TAG,
  7962. `heanup ISO metadata post-process path=${filePath}, success=${metadataResult}, type=${entry.entryType || ''}`)
  7963. } catch (error) {
  7964. Logger.error(TAG, `heanup ISO metadata post-process failed path=${filePath}, message=${(error as Error).message}`)
  7965. }
  7966. }
  7967. if (!filePath.toLowerCase().endsWith('.dsf')) {
  7968. return
  7969. }
  7970. const coverUrl = await this.resolveIsoExtractCoverUrl(entry)
  7971. if (StrUtil.isEmpty(coverUrl)) {
  7972. return
  7973. }
  7974. try {
  7975. const coverResult = await changeMusicCover(this.context, filePath, coverUrl, true, '')
  7976. Logger.info(TAG, `heanup ISO cover post-process path=${filePath}, success=${coverResult}`)
  7977. } catch (error) {
  7978. Logger.error(TAG, `heanup ISO cover post-process failed path=${filePath}, message=${(error as Error).message}`)
  7979. }
  7980. }
  7981. private buildIsoExtractedMetadata(entry: IsoArchiveAudioEntry): FFMpegTags {
  7982. const metadata: FFMpegTags = {}
  7983. const title = entry.title || this.getIsoEntryBaseName(entry.name || entry.path)
  7984. if (StrUtil.isNotEmpty(title)) {
  7985. metadata.title = title
  7986. metadata.TITLE = title
  7987. }
  7988. if (StrUtil.isNotEmpty(entry.artist)) {
  7989. metadata.artist = entry.artist
  7990. metadata.ARTIST = entry.artist
  7991. }
  7992. if (StrUtil.isNotEmpty(entry.album)) {
  7993. metadata.album = entry.album
  7994. metadata.ALBUM = entry.album
  7995. }
  7996. if (entry.trackNumber && entry.trackNumber > 0) {
  7997. metadata.track = `${entry.trackNumber}`
  7998. metadata.TRACK = `${entry.trackNumber}`
  7999. }
  8000. if (StrUtil.isNotEmpty(entry.albumArtist)) {
  8001. metadata.ALBUMARTIST = entry.albumArtist
  8002. metadata.album_artist = entry.albumArtist
  8003. metadata.TPE2 = entry.albumArtist
  8004. }
  8005. if (StrUtil.isNotEmpty(entry.comment)) {
  8006. metadata.comment = entry.comment
  8007. metadata.COMMENT = entry.comment
  8008. metadata.COMM = entry.comment
  8009. }
  8010. return metadata
  8011. }
  8012. private getIsoEntryBaseName(fileName: string): string {
  8013. const lastSegment = this.getIsoLastPathSegment(fileName)
  8014. const lastDot = lastSegment.lastIndexOf('.')
  8015. if (lastDot <= 0) {
  8016. return lastSegment
  8017. }
  8018. return lastSegment.substring(0, lastDot)
  8019. }
  8020. private async resolveIsoExtractCoverUrl(entry: IsoArchiveAudioEntry): Promise<string> {
  8021. const title = entry.title || this.getIsoEntryBaseName(entry.name || entry.path)
  8022. const artist = entry.artist || entry.albumArtist || ''
  8023. if (StrUtil.isEmpty(title) || PreferencesUtil.getStringSync('COVER_API', '') === '') {
  8024. return ''
  8025. }
  8026. try {
  8027. const coverUrl = await NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', ''))
  8028. if (StrUtil.isNotEmpty(coverUrl) && coverUrl !== 'unknown') {
  8029. return coverUrl
  8030. }
  8031. } catch (error) {
  8032. Logger.error(TAG,
  8033. `heanup ISO resolve cover failed title=${title}, artist=${artist}, message=${(error as Error).message}`)
  8034. }
  8035. return ''
  8036. }
  8037. private async importExtractedFilesToDirectory(paths: Array<string>, destinationDir: string): Promise<number> {
  8038. if (ArrayUtil.isEmpty(paths)) {
  8039. return 0
  8040. }
  8041. let importedCount: number = 0
  8042. for (let i = 0; i < paths.length; i++) {
  8043. const filePath = paths[i]
  8044. if (destinationDir === this.lockPath || !Utility.isMeidaByExtension(filePath) ||
  8045. filePath.endsWith('.lrc') || filePath.endsWith('.srt') || Utility.isIsoByExtension(filePath)) {
  8046. continue
  8047. }
  8048. const mediaItem = await Utility.uriGetMusicAssetsFromFile(this.context, filePath,
  8049. CommonConstants.TYPE_LOCAL, this.autoParseMusicName)
  8050. await new Promise<void>((resolve) => {
  8051. this.table.insert(mediaItem, (_id: number) => resolve())
  8052. })
  8053. importedCount++
  8054. }
  8055. this.cache.delete(destinationDir)
  8056. if (this.currentPath === destinationDir) {
  8057. this.pageCache.clear()
  8058. this.pageHasMoreCache.clear()
  8059. this.pageTotalCountCache.clear()
  8060. if (destinationDir === this.lockPath) {
  8061. this.getSortedFiles(destinationDir, true)
  8062. } else {
  8063. await this.resetAndLoadFirstPage()
  8064. }
  8065. }
  8066. return importedCount
  8067. }
  8068. private resetIsoDialogState(): void {
  8069. this.isoAudioEntries = []
  8070. this.selectedIsoAudioPaths = []
  8071. this.isoSourceFileName = ''
  8072. this.isoSourceFilePath = ''
  8073. this.isoExtractDestinationDir = ''
  8074. this.isIsoExtracting = false
  8075. this.stopIsoExtractProgressWatcher()
  8076. this.isoExtractTask = undefined
  8077. this.resetIsoExtractProgressState()
  8078. }
  8079. private closeIsoDialog(reset: boolean = true): void {
  8080. if (this.isoComponentId > 0) {
  8081. try {
  8082. this.getUIContext().getPromptAction().closeCustomDialog(this.isoComponentId)
  8083. } catch (_error) {
  8084. }
  8085. this.isoComponentId = 0
  8086. }
  8087. if (!reset) {
  8088. return
  8089. }
  8090. this.resetIsoDialogState()
  8091. }
  8092. @Builder
  8093. isoComptentBuilder() {
  8094. IsoExtractComptent({
  8095. isoFileName: this.isoSourceFileName,
  8096. entries: this.isoAudioEntries,
  8097. selectedPaths: this.selectedIsoAudioPaths,
  8098. isLongNameRoLL: this.isLongNameRoLL,
  8099. isExtracting: this.isIsoExtracting,
  8100. extractProgress: this.isoExtractProgress,
  8101. extractProgressText: this.isoExtractProgressText,
  8102. extractCurrentName: this.isoExtractCurrentEntryName,
  8103. onToggleSelection: (path: string, checked: boolean) => {
  8104. this.toggleIsoEntrySelection(path, checked)
  8105. },
  8106. onToggleSelectAll: () => {
  8107. this.toggleIsoEntrySelectAll()
  8108. },
  8109. onExtract: async () => {
  8110. await this.extractSelectedIsoAudioFiles()
  8111. },
  8112. onRunInBackground: () => {
  8113. this.moveIsoExtractionToBackground()
  8114. },
  8115. onStopExtract: () => {
  8116. this.cancelIsoExtraction('已取消 ISO 提取')
  8117. },
  8118. onCancel: () => {
  8119. if (this.isIsoExtracting) {
  8120. this.moveIsoExtractionToBackground()
  8121. return
  8122. }
  8123. this.closeIsoDialog()
  8124. }
  8125. })
  8126. }
  8127. private cueComponentId: number = 0
  8128. private async handleCueTrackImport(cueinfo: CueInfo): Promise<void> {
  8129. try {
  8130. let sourceItem = Utility.getItemByFilePath(this.videoLocalList, cueinfo.filePath);
  8131. if (!sourceItem) {
  8132. sourceItem = await this.table.queryVideoByFilePath(cueinfo.filePath) || undefined;
  8133. }
  8134. const importedItems = await importCueTracks(this.context, this.table, cueinfo, sourceItem);
  8135. if (ArrayUtil.isEmpty(importedItems)) {
  8136. ToastUtil.showToast('未导入到任何分轨');
  8137. return;
  8138. }
  8139. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId);
  8140. await this.resetAndLoadFirstPage();
  8141. ToastUtil.showToast(`分轨完成,已入库 ${importedItems.length} 首`);
  8142. } catch (error) {
  8143. Logger.error(TAG, `CUE 分轨入库失败: ${(error as Error).message}`);
  8144. ToastUtil.showToast('分轨失败');
  8145. }
  8146. }
  8147. //显示cue分轨列表对话框
  8148. showCueDialog(cueTracks:CueTrack[],cueinfo:CueInfo){
  8149. this.getUIContext().getPromptAction().openCustomDialog({
  8150. builder: () => {
  8151. this.cueComptentBuilder(cueTracks,cueinfo)
  8152. },
  8153. isModal:true,
  8154. showInSubWindow:false,
  8155. maskColor: Color.Transparent,
  8156. dialogTransition: // 设置弹窗内容显示的过渡效果
  8157. TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  8158. .animation({ duration: 600, curve: Curve.Smooth }),
  8159. maskTransition: // 设置蒙层显示的过渡效果
  8160. TransitionEffect.opacity(0.5)
  8161. .animation({ duration: 600, curve: Curve.Smooth })
  8162. }).then((dialogId: number) => {
  8163. this.cueComponentId = dialogId
  8164. })
  8165. .catch((error: BusinessError) => {
  8166. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  8167. })
  8168. }
  8169. @Builder
  8170. cueComptentBuilder(cueTracks:CueTrack[]=[],cueinfo:CueInfo){
  8171. CueComptent({
  8172. title:cueinfo.title,
  8173. cueTracks:cueTracks,
  8174. isLongNameRoLL:this.isLongNameRoLL,
  8175. onCancel:()=>{
  8176. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId)
  8177. },
  8178. onSplitTracks: async ()=>{
  8179. await this.handleCueTrackImport(cueinfo)
  8180. },
  8181. onDoItemClick: async (item: CueTrack, index: number)=>{
  8182. //获取cueinfo对应的filePath
  8183. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  8184. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, cueinfo.filePath)
  8185. this.currentSong = Utility.getItemByFilePath(globalVideoList, cueinfo.filePath)
  8186. console.info('onecold cueinfo.filePath=', cueinfo.filePath)
  8187. console.info('onecold this.currentSong =', JSON.stringify(this.currentSong))
  8188. if (this.currentSong){
  8189. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  8190. this.stop();//播放之前先停止之前播放。
  8191. }
  8192. this.songList = globalVideoList
  8193. this.sonDataSource.pushArrayData(this.songList)
  8194. if (this.currentSong) {
  8195. try {
  8196. const cueUrl = await this.resolvePlaybackUrlForCurrentSong('cue-track-play');
  8197. if (!cueUrl) {
  8198. return;
  8199. }
  8200. this.videoUrl = cueUrl;
  8201. } catch (error) {
  8202. Logger.error(TAG, `CUE 点播构建播放地址失败: ${(error as Error).message}`);
  8203. this.videoUrl = this.currentSong.filePath;
  8204. }
  8205. }
  8206. this.name = item.title||this.currentSong.name
  8207. this.cover = this.currentSong.pixelMapPath
  8208. this.artist = item.performer||this.currentSong.artist
  8209. this.currentSong.name = this.name
  8210. this.currentSong.artist = this.artist
  8211. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  8212. this.startPlayOrResumePlay(item.startOffset)//从cue的某个位置开始播放
  8213. }
  8214. }
  8215. })
  8216. }
  8217. @State isFrontWhite: boolean = false
  8218. private showCoverScaleGuideIfNeeded(): void {
  8219. const hasShown = PreferencesUtil.getBooleanSync(PREF_PLAY_COVER_SCALE_GUIDE_SHOWN, false)
  8220. if (hasShown) {
  8221. return
  8222. }
  8223. this.isShowCoverScaleGuide = true
  8224. setTimeout(() => {
  8225. if (this.isShowCoverScaleGuide) {
  8226. this.dismissCoverScaleGuide()
  8227. }
  8228. }, 9000)
  8229. }
  8230. private dismissCoverScaleGuide(): void {
  8231. this.isShowCoverScaleGuide = false
  8232. PreferencesUtil.put(PREF_PLAY_COVER_SCALE_GUIDE_SHOWN, true)
  8233. }
  8234. private resolveMiniBarDismissTarget() {
  8235. const viewportWidthVp = this.windowWidth > 0 ? px2vp(this.windowWidth) : 360
  8236. const viewportHeightVp = this.windowHeight > 0 ? px2vp(this.windowHeight) : 800
  8237. const useFixedBottomMargin = DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_2IN1
  8238. || this.curDisplayIsHiCar
  8239. return resolvePlayerDismissMorphTarget(viewportWidthVp, viewportHeightVp, this.bottomSafeHeight, useFixedBottomMargin)
  8240. }
  8241. private clearPlayDismissTimer(): void {
  8242. if (this.playDismissTimer >= 0) {
  8243. clearTimeout(this.playDismissTimer)
  8244. this.playDismissTimer = -1
  8245. }
  8246. }
  8247. private clearPlayOpenTimer(): void {
  8248. if (this.playOpenTimer >= 0) {
  8249. clearTimeout(this.playOpenTimer)
  8250. this.playOpenTimer = -1
  8251. }
  8252. }
  8253. private resetMusicPlayDismissState(): void {
  8254. this.clearPlayDismissTimer()
  8255. this.clearPlayOpenTimer()
  8256. this.playOpenFromMiniBarPending = false
  8257. this.translateY = 0
  8258. this.playDismissTranslateX = 0
  8259. this.playDismissScale = 1
  8260. this.playDismissScaleY = 1
  8261. this.playDismissOpacity = 1
  8262. this.playDismissBorderRadius = 0
  8263. this.playDismissProxySize = 0
  8264. this.playDismissProxyOpacity = 0
  8265. this.scaleValueImage = 1
  8266. this.scaleValueText = 1
  8267. this.playDragUiOpacity = 1
  8268. }
  8269. private preparePlayerViewOpenFromMiniBar(): void {
  8270. const target = this.resolveMiniBarDismissTarget()
  8271. this.playOpenFromMiniBarPending = true
  8272. this.translateY = target.translateY
  8273. this.playDismissTranslateX = 0
  8274. this.playDismissScale = 0.9
  8275. this.playDismissScaleY = 0.8
  8276. this.playDismissOpacity = 0
  8277. this.playDismissBorderRadius = 48
  8278. this.playDismissProxySize = 0
  8279. this.playDismissProxyOpacity = 0
  8280. this.playDragUiOpacity = 0
  8281. this.scaleValueImage = 0.82
  8282. this.scaleValueText = 0.88
  8283. }
  8284. private startPlayerViewOpenAnimationIfNeeded(): void {
  8285. if (!this.playOpenFromMiniBarPending) {
  8286. return
  8287. }
  8288. this.playOpenFromMiniBarPending = false
  8289. this.getUIContext()?.animateTo({
  8290. duration: this.playOpenExpandDuration,
  8291. curve: Curve.Friction
  8292. }, () => {
  8293. this.playDismissProxySize = 0
  8294. this.playDismissProxyOpacity = 0
  8295. this.translateY = 0
  8296. this.playDismissTranslateX = 0
  8297. this.playDismissScale = 1
  8298. this.playDismissScaleY = 1
  8299. this.playDismissOpacity = 1
  8300. this.playDismissBorderRadius = 0
  8301. this.playDragUiOpacity = 1
  8302. this.scaleValueImage = 1
  8303. this.scaleValueText = 1
  8304. })
  8305. }
  8306. setShowPlayTrue(fromMiniBar: boolean = false){
  8307. this.clearPlayDismissTimer()
  8308. this.clearPlayOpenTimer()
  8309. if (this.isShowPlay) {
  8310. return
  8311. }
  8312. if (fromMiniBar) {
  8313. this.preparePlayerViewOpenFromMiniBar()
  8314. } else {
  8315. this.resetMusicPlayDismissState()
  8316. }
  8317. this.isShowPlay = true;
  8318. this.showCoverScaleGuideIfNeeded()
  8319. }
  8320. private closePlayerViewWithMiniBarAnimation(): void {
  8321. if (!this.isShowPlay || this.playDismissOpacity < 1) {
  8322. return
  8323. }
  8324. const target = this.resolveMiniBarDismissTarget()
  8325. this.clearPlayDismissTimer()
  8326. this.clearPlayOpenTimer()
  8327. this.getUIContext()?.animateTo({
  8328. duration: this.playDismissContentDuration + 40,
  8329. curve: Curve.Sharp
  8330. }, () => {
  8331. this.translateY = target.translateY
  8332. this.playDismissTranslateX = 0
  8333. this.playDismissScale = 0.9
  8334. this.playDismissScaleY = 0.8
  8335. this.playDismissOpacity = 0.04
  8336. this.playDismissBorderRadius = 48
  8337. this.playDismissProxySize = 0
  8338. this.playDismissProxyOpacity = 0
  8339. this.playDragUiOpacity = 0
  8340. this.scaleValueImage = 0.8
  8341. this.scaleValueText = 0.86
  8342. })
  8343. this.playDismissTimer = setTimeout(() => {
  8344. this.playDismissTimer = -1
  8345. this.isShowPlay = false
  8346. this.isShowCoverScaleGuide = false
  8347. }, this.playDismissContentDuration + 56)
  8348. }
  8349. setShowPlayFalse(){
  8350. this.closePlayerViewWithMiniBarAnimation()
  8351. }
  8352. //打开播放页
  8353. showPlayerView() {
  8354. console.info('onecold showPlayerView this.songList'+ JSON.stringify(this.songList))
  8355. if (ArrayUtil.isNotEmpty(this.songList)) {
  8356. // this.setShowPlayTrue()
  8357. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
  8358. this.initLyric(lyricPath);
  8359. this.startAutoHide();
  8360. } else {
  8361. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  8362. }
  8363. }
  8364. //打开播放列表
  8365. openPlayList(){
  8366. if (ArrayUtil.isNotEmpty(this.songList)) {
  8367. this.isShowSheet = !this.isShowSheet;
  8368. this.isFrontWhite = false
  8369. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  8370. this.scrollIndex()
  8371. // 只有在播放本地音乐时才自动加载完整列表
  8372. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_LOCAL) {
  8373. void this.hydrateFullMediaPlayListIfNeeded();
  8374. }
  8375. } else {
  8376. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  8377. }
  8378. }
  8379. scrollIndex(){
  8380. try {
  8381. setTimeout(() => {
  8382. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  8383. if(this.curIndex>60){
  8384. this.playListScroller.scrollToIndex(this.curIndex,false, ScrollAlign.CENTER)
  8385. }else{
  8386. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  8387. }
  8388. })
  8389. }, 123)
  8390. }catch (error) {
  8391. console.error(`onecold scrollIndex出错: ${error}`);
  8392. }
  8393. }
  8394. scrollIndexMain(dialogId?:string){
  8395. try {
  8396. setTimeout(() => {
  8397. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  8398. console.info('heanup scrollIndexMain this.curIndex='+this.curIndex)
  8399. if(dialogId)
  8400. DialogHelper.closeDialog(dialogId)
  8401. let isAni:boolean = false
  8402. if(this.curIndex<50){
  8403. isAni = true
  8404. }
  8405. if(this.twoFingerType==4){
  8406. this.waterScroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  8407. }else{
  8408. if(this.isGridMusic){
  8409. this.scroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  8410. }else{
  8411. this.listScroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  8412. }
  8413. }
  8414. })
  8415. }, 123)
  8416. }catch (error) {
  8417. console.error(`onecold scrollIndexMain出错: ${error}`);
  8418. }
  8419. }
  8420. // 智能定位当前播放歌曲,如果当前页没有则加载完整列表
  8421. async locateCurrentSong(): Promise<void> {
  8422. if (!this.currentSong) {
  8423. console.warn("heanup locateCurrentSong: 当前没有播放的歌曲");
  8424. return;
  8425. }
  8426. // 检查当前播放歌曲是否在已加载的列表中
  8427. const targetIndex = Utility.getIndexFromList(this.videoLocalList, this.currentSong.filePath);
  8428. if (targetIndex > 0) {
  8429. // 歌曲在当前列表中,直接滚动
  8430. console.info("heanup locateCurrentSong: 找到歌曲,索引=" + targetIndex);
  8431. this.curIndex = targetIndex;
  8432. this.scrollIndexMain();
  8433. } else {
  8434. // 歌曲不在当前列表中,加载当前歌曲再第几页完整列表后再定位
  8435. console.info("heanup locateCurrentSong: 歌曲不在当前列表,开始加载完整列表");
  8436. const dialogID = DialogHelper.showLoadingDialog()
  8437. await this.hydrateFullMediaPlayListIfNeeded(false);
  8438. this.curIndex = Utility.getIndexFromList(this.videoLocalList, this.currentSong.filePath);
  8439. this.scrollIndexMain(dialogID);
  8440. }
  8441. }
  8442. //播放列表布局
  8443. @Builder
  8444. PlayListSheet() {
  8445. Column() {
  8446. this.PlayList()
  8447. }
  8448. .width('100%')
  8449. .height('100%')
  8450. }
  8451. @State titleStr: string = ''
  8452. @State ablumStr: string = ''
  8453. @State artistStr: string = ''
  8454. @State lyricConStr: string = ''
  8455. @State currentEditItem: string = ''
  8456. @State yearStr: string = ''
  8457. @State trackStr: string = ''
  8458. @State genreStr: string = ''
  8459. @State imagePathStr: string = ''
  8460. @State albumArtistStr: string = ''
  8461. @State composerStr: string = ''
  8462. @State lyricistStr: string = ''
  8463. @State commentStr: string = ''
  8464. @State discStr: string = ''
  8465. doUpdateData() {
  8466. setTimeout(async () => {
  8467. if (this.modeType === 0) {
  8468. this.deleteCache(this.currentPath)
  8469. await this.resetAndLoadFirstPage();
  8470. }else if (this.modeType === 1){
  8471. await this.resetAndLoadFirstPage();
  8472. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  8473. }
  8474. }, 500)
  8475. }
  8476. doAllUpdateData() {
  8477. setTimeout(async () => {
  8478. if (this.modeType === 0) {
  8479. this.deleteCache(this.currentPath)
  8480. await this.resetAndLoadFirstPage();
  8481. }else{
  8482. await this.resetAndLoadFirstPage();
  8483. }
  8484. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  8485. workerInstance.postMessage({ code: 3, data: this.context });
  8486. workerInstance.postMessage({ code: 4, data: this.context });
  8487. }, 999)
  8488. }
  8489. private delayMs(ms: number): Promise<void> {
  8490. return new Promise(resolve => {
  8491. setTimeout(() => resolve(), ms);
  8492. });
  8493. }
  8494. private async appendItemsSmoothly(items: VideoItem[]): Promise<void> {
  8495. if (!items || items.length === 0) {
  8496. return;
  8497. }
  8498. const isMediaLibraryListMode = this.isMediaLibraryListMode();
  8499. const isHeavyGridWaterMode = this.isGridMusic || this.twoFingerType == 4;
  8500. const directAppendThreshold = isHeavyGridWaterMode ? 8 : (isMediaLibraryListMode ? 6 : 12);
  8501. if (!this.isScrolling || items.length <= directAppendThreshold) {
  8502. this.videoLocalList.push(...items);
  8503. this.dataSource.appendArrayData(items);
  8504. return;
  8505. }
  8506. const chunkSize = isHeavyGridWaterMode
  8507. ? Math.max(3, Math.min(6, Math.floor(this.pageSize * 0.15)))
  8508. : (isMediaLibraryListMode
  8509. ? Math.max(2, Math.min(4, Math.floor(this.pageSize * 0.08)))
  8510. : Math.max(4, Math.min(8, Math.floor(this.pageSize * 0.18))));
  8511. const chunkDelay = isHeavyGridWaterMode ? 12 : (isMediaLibraryListMode ? 10 : 8);
  8512. for (let index = 0; index < items.length; index += chunkSize) {
  8513. const chunk = items.slice(index, Math.min(index + chunkSize, items.length));
  8514. this.videoLocalList.push(...chunk);
  8515. this.dataSource.appendArrayData(chunk);
  8516. if (index + chunkSize < items.length) {
  8517. await this.delayMs(chunkDelay);
  8518. }
  8519. }
  8520. }
  8521. /**
  8522. * 加载指定页的数据
  8523. */
  8524. private async loadPage(pageIndex: number, append: boolean = true): Promise<void> {
  8525. try {
  8526. // 1. 检查缓存
  8527. if (this.pageCache.has(pageIndex)) {
  8528. Logger.info('heanup LocalMusic', `loadPage: 从缓存加载 page=${pageIndex}`);
  8529. const inMediaLibraryWarmup = this.modeType === 1 && pageIndex === 0 && !append && this.isMediaLibraryWarmupWindow();
  8530. const cachedData = this.pageCache.get(pageIndex)!;
  8531. const cachedHasMore = this.pageHasMoreCache.get(pageIndex);
  8532. const cachedTotal = this.pageTotalCountCache.get(pageIndex);
  8533. if (cachedHasMore !== undefined) {
  8534. this.hasMoreData = cachedHasMore;
  8535. }
  8536. if (cachedTotal !== undefined) {
  8537. this.totalCount = cachedTotal;
  8538. if (this.modeType === 1) {
  8539. this.mediaKuCount = cachedTotal;
  8540. }
  8541. }
  8542. if (append) {
  8543. this.prefetchListThumbsFromItems(cachedData, 26);
  8544. this.prefetchGridWaterThumbsFromItems(cachedData, this.twoFingerType == 4 ? 56 : 42);
  8545. await this.appendItemsSmoothly(cachedData);
  8546. } else {
  8547. this.videoLocalList = cachedData;
  8548. this.dataSource.pushArrayData(this.videoLocalList);
  8549. if (inMediaLibraryWarmup) {
  8550. this.prefetchListThumbsFromItems(cachedData, 8);
  8551. } else {
  8552. this.prefetchListThumbsFromItems(cachedData, 30);
  8553. this.prefetchGridWaterThumbsFromItems(cachedData, this.twoFingerType == 4 ? 56 : 42);
  8554. }
  8555. }
  8556. this.setButtonStatus();
  8557. if (inMediaLibraryWarmup) {
  8558. this.scheduleAlphaBetRebuild(900);
  8559. } else {
  8560. this.markAlphaBetDirty();
  8561. }
  8562. if (this.hasMoreData) {
  8563. if (inMediaLibraryWarmup) {
  8564. if (this.mediaLibraryWarmupPrefetchTimer) {
  8565. clearTimeout(this.mediaLibraryWarmupPrefetchTimer);
  8566. }
  8567. this.mediaLibraryWarmupPrefetchTimer = setTimeout(() => {
  8568. this.mediaLibraryWarmupPrefetchTimer = 0;
  8569. if (this.modeType === 1 && !this.isCanBack) {
  8570. this.prefetchFollowingPages(pageIndex + 1);
  8571. }
  8572. }, 900) as number;
  8573. } else {
  8574. this.prefetchFollowingPages(pageIndex + 1);
  8575. }
  8576. }
  8577. return;
  8578. }
  8579. this.isLoadingPage = true;
  8580. Logger.info('heanup LocalMusic', `loadPage: 开始加载 page=${pageIndex}, size=${this.pageSize}, mode=${this.modeType}`);
  8581. // 2. 构造查询参数
  8582. const options: PageQueryOptions = {
  8583. pageIndex: pageIndex,
  8584. pageSize: this.pageSize,
  8585. sortType: this.sortType,
  8586. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  8587. isShowFileName: this.isShowFileName
  8588. };
  8589. // 根据 modeType 补充查询条件
  8590. if (this.modeType === 0) {
  8591. options.parentPath = this.currentPath;
  8592. }
  8593. // 3. 执行查询
  8594. let result: PageQueryResult = { items: [], totalCount: 0, hasMore: false };
  8595. switch (this.modeType) {
  8596. case 0:
  8597. result = await this.table.queryByParentPathPaged(options);
  8598. result.items = this.filterOutLocalIsoItems(result.items);
  8599. // modeType=0时,第一页需要添加文件夹列表
  8600. if (pageIndex === 0 && !this.isSearchMode) {
  8601. const directories: VideoItem[] = await this.loadDirectories(this.currentPath);
  8602. const isoItems: VideoItem[] = this.getLocalIsoItems(this.currentPath);
  8603. result.items = [...directories, ...isoItems, ...result.items];
  8604. result.totalCount += directories.length + isoItems.length;
  8605. }
  8606. break;
  8607. case 1:
  8608. result = await this.table.queryMediaLibraryPaged(options);
  8609. break;
  8610. case 2:
  8611. result = await this.table.queryArtistsPaged(options);
  8612. break;
  8613. case 3:
  8614. result = await this.table.queryAlbumsPaged(options);
  8615. break;
  8616. default:
  8617. result = await this.table.queryMediaLibraryPaged(options);
  8618. break;
  8619. }
  8620. if (!result || result.items.length === 0) {
  8621. Logger.info('heanup LocalMusic', 'loadPage: 查询结果为空');
  8622. this.isLoadingPage = false;
  8623. this.hasMoreData = false;
  8624. // 仅首页为空时清空,后续页为空只终止继续分页
  8625. if (pageIndex === 0) {
  8626. this.totalCount = 0;
  8627. this.videoLocalList = [];
  8628. this.dataSource.pushArrayData(this.videoLocalList);
  8629. this.setButtonStatus();
  8630. this.markAlphaBetDirty();
  8631. }
  8632. return;
  8633. }
  8634. // 4. 更新状态和缓存
  8635. this.totalCount = result.totalCount;
  8636. this.hasMoreData = result.hasMore;
  8637. if (this.modeType === 1) {
  8638. this.mediaKuCount = result.totalCount;
  8639. }
  8640. if (this.modeType === 2 && result.countMap) {
  8641. this.mergeArtistCountMap(result.countMap);
  8642. } else if (this.modeType === 3 && result.countMap) {
  8643. this.mergeAlbumCountMap(result.countMap);
  8644. }
  8645. Logger.info('heanup LocalMusic', `loadPage: 查询完成 items=${result.items.length}, total=${result.totalCount}, hasMore=${result.hasMore}`);
  8646. // 缓存管理 - 只保留最近3页
  8647. this.pageCache.set(pageIndex, result.items);
  8648. this.pageHasMoreCache.set(pageIndex, result.hasMore);
  8649. this.pageTotalCountCache.set(pageIndex, result.totalCount);
  8650. this.cleanOldCache(pageIndex);
  8651. // 5. 更新显示列表
  8652. const inMediaLibraryWarmup = this.modeType === 1 && pageIndex === 0 && !append && this.isMediaLibraryWarmupWindow();
  8653. if (append) {
  8654. this.prefetchListThumbsFromItems(result.items, 26);
  8655. this.prefetchGridWaterThumbsFromItems(result.items, this.twoFingerType == 4 ? 56 : 42);
  8656. await this.appendItemsSmoothly(result.items);
  8657. } else {
  8658. this.videoLocalList = result.items;
  8659. this.dataSource.pushArrayData(this.videoLocalList);
  8660. if (inMediaLibraryWarmup) {
  8661. this.prefetchListThumbsFromItems(result.items, 8);
  8662. } else {
  8663. this.prefetchListThumbsFromItems(result.items, 30);
  8664. this.prefetchGridWaterThumbsFromItems(result.items, this.twoFingerType == 4 ? 56 : 42);
  8665. }
  8666. }
  8667. this.setButtonStatus();
  8668. if (inMediaLibraryWarmup) {
  8669. this.scheduleAlphaBetRebuild(900);
  8670. } else {
  8671. this.markAlphaBetDirty();
  8672. }
  8673. if (inMediaLibraryWarmup) {
  8674. if (this.mediaLibraryWarmupPrefetchTimer) {
  8675. clearTimeout(this.mediaLibraryWarmupPrefetchTimer);
  8676. }
  8677. this.mediaLibraryWarmupPrefetchTimer = setTimeout(() => {
  8678. this.mediaLibraryWarmupPrefetchTimer = 0;
  8679. if (this.modeType === 1 && !this.isCanBack) {
  8680. this.prefetchFollowingPages(pageIndex + 1);
  8681. }
  8682. }, 900) as number;
  8683. } else {
  8684. this.prefetchFollowingPages(pageIndex + 1);
  8685. }
  8686. this.isLoadingPage = false;
  8687. } catch (err) {
  8688. const error = err as Error;
  8689. Logger.error('heanup LocalMusic', `loadPage error: ${error.message}`);
  8690. // ToastUtil.showToast('加载数据失败');
  8691. this.isLoadingPage = false;
  8692. this.hasMoreData = false;
  8693. }
  8694. }
  8695. /**
  8696. * 清理旧缓存 - 只保留当前页前后各1页
  8697. */
  8698. private cleanOldCache(currentPage: number): void {
  8699. const pagesToKeep = new Set([currentPage - 1, currentPage, currentPage + 1]);
  8700. const keysToDelete: number[] = [];
  8701. this.pageCache.forEach((_, page) => {
  8702. if (!pagesToKeep.has(page)) {
  8703. keysToDelete.push(page);
  8704. }
  8705. });
  8706. keysToDelete.forEach(page => {
  8707. this.pageCache.delete(page);
  8708. this.pageHasMoreCache.delete(page);
  8709. this.pageTotalCountCache.delete(page);
  8710. });
  8711. if (keysToDelete.length > 0) {
  8712. Logger.info('heanup LocalMusic', `cleanOldCache: 清理了 ${keysToDelete.length} 页缓存`);
  8713. }
  8714. }
  8715. private async prefetchNextPage(nextPage: number): Promise<void> {
  8716. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  8717. return;
  8718. }
  8719. if (!this.hasMoreData || this.pageCache.has(nextPage) || this.prefetchingPages.has(nextPage)) {
  8720. return;
  8721. }
  8722. const expectedModeType = this.modeType;
  8723. const expectedSortType = this.sortType;
  8724. const expectedIsShowFileName = this.isShowFileName;
  8725. const expectedSearchKeyword = this.isSearchMode ? this.searchText : '';
  8726. const expectedParentPath = this.currentPath;
  8727. this.prefetchingPages.add(nextPage);
  8728. try {
  8729. const options: PageQueryOptions = {
  8730. pageIndex: nextPage,
  8731. pageSize: this.pageSize,
  8732. sortType: this.sortType,
  8733. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  8734. isShowFileName: this.isShowFileName
  8735. };
  8736. if (this.modeType === 0) {
  8737. options.parentPath = this.currentPath;
  8738. }
  8739. let result: PageQueryResult = { items: [], totalCount: 0, hasMore: false };
  8740. switch (this.modeType) {
  8741. case 0:
  8742. result = await this.table.queryByParentPathPaged(options);
  8743. result.items = this.filterOutLocalIsoItems(result.items);
  8744. break;
  8745. case 1:
  8746. result = await this.table.queryMediaLibraryPaged(options);
  8747. break;
  8748. case 2:
  8749. result = await this.table.queryArtistsPaged(options);
  8750. if (result.countMap) {
  8751. this.mergeArtistCountMap(result.countMap);
  8752. }
  8753. break;
  8754. case 3:
  8755. result = await this.table.queryAlbumsPaged(options);
  8756. if (result.countMap) {
  8757. this.mergeAlbumCountMap(result.countMap);
  8758. }
  8759. break;
  8760. default:
  8761. result = await this.table.queryMediaLibraryPaged(options);
  8762. break;
  8763. }
  8764. const currentSearchKeyword = this.isSearchMode ? this.searchText : '';
  8765. if (expectedModeType !== this.modeType ||
  8766. expectedSortType !== this.sortType ||
  8767. expectedIsShowFileName !== this.isShowFileName ||
  8768. expectedSearchKeyword !== currentSearchKeyword ||
  8769. (expectedModeType === 0 && expectedParentPath !== this.currentPath)) {
  8770. Logger.info('heanup LocalMusic', `prefetchNextPage: 上下文已变化,放弃写入 page=${nextPage}`);
  8771. return;
  8772. }
  8773. this.pageHasMoreCache.set(nextPage, result.hasMore);
  8774. this.pageTotalCountCache.set(nextPage, result.totalCount);
  8775. if (result.items.length > 0) {
  8776. this.pageCache.set(nextPage, result.items);
  8777. this.prefetchGridWaterThumbsFromItems(result.items, this.twoFingerType == 4 ? 48 : 36);
  8778. this.cleanOldCache(nextPage);
  8779. if (nextPage === this.currentPage + 1 && !this.isLoadingPage && !this.isPagingTransition
  8780. && this.lastVisibleEndIndex >= 0 && this.videoLocalList.length > 0) {
  8781. const seenRatio = (this.lastVisibleEndIndex + 1) / Math.max(this.videoLocalList.length, 1);
  8782. if (seenRatio >= Math.max(0.14, this.getDynamicAppendStartRatio() - 0.12)) {
  8783. Logger.info('heanup LocalMusic',
  8784. `prefetchNextPage: 下一页缓存已就绪,提前衔接 page=${nextPage}, ratio=${seenRatio}`);
  8785. this.scheduleLoadNextPage(8);
  8786. }
  8787. }
  8788. }
  8789. } catch (err) {
  8790. const error = err as Error;
  8791. Logger.warn('heanup LocalMusic', `prefetchNextPage error: ${error.message}`);
  8792. } finally {
  8793. this.prefetchingPages.delete(nextPage);
  8794. }
  8795. }
  8796. private mergeArtistCountMap(countMap: Map<string, number>): void {
  8797. const nextMap = new Map(this.artistSongCountMap);
  8798. countMap.forEach((count, artist) => {
  8799. nextMap.set(artist, count);
  8800. });
  8801. this.artistSongCountMap = nextMap;
  8802. }
  8803. private mergeAlbumCountMap(countMap: Map<string, number>): void {
  8804. const nextMap = new Map(this.albumSongCountMap);
  8805. countMap.forEach((count, album) => {
  8806. nextMap.set(album, count);
  8807. });
  8808. this.albumSongCountMap = nextMap;
  8809. }
  8810. private getArtistSongCount(artist: string): number {
  8811. return this.artistSongCountMap.get(artist) ?? this.artistMap.get(artist)?.length ?? 0;
  8812. }
  8813. private getAlbumSongCount(album: string): number {
  8814. return this.albumSongCountMap.get(album) ?? this.albumMap.get(album)?.length ?? 0;
  8815. }
  8816. /**
  8817. * 加载文件夹列表(仅用于modeType=0的首页模式)
  8818. */
  8819. private async loadDirectories(curPath: string): Promise<VideoItem[]> {
  8820. try {
  8821. Logger.info('heanup LocalMusic', `loadDirectories: 开始加载文件夹 path=${curPath}`);
  8822. // 检查缓存
  8823. const cacheKey = curPath + "_dirList";
  8824. const cachedDirList = this.findCache(cacheKey);
  8825. if (cachedDirList !== undefined && Array.isArray(cachedDirList)) {
  8826. Logger.info('heanup LocalMusic', `loadDirectories: 从缓存加载 count=${cachedDirList.length}`);
  8827. return cachedDirList as VideoItem[];
  8828. }
  8829. // 从文件系统读取
  8830. const fileList = FileUtil.listFileSync(curPath);
  8831. const directories: VideoItem[] = [];
  8832. for (let i = 0; i < fileList.length; i++) {
  8833. const path = curPath + '/' + fileList[i];
  8834. if (FileUtil.isDirectory(path)) {
  8835. const item: VideoItem = new VideoItem(
  8836. fileList[i].toString(),
  8837. fileList[i].toString(),
  8838. path,
  8839. CommonConstants.TYPE_IS_DIR,
  8840. 0,
  8841. ''
  8842. );
  8843. if (this.isShowDir(item.name)) {
  8844. directories.push(item);
  8845. }
  8846. }
  8847. }
  8848. // 排序
  8849. Utility.doSortListAscending(directories);
  8850. // 缓存文件夹列表
  8851. if (curPath === this.rootPath) {
  8852. this.dirList = directories;
  8853. this.addCache(cacheKey, directories);
  8854. }
  8855. Logger.info('heanup LocalMusic', `loadDirectories: 加载完成 count=${directories.length}`);
  8856. return directories;
  8857. } catch (err) {
  8858. const error = err as Error;
  8859. Logger.error('heanup LocalMusic', `loadDirectories error: ${error.message}`);
  8860. return [];
  8861. }
  8862. }
  8863. /**
  8864. * 构建播放队列(避免一次性加载全量)
  8865. */
  8866. private buildPlayQueueFromView(): Array<VideoItem> {
  8867. if (this.modeType === 4) {
  8868. this.playQueueScope = 'playlist';
  8869. return this.currentSongList;
  8870. }
  8871. if (this.isHistory) {
  8872. this.playQueueScope = 'history';
  8873. return this.historyList;
  8874. }
  8875. if (this.isFavMusic) {
  8876. this.playQueueScope = 'fav';
  8877. return this.favList;
  8878. }
  8879. this.playQueueScope = 'view';
  8880. return Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL);
  8881. }
  8882. private openSpecialLocalList(target: string): void {
  8883. this.mType = 0
  8884. this.isShowDrawer = false
  8885. this.offsetX = 0
  8886. this.isHistory = false
  8887. this.isFavMusic = false
  8888. if (target === 'recent') {
  8889. this.titleName = '最近播放'
  8890. this.currentTitleName = '最近播放'
  8891. this.currentTitleCover = $r('app.media.alt')
  8892. this.updateListData(this.historyList, true)
  8893. if (ArrayUtil.isNotEmpty(this.historyList)) {
  8894. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  8895. }
  8896. this.isHistory = true
  8897. return
  8898. }
  8899. if (target === 'favorite') {
  8900. this.titleName = '我的收藏'
  8901. this.currentTitleName = '我的收藏'
  8902. this.currentTitleCover = $r('app.media.alt')
  8903. this.updateListData(this.favList, true)
  8904. if (ArrayUtil.isNotEmpty(this.favList)) {
  8905. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  8906. }
  8907. this.isFavMusic = true
  8908. }
  8909. }
  8910. private async tryLoadNextPageForPlayback(): Promise<void> {
  8911. if (this.playQueueScope !== 'view') {
  8912. return;
  8913. }
  8914. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  8915. return;
  8916. }
  8917. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  8918. return;
  8919. }
  8920. await this.loadNextPage();
  8921. const nextList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL);
  8922. if (nextList.length > this.songList.length) {
  8923. this.songList = nextList;
  8924. this.sonDataSource.pushArrayData(this.songList);
  8925. }
  8926. }
  8927. /**
  8928. * 加载更多流媒体歌曲(Navidrome/Jellyfin/Emby/AudioStation/Plex)
  8929. * 当播放列表弹窗滚动到底部时调用
  8930. */
  8931. private async loadMoreNavidromeSongs(): Promise<void> {
  8932. const beforeCount = this.songList.length;
  8933. const hasMore = hasMoreData();
  8934. Logger.info('heanup', `开始加载更多流媒体歌曲, 当前数量=${beforeCount}, hasMoreData=${hasMore}`);
  8935. if (!hasMore) {
  8936. Logger.info('heanup', '没有更多数据可加载(hasMoreData=false)');
  8937. return;
  8938. }
  8939. // 触发加载更多(会更新NavidromePlaylistStore中的数据)
  8940. const success = await triggerLoadMoreSongs(1);
  8941. Logger.info('heanup', `triggerLoadMoreSongs返回: ${success}`);
  8942. if (success) {
  8943. // 获取更新后的完整列表
  8944. const updatedList = getNavidromeVideoItems();
  8945. Logger.info('heanup', `更新后列表长度: ${updatedList.length}`);
  8946. if (updatedList.length > beforeCount) {
  8947. Logger.info('heanup', `流媒体歌曲加载成功: ${beforeCount} -> ${updatedList.length}`);
  8948. this.songList = updatedList;
  8949. this.sonDataSource.pushArrayData(this.songList);
  8950. } else {
  8951. Logger.info('heanup', '列表长度未增加');
  8952. }
  8953. } else {
  8954. Logger.info('heanup', '流媒体歌曲加载未返回新数据(triggerLoadMoreSongs=false)');
  8955. }
  8956. }
  8957. /**
  8958. * 重置分页状态并加载首页
  8959. */
  8960. private async resetAndLoadFirstPage(clearExistingList: boolean = true): Promise<void> {
  8961. Logger.info('heanup LocalMusic', 'resetAndLoadFirstPage: 重置分页状态');
  8962. this.currentPage = 0;
  8963. if (clearExistingList) {
  8964. this.videoLocalList = [];
  8965. }
  8966. this.pageCache.clear();
  8967. this.pageHasMoreCache.clear();
  8968. this.pageTotalCountCache.clear();
  8969. this.prefetchingPages.clear();
  8970. this.hasMoreData = true;
  8971. this.totalCount = 0;
  8972. this.lastScrollTriggerPage = -1;
  8973. this.lastVisibleEndIndex = -1;
  8974. this.listScrollAlphaCheckAt = 0;
  8975. this.listScrollPagingCheckAt = 0;
  8976. this.listScrollLastAlphaStart = -1;
  8977. this.listScrollLastPagingEnd = -1;
  8978. this.gridScrollPagingCheckAt = 0;
  8979. this.gridScrollLastPagingEnd = -1;
  8980. this.waterScrollPagingCheckAt = 0;
  8981. this.waterScrollLastPagingEnd = -1;
  8982. this.listVisibleStart = -1;
  8983. this.listVisibleEnd = -1;
  8984. this.listThumbWarmupCheckAt = 0;
  8985. this.listThumbWarmupStart = -1;
  8986. this.listThumbWarmupEnd = -1;
  8987. this.gridThumbWarmupCheckAt = 0;
  8988. this.gridThumbWarmupStart = -1;
  8989. this.gridThumbWarmupEnd = -1;
  8990. this.waterThumbWarmupCheckAt = 0;
  8991. this.waterThumbWarmupStart = -1;
  8992. this.waterThumbWarmupEnd = -1;
  8993. this.gridVisibleStart = -1;
  8994. this.gridVisibleEnd = -1;
  8995. this.waterVisibleStart = -1;
  8996. this.waterVisibleEnd = -1;
  8997. this.gridWaterLastActiveTs = 0;
  8998. this.isPagingTransition = false;
  8999. if (this.pagingScheduleTimer) {
  9000. clearTimeout(this.pagingScheduleTimer);
  9001. this.pagingScheduleTimer = 0;
  9002. }
  9003. if (this.gridWaterScrollIdleTimer) {
  9004. clearTimeout(this.gridWaterScrollIdleTimer);
  9005. this.gridWaterScrollIdleTimer = 0;
  9006. }
  9007. this.coverThumbCache.clearPending();
  9008. this.pendingCoverThumbRefresh = false;
  9009. if (this.modeType === 2) {
  9010. this.artistSongCountMap = new Map();
  9011. } else if (this.modeType === 3) {
  9012. this.albumSongCountMap = new Map();
  9013. }
  9014. await this.loadPage(0, false);
  9015. }
  9016. private markGridWaterScrollingActive(): void {
  9017. if (!this.isScrolling) {
  9018. this.isScrolling = true;
  9019. }
  9020. const now = Date.now();
  9021. if (now - this.gridWaterLastActiveTs < 80) {
  9022. return;
  9023. }
  9024. this.gridWaterLastActiveTs = now;
  9025. if (this.gridWaterScrollIdleTimer) {
  9026. clearTimeout(this.gridWaterScrollIdleTimer);
  9027. }
  9028. this.gridWaterScrollIdleTimer = setTimeout(() => {
  9029. this.gridWaterScrollIdleTimer = 0;
  9030. if (this.isScrolling) {
  9031. this.isScrolling = false;
  9032. }
  9033. this.flushPendingCoverThumbRefresh();
  9034. }, 120);
  9035. }
  9036. private updateTitleBarByScrollOffset(currentOffsetY: number): void {
  9037. if (!this.autoHideTitle) {
  9038. return;
  9039. }
  9040. const now = Date.now();
  9041. if (now - this.titleBarLastCheckTs < 36) {
  9042. return;
  9043. }
  9044. this.titleBarLastCheckTs = now;
  9045. const delta = currentOffsetY - this.prevOffsetY;
  9046. if (Math.abs(delta) < this.titleBarToggleMinDelta) {
  9047. return;
  9048. }
  9049. if (delta > 0) {
  9050. if (this.isShowTitleBar) {
  9051. this.isShowTitleBar = false;
  9052. }
  9053. } else {
  9054. if (!this.isShowTitleBar) {
  9055. this.isShowTitleBar = true;
  9056. }
  9057. }
  9058. this.prevOffsetY = currentOffsetY;
  9059. }
  9060. private shouldPrefetchSecondPage(): boolean {
  9061. if (this.isMediaLibraryListMode()) {
  9062. return this.pageSize <= 120;
  9063. }
  9064. if (this.pageSize > 60) {
  9065. return false;
  9066. }
  9067. return this.isGridMusic || this.twoFingerType == 4;
  9068. }
  9069. private isMediaLibraryListMode(): boolean {
  9070. return this.modeType === 1 && !this.isGridMusic && this.twoFingerType != 4;
  9071. }
  9072. private isMediaLibraryWarmupWindow(): boolean {
  9073. if (this.modeType !== 1 || this.isCanBack) {
  9074. return false;
  9075. }
  9076. if (this.mediaLibraryEnterTs <= 0) {
  9077. return false;
  9078. }
  9079. return Date.now() - this.mediaLibraryEnterTs < 1800;
  9080. }
  9081. private getDynamicPreloadStartRatio(): number {
  9082. if (this.twoFingerType == 4) {
  9083. return 0.10;
  9084. }
  9085. if (this.isGridMusic) {
  9086. return 0.14;
  9087. }
  9088. if (this.isMediaLibraryListMode()) {
  9089. return 0.12;
  9090. }
  9091. return this.preloadStartRatio;
  9092. }
  9093. private getDynamicAppendStartRatio(): number {
  9094. if (this.twoFingerType == 4) {
  9095. return 0.18;
  9096. }
  9097. if (this.isGridMusic) {
  9098. return 0.22;
  9099. }
  9100. if (this.isMediaLibraryListMode()) {
  9101. return 0.22;
  9102. }
  9103. return this.appendStartRatio;
  9104. }
  9105. private getDynamicEarlyAppendReserveCount(): number {
  9106. if (this.twoFingerType == 4) {
  9107. return Math.max(this.earlyAppendReserveCount, Math.floor(this.pageSize * 0.9));
  9108. }
  9109. if (this.isGridMusic) {
  9110. return Math.max(this.earlyAppendReserveCount, Math.floor(this.pageSize * 0.82));
  9111. }
  9112. if (this.isMediaLibraryListMode()) {
  9113. return Math.max(this.earlyAppendReserveCount, Math.floor(this.pageSize * 0.75));
  9114. }
  9115. return this.earlyAppendReserveCount;
  9116. }
  9117. private prefetchFollowingPages(nextPage: number): void {
  9118. void this.prefetchNextPage(nextPage);
  9119. if (this.shouldPrefetchSecondPage()) {
  9120. void this.prefetchNextPage(nextPage + 1);
  9121. }
  9122. }
  9123. private scrollToTopForCurrentLayout(): void {
  9124. if (this.twoFingerType == 4) {
  9125. this.waterScroller.scrollEdge(Edge.Top);
  9126. this.scroller.scrollEdge(Edge.Top);
  9127. return;
  9128. }
  9129. if (this.isGridMusic) {
  9130. this.scroller.scrollEdge(Edge.Top);
  9131. return;
  9132. }
  9133. this.listScroller.scrollEdge(Edge.Top);
  9134. }
  9135. private getListImageSource(item: VideoItem, index: number, coverVersion: number = 0): ResourceStr {
  9136. const fallback = item.type == CommonConstants.TYPE_IS_DIR ? $r('app.media.dir_alt') : $r('app.media.alt');
  9137. if (coverVersion < -1) {
  9138. return fallback;
  9139. }
  9140. if (StrUtil.isEmpty(item.pixelMapPath)) {
  9141. return fallback;
  9142. }
  9143. const sourceUri = item.pixelMapPath as string;
  9144. this.initCoverThumbCacheIfNeeded();
  9145. const targetSize = this.getListThumbTargetSize();
  9146. const cachedThumb = this.coverThumbCache.getThumbUri(sourceUri, targetSize);
  9147. if (cachedThumb) {
  9148. return cachedThumb;
  9149. }
  9150. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  9151. const preloadBuffer = Math.max(8, Math.floor(this.pageSize * 0.2));
  9152. const hasRange = this.listVisibleStart >= 0 && this.listVisibleEnd >= 0;
  9153. const isNearVisible = !hasRange ||
  9154. (index >= this.listVisibleStart - preloadBuffer && index <= this.listVisibleEnd + preloadBuffer);
  9155. if (isNearVisible) {
  9156. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  9157. }
  9158. }
  9159. return sourceUri;
  9160. }
  9161. private getListThumbTargetSize(): number {
  9162. if (this.twoFingerType == 1) {
  9163. return 96;
  9164. }
  9165. if (this.twoFingerType == 2) {
  9166. return 112;
  9167. }
  9168. return 128;
  9169. }
  9170. private prefetchListThumbsFromItems(items: VideoItem[], limit: number = 24): void {
  9171. if (!this.isMediaLibraryListMode() || !items || items.length === 0) {
  9172. return;
  9173. }
  9174. this.initCoverThumbCacheIfNeeded();
  9175. const targetSize = this.getListThumbTargetSize();
  9176. const maxCount = Math.min(limit, items.length);
  9177. for (let i = 0; i < maxCount; i++) {
  9178. const item = items[i];
  9179. if (StrUtil.isEmpty(item.pixelMapPath)) {
  9180. continue;
  9181. }
  9182. const sourceUri = item.pixelMapPath as string;
  9183. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  9184. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  9185. }
  9186. }
  9187. }
  9188. private warmupListVisibleThumbs(start: number, end: number): void {
  9189. if (!this.isMediaLibraryListMode()) {
  9190. return;
  9191. }
  9192. if (start < 0 || end < 0 || this.videoLocalList.length <= 0) {
  9193. return;
  9194. }
  9195. const now = Date.now();
  9196. const startDelta = this.listThumbWarmupStart >= 0 ? Math.abs(start - this.listThumbWarmupStart) : 999;
  9197. const endDelta = this.listThumbWarmupEnd >= 0 ? Math.abs(end - this.listThumbWarmupEnd) : 999;
  9198. if (startDelta < 2 && endDelta < 2 && now - this.listThumbWarmupCheckAt < 90) {
  9199. return;
  9200. }
  9201. this.listThumbWarmupCheckAt = now;
  9202. this.listThumbWarmupStart = start;
  9203. this.listThumbWarmupEnd = end;
  9204. this.initCoverThumbCacheIfNeeded();
  9205. const targetSize = this.getListThumbTargetSize();
  9206. const preloadAhead = Math.max(14, Math.floor(this.pageSize * 0.4));
  9207. const begin = Math.max(0, start - 4);
  9208. const last = Math.min(this.videoLocalList.length - 1, end + preloadAhead);
  9209. for (let index = begin; index <= last; index++) {
  9210. const item = this.videoLocalList[index];
  9211. if (!item || StrUtil.isEmpty(item.pixelMapPath)) {
  9212. continue;
  9213. }
  9214. const sourceUri = item.pixelMapPath as string;
  9215. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  9216. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  9217. }
  9218. }
  9219. }
  9220. private prefetchGridWaterThumbsFromItems(items: VideoItem[], limit: number = 42): void {
  9221. if (!(this.isGridMusic || this.twoFingerType == 4) || !items || items.length === 0) {
  9222. return;
  9223. }
  9224. this.initCoverThumbCacheIfNeeded();
  9225. const isWater = this.twoFingerType == 4;
  9226. const targetSize = this.getCoverThumbTargetSize(isWater);
  9227. const maxCount = Math.min(limit, items.length);
  9228. for (let i = 0; i < maxCount; i++) {
  9229. const item = items[i];
  9230. if (!item || StrUtil.isEmpty(item.pixelMapPath)) {
  9231. continue;
  9232. }
  9233. const sourceUri = item.pixelMapPath as string;
  9234. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  9235. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  9236. }
  9237. }
  9238. }
  9239. private warmupGridWaterVisibleThumbs(start: number, end: number, isWater: boolean): void {
  9240. if (!(this.isGridMusic || this.twoFingerType == 4)) {
  9241. return;
  9242. }
  9243. if (start < 0 || end < 0 || this.videoLocalList.length <= 0) {
  9244. return;
  9245. }
  9246. const now = Date.now();
  9247. let lastStart = -1;
  9248. let lastEnd = -1;
  9249. let lastCheckAt = 0;
  9250. if (isWater) {
  9251. lastStart = this.waterThumbWarmupStart;
  9252. lastEnd = this.waterThumbWarmupEnd;
  9253. lastCheckAt = this.waterThumbWarmupCheckAt;
  9254. } else {
  9255. lastStart = this.gridThumbWarmupStart;
  9256. lastEnd = this.gridThumbWarmupEnd;
  9257. lastCheckAt = this.gridThumbWarmupCheckAt;
  9258. }
  9259. const startDelta = lastStart >= 0 ? Math.abs(start - lastStart) : 999;
  9260. const endDelta = lastEnd >= 0 ? Math.abs(end - lastEnd) : 999;
  9261. if (startDelta < 2 && endDelta < 2 && now - lastCheckAt < 70) {
  9262. return;
  9263. }
  9264. if (isWater) {
  9265. this.waterThumbWarmupCheckAt = now;
  9266. this.waterThumbWarmupStart = start;
  9267. this.waterThumbWarmupEnd = end;
  9268. } else {
  9269. this.gridThumbWarmupCheckAt = now;
  9270. this.gridThumbWarmupStart = start;
  9271. this.gridThumbWarmupEnd = end;
  9272. }
  9273. this.initCoverThumbCacheIfNeeded();
  9274. const columns = isWater ? Math.max(this.columns, 1) :
  9275. (this.twoFingerType == 1 ? 4 : this.twoFingerType == 2 ? 3 : 2);
  9276. const preloadAhead = Math.max(columns * (isWater ? 8 : 6), isWater ? 24 : 18);
  9277. const begin = Math.max(0, start - Math.max(columns * 2, 4));
  9278. const last = Math.min(this.videoLocalList.length - 1, end + preloadAhead);
  9279. const targetSize = this.getCoverThumbTargetSize(isWater);
  9280. for (let index = begin; index <= last; index++) {
  9281. const item = this.videoLocalList[index];
  9282. if (!item || StrUtil.isEmpty(item.pixelMapPath)) {
  9283. continue;
  9284. }
  9285. const sourceUri = item.pixelMapPath as string;
  9286. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  9287. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  9288. }
  9289. }
  9290. }
  9291. private getGridWaterImageSource(item: VideoItem, index: number, isWater: boolean,
  9292. coverVersion: number = 0): ResourceStr {
  9293. const fallback = item.type == CommonConstants.TYPE_IS_DIR ? $r('app.media.dir_alt') : $r('app.media.alt');
  9294. if (coverVersion < -1) {
  9295. return fallback;
  9296. }
  9297. if (StrUtil.isEmpty(item.pixelMapPath)) {
  9298. return fallback;
  9299. }
  9300. const sourceUri = item.pixelMapPath as string;
  9301. this.initCoverThumbCacheIfNeeded();
  9302. const isRemoteCover = this.coverThumbCache.isRemoteImageSource(sourceUri);
  9303. const targetSize = this.getCoverThumbTargetSize(isWater);
  9304. const cachedThumb = this.coverThumbCache.getThumbUri(sourceUri, targetSize);
  9305. if (cachedThumb) {
  9306. return cachedThumb;
  9307. }
  9308. const visibleStart = isWater ? this.waterVisibleStart : this.gridVisibleStart;
  9309. const visibleEnd = isWater ? this.waterVisibleEnd : this.gridVisibleEnd;
  9310. const columns = isWater ? Math.max(this.columns, 1) :
  9311. (this.twoFingerType == 1 ? 4 : this.twoFingerType == 2 ? 3 : 2);
  9312. const preloadBuffer = Math.max(columns * 2, 8);
  9313. const isVisibleRangeReady = visibleStart >= 0 && visibleEnd >= 0;
  9314. const isNearVisible = !isVisibleRangeReady || (index >= visibleStart - preloadBuffer && index <= visibleEnd + preloadBuffer);
  9315. if (!isRemoteCover && isNearVisible) {
  9316. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  9317. }
  9318. if (!this.isScrolling) {
  9319. return sourceUri;
  9320. }
  9321. if (isNearVisible) {
  9322. return sourceUri;
  9323. }
  9324. return fallback;
  9325. }
  9326. private flushPendingCoverThumbRefresh(): void {
  9327. if (!this.pendingCoverThumbRefresh) {
  9328. return;
  9329. }
  9330. this.pendingCoverThumbRefresh = false;
  9331. this.coverThumbVersion++;
  9332. }
  9333. private initCoverThumbCacheIfNeeded(): void {
  9334. if (this.coverThumbCacheReady) {
  9335. return;
  9336. }
  9337. this.coverThumbCache.setContext(this.context);
  9338. this.coverThumbCache.setOnThumbReady(() => {
  9339. if (this.isScrolling) {
  9340. this.pendingCoverThumbRefresh = true;
  9341. return;
  9342. }
  9343. this.coverThumbVersion++;
  9344. });
  9345. this.coverThumbCacheReady = true;
  9346. }
  9347. private getCoverThumbTargetSize(isWater: boolean): number {
  9348. if (isWater) {
  9349. if (this.columns >= 4) {
  9350. return 160;
  9351. }
  9352. if (this.columns == 3) {
  9353. return 200;
  9354. }
  9355. return 260;
  9356. }
  9357. const baseSize = Math.max(this.getGridWight(), this.getGridHeight());
  9358. if (this.twoFingerType == 1) {
  9359. return baseSize;
  9360. }
  9361. if (this.twoFingerType == 2) {
  9362. return Math.floor(baseSize * 1.1);
  9363. }
  9364. return Math.floor(baseSize * 1.15);
  9365. }
  9366. private tryTriggerLoadForWaterByOffset(currentOffsetY: number): void {
  9367. if (this.videoLocalList.length <= 0) {
  9368. return;
  9369. }
  9370. const columns = Math.max(this.columns, 1);
  9371. const viewportHeight = this.windowHeight > 0 ? this.windowHeight : 900;
  9372. const estimatedCardHeight = this.columns >= 3 ? 196 : 228;
  9373. const startRow = Math.max(0, Math.floor(Math.max(currentOffsetY, 0) / estimatedCardHeight) - 1);
  9374. const estimatedRows = Math.ceil((Math.max(currentOffsetY, 0) + viewportHeight) / estimatedCardHeight);
  9375. const startIndex = Math.min(this.videoLocalList.length - 1, startRow * columns);
  9376. const estimatedEnd = Math.min(this.videoLocalList.length - 1, estimatedRows * columns + columns);
  9377. this.waterVisibleStart = startIndex;
  9378. this.waterVisibleEnd = estimatedEnd;
  9379. this.lastVisibleEndIndex = estimatedEnd;
  9380. this.warmupGridWaterVisibleThumbs(startIndex, estimatedEnd, true);
  9381. const now = Date.now();
  9382. const pagingDelta = this.waterScrollLastPagingEnd >= 0 ? Math.abs(estimatedEnd - this.waterScrollLastPagingEnd) : 999;
  9383. if (pagingDelta >= 3 || now - this.waterScrollPagingCheckAt >= 80) {
  9384. this.waterScrollPagingCheckAt = now;
  9385. this.waterScrollLastPagingEnd = estimatedEnd;
  9386. this.tryTriggerLoadNextPageByScroll(estimatedEnd);
  9387. }
  9388. }
  9389. private tryTriggerLoadNextPageByScroll(endIndex: number): void {
  9390. if (this.modeType === 4) {
  9391. return;
  9392. }
  9393. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  9394. return;
  9395. }
  9396. if (this.isHistory || this.isFavMusic) {
  9397. return;
  9398. }
  9399. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  9400. return;
  9401. }
  9402. if (endIndex < 0 || endIndex >= this.videoLocalList.length) {
  9403. return;
  9404. }
  9405. const nextPage = this.currentPage + 1;
  9406. const next2Page = this.currentPage + 2;
  9407. const totalLoaded = this.videoLocalList.length;
  9408. const seenRatio = (endIndex + 1) / Math.max(totalLoaded, 1);
  9409. const remainCount = this.videoLocalList.length - endIndex - 1;
  9410. const preloadStartRatio = this.getDynamicPreloadStartRatio();
  9411. const appendStartRatio = this.getDynamicAppendStartRatio();
  9412. const earlyAppendReserveCount = this.getDynamicEarlyAppendReserveCount();
  9413. const emergencyDistance = Math.max(12, Math.floor(this.pageSize * 0.5));
  9414. if (seenRatio >= preloadStartRatio) {
  9415. if (!this.pageCache.has(nextPage)) {
  9416. void this.prefetchNextPage(nextPage);
  9417. }
  9418. if (this.shouldPrefetchSecondPage() && !this.pageCache.has(next2Page)) {
  9419. void this.prefetchNextPage(next2Page);
  9420. }
  9421. }
  9422. const shouldAppendEarly = this.pageCache.has(nextPage) &&
  9423. (seenRatio >= appendStartRatio || remainCount <= earlyAppendReserveCount);
  9424. const shouldGapAppend = this.pageCache.has(nextPage) &&
  9425. seenRatio >= (appendStartRatio - 0.08) &&
  9426. remainCount <= Math.max(earlyAppendReserveCount, Math.floor(this.pageSize * 0.9));
  9427. const shouldEmergencyLoad = remainCount <= emergencyDistance;
  9428. if (!shouldAppendEarly && !shouldGapAppend && !shouldEmergencyLoad) {
  9429. return;
  9430. }
  9431. if (this.lastScrollTriggerPage === this.currentPage) {
  9432. return;
  9433. }
  9434. this.lastScrollTriggerPage = this.currentPage;
  9435. Logger.info('heanup LocalMusic',
  9436. `tryTriggerLoadNextPageByScroll: end=${endIndex}, remain=${remainCount}, ratio=${seenRatio}, page=${this.currentPage}`);
  9437. this.scheduleLoadNextPage(8);
  9438. }
  9439. private scheduleLoadNextPage(delayMs: number = 0): void {
  9440. if (this.pagingScheduleTimer) {
  9441. return;
  9442. }
  9443. this.pagingScheduleTimer = setTimeout(() => {
  9444. this.pagingScheduleTimer = 0;
  9445. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  9446. return;
  9447. }
  9448. void this.loadNextPage();
  9449. }, delayMs);
  9450. }
  9451. /**
  9452. * 加载下一页
  9453. */
  9454. private async loadNextPage(): Promise<void> {
  9455. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  9456. return;
  9457. }
  9458. this.isPagingTransition = true;
  9459. this.currentPage++;
  9460. Logger.info('heanup LocalMusic', `loadNextPage: 加载第 ${this.currentPage} 页`);
  9461. try {
  9462. await this.loadPage(this.currentPage, true);
  9463. } finally {
  9464. this.isPagingTransition = false;
  9465. }
  9466. }
  9467. //编辑信息
  9468. async doEdit(item: VideoItem) {
  9469. if (!item) {
  9470. return
  9471. }
  9472. if (StrUtil.isEmpty(this.titleStr)) {
  9473. ToastUtil.showToast('标题不能为空')
  9474. return
  9475. }
  9476. //内嵌音乐标签不能开启监听
  9477. // this.deletionWatcher?.stop();
  9478. this.loadingDialogId = DialogHelper.showLoadingDialog()
  9479. if (isRemoteCloudType(item.type)) {
  9480. await this.saveRemoteSongEdit(item);
  9481. return;
  9482. }
  9483. await PermissionUtil.activatePermission(item.filePath)
  9484. let tempOutPath = ''
  9485. // 如果不是 packName 包下的文件,则直接路径用this.currentPath
  9486. if(!item.filePath.toLowerCase().includes(this.packName)){
  9487. tempOutPath = this.currentPath + '/' + item.fileName
  9488. }
  9489. console.info('onecold tempOutPath ='+tempOutPath)
  9490. //用户更改了封面,那就内嵌下封面
  9491. if(StrUtil.isNotEmpty(this.imagePathStr)){
  9492. const resultCover:boolean = await changeMusicCover(this.context,
  9493. item.filePath,this.imagePathStr,true,tempOutPath);
  9494. this.imagePathStr = ''
  9495. if(resultCover){
  9496. ToastUtil.showToast('内嵌封面成功')
  9497. }
  9498. }
  9499. const metadata:FFMpegTags = {
  9500. title: this.titleStr,
  9501. artist: this.artistStr,
  9502. album: this.ablumStr,
  9503. TYER:this.yearStr,
  9504. genre:this.genreStr,
  9505. track:this.trackStr,
  9506. album_artist:this.albumArtistStr,
  9507. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  9508. COMPOSER:this.composerStr,
  9509. lyricist:this.lyricistStr,
  9510. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  9511. comment:this.commentStr,
  9512. disc:this.discStr,
  9513. };
  9514. let newInput = item.filePath
  9515. //内嵌标签歌路径如果不是包含包名,输入newInput要赋值tempOutPath,然后tempOutPath为空
  9516. if(!item.filePath.toLowerCase().includes(this.packName)&&FileUtil.accessSync(tempOutPath)){
  9517. newInput = tempOutPath
  9518. tempOutPath = ''
  9519. }
  9520. const isWav:boolean = newInput.toLowerCase().endsWith('.wav')
  9521. ||newInput.toLowerCase().endsWith('.ape')
  9522. ||newInput.toLowerCase().endsWith('.dsf')
  9523. ||newInput.toLowerCase().endsWith('.dff');
  9524. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  9525. const result:boolean = await repairAudioMetadata(
  9526. newInput,
  9527. this.lyricConStr,
  9528. metadata,
  9529. true,
  9530. tempOutPath
  9531. );
  9532. // ToastUtil.showToast('result ='+ result)
  9533. if (result||isWav) {
  9534. if(!item.filePath.includes(this.packName)){
  9535. //内嵌成功的歌路径如果不是包含包名,则要入库
  9536. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newInput,
  9537. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  9538. this.table.insert(newItem, (id: number) => {
  9539. //加入数据库
  9540. if(this.modeType==0){
  9541. this.deleteCache(this.currentPath)
  9542. this.getSortedFiles(this.currentPath)
  9543. }
  9544. });
  9545. }
  9546. const task = new taskpool.Task(
  9547. updateInfoDb,
  9548. this.context,
  9549. item.filePath,
  9550. this.titleStr,
  9551. this.artistStr,
  9552. this.ablumStr,
  9553. this.lyricConStr,
  9554. this.yearStr,this.genreStr,
  9555. this.trackStr,this.albumArtistStr,
  9556. this.composerStr, this.lyricistStr,
  9557. this.commentStr,this.discStr
  9558. );
  9559. taskpool.execute(task, taskpool.Priority.HIGH).then((result) => {
  9560. if (result) {
  9561. console.log(" onecold 编辑信息成功,数据库已同步");
  9562. if(isWav){
  9563. ToastUtil.showToast('dsf、wav、dff或者ape格式有可能内嵌失败,但是编辑信息成功')
  9564. }else{
  9565. ToastUtil.showToast('内嵌音乐标签成功')
  9566. }
  9567. this.isShowMoreView = false
  9568. this.name = this.titleStr
  9569. this.syncEditedFields(item)
  9570. if (item.filePath == this.currentSong?.filePath) {
  9571. this.currentSong.name = this.titleStr
  9572. this.artist = this.artistStr
  9573. this.currentSong.artist = this.artistStr
  9574. this.currentSong.album = this.ablumStr
  9575. this.currentSong.year = this.yearStr
  9576. this.currentSong.genre = this.genreStr
  9577. this.currentSong.track = this.trackStr
  9578. this.currentSong.lyricContent = this.lyricConStr
  9579. this.currentSong.ALBUMARTIST = this.albumArtistStr
  9580. this.currentSong.COMPOSER = this.composerStr
  9581. this.currentSong.LYRICIST = this.lyricistStr
  9582. this.currentSong.COMMENT = this.commentStr
  9583. }
  9584. this.syncListsAfterEdit(item.filePath)
  9585. this.doUpateEditedFields(item)
  9586. //this.doUpdateData()
  9587. } else {
  9588. // ToastUtil.showToast('保存失败' + error?.toString())
  9589. console.error(" onecold 编辑信息数据库失败 ");
  9590. }
  9591. // 关闭进度条
  9592. DialogHelper.closeDialog(this.loadingDialogId)
  9593. }).catch((error: Error) => {
  9594. // 关闭进度条
  9595. DialogHelper.closeDialog(this.loadingDialogId)
  9596. console.error('onecold Subtitle sync failed:', error);
  9597. });
  9598. console.log(' onecold 元数据标签更新成功,');
  9599. } else {
  9600. // 关闭进度条
  9601. DialogHelper.closeDialog(this.loadingDialogId)
  9602. ToastUtil.showToast('内嵌音乐标签失败')
  9603. console.log('onecold 内嵌音乐标签失败');
  9604. }
  9605. this.longItemFilePath = ''
  9606. this.tempLyricContent = ''
  9607. this.isShowEdit = false
  9608. }
  9609. private normalizeEditedCoverPath(path: string): string {
  9610. if (StrUtil.isEmpty(path)) {
  9611. return '';
  9612. }
  9613. const lowerPath = path.toLowerCase();
  9614. if (lowerPath.startsWith('http://') || lowerPath.startsWith('https://')
  9615. || lowerPath.startsWith('file://') || lowerPath.startsWith('data:')) {
  9616. return path;
  9617. }
  9618. return fileUri.getUriFromPath(path);
  9619. }
  9620. private emitRemoteMetadataUpdated(item: VideoItem): void {
  9621. if (!item || StrUtil.isEmpty(item.filePath)) {
  9622. return;
  9623. }
  9624. const payload: WebDavMetadataUpdatePayload = {
  9625. filePath: item.filePath,
  9626. pixelMapPath: item.pixelMapPath,
  9627. isCustomCover: item.isCustomCover,
  9628. md5Str: item.md5Str,
  9629. name: item.name,
  9630. artist: item.artist
  9631. };
  9632. const eventUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
  9633. emitter.emit(eventUpdate, { data: [payload] });
  9634. }
  9635. private syncRemoteManagerSong(item: VideoItem): void {
  9636. if (!item || StrUtil.isEmpty(item.filePath)) {
  9637. return;
  9638. }
  9639. const remoteManager = RemoteDriveManager.getInstance();
  9640. const target = Utility.getItemByFilePath(remoteManager.webDavSongs, item.filePath);
  9641. if (!target) {
  9642. return;
  9643. }
  9644. this.mergeVideoItemFromSource(target, item);
  9645. }
  9646. private async saveRemoteSongEdit(item: VideoItem): Promise<void> {
  9647. try {
  9648. this.syncEditedFields(item);
  9649. if (StrUtil.isNotEmpty(this.imagePathStr)) {
  9650. item.pixelMapPath = this.normalizeEditedCoverPath(this.imagePathStr);
  9651. item.isCustomCover = 1;
  9652. }
  9653. this.name = this.titleStr;
  9654. if (this.currentSong && item.filePath === this.currentSong.filePath) {
  9655. this.syncEditedFields(this.currentSong);
  9656. if (StrUtil.isNotEmpty(item.pixelMapPath)) {
  9657. mergeCoverWithPriority(this.currentSong, item.pixelMapPath, item.isCustomCover ?? 0);
  9658. this.cover = this.currentSong.pixelMapPath || item.pixelMapPath;
  9659. }
  9660. this.artist = this.currentSong.artist ?? '';
  9661. this.currentSong = cloneVideoItem(this.currentSong);
  9662. AppStorage.setOrCreate('currentSong', this.currentSong);
  9663. }
  9664. this.syncListsAfterEdit(item.filePath);
  9665. this.syncRemoteManagerSong(item);
  9666. await this.persistRemoteMetadataToDb(item);
  9667. this.emitRemoteMetadataUpdated(item);
  9668. ToastUtil.showToast(StrUtil.isNotEmpty(item.pixelMapPath) ? '网盘歌曲信息已保存' : '网盘歌曲标签已保存');
  9669. } catch (error) {
  9670. Logger.error(TAG, `saveRemoteSongEdit 失败: ${(error as Error).message}`);
  9671. ToastUtil.showToast('网盘歌曲编辑失败');
  9672. } finally {
  9673. DialogHelper.closeDialog(this.loadingDialogId);
  9674. this.longItemFilePath = '';
  9675. this.tempLyricContent = '';
  9676. this.isShowEdit = false;
  9677. this.imagePathStr = '';
  9678. this.isShowMoreView = false;
  9679. }
  9680. }
  9681. // 内嵌标签更新当前内嵌的Item
  9682. async doUpateEditedFields(item: VideoItem) {
  9683. // 找到当前项在 videoLocalList 中的索引
  9684. const index = this.videoLocalList.findIndex(video => video.filePath === item.filePath);
  9685. if (index !== -1) {
  9686. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  9687. const updatedItem = await this.table.queryVideoByFilePath(item.filePath)
  9688. // 只有当查询结果不为 null 时才更新列表
  9689. if (updatedItem !== null) {
  9690. // 更新 videoLocalList 中的项(通过创建新数组触发响应式更新)
  9691. this.videoLocalList = [
  9692. ...this.videoLocalList.slice(0, index),
  9693. updatedItem,
  9694. ...this.videoLocalList.slice(index + 1)
  9695. ];
  9696. // 同步更新 LazyDataSource
  9697. this.dataSource.pushArrayData(this.videoLocalList)
  9698. } else {
  9699. ToastUtil.showToast('未找到更新的数据');
  9700. }
  9701. }
  9702. DialogHelper.closeDialog(this.loadingDialogId)
  9703. }
  9704. @Builder
  9705. editSheet(item: VideoItem) {
  9706. Scroll() {
  9707. Column() {
  9708. this.editDetail(item)
  9709. }
  9710. }
  9711. .width('100%')
  9712. .height('100%')
  9713. }
  9714. @Builder
  9715. editDetail(item: VideoItem) {
  9716. Column() {
  9717. if (item) {
  9718. Row() {
  9719. Stack() {
  9720. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  9721. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  9722. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
  9723. item.pixelMapPath)
  9724. .fillColor(this.themeColor)
  9725. .height(88)
  9726. .width(88)
  9727. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  9728. .borderRadius(12)
  9729. .clip(true)
  9730. .opacity(this.opacityItem)// 绑定透明度
  9731. .margin({ left: 25 })
  9732. }
  9733. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  9734. .onClick(async () => {
  9735. const imagePath:string | undefined = await this.goSelectImage(item);
  9736. if (imagePath) {
  9737. //用户更改过图片
  9738. this.imagePathStr = imagePath
  9739. }
  9740. })
  9741. .width('28%')
  9742. Row() {
  9743. Column() {
  9744. Text(item.name)
  9745. .fontSize(17)
  9746. .maxLines(1)
  9747. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9748. .animation({
  9749. duration: 555,
  9750. curve: 'Linear',
  9751. })
  9752. .fontColor(this.themeColor)
  9753. .margin({ left: 8 })
  9754. Row() {
  9755. Text(item.artist)
  9756. .fontSize(14)
  9757. .maxLines(1)
  9758. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9759. .padding({ top: 8 })
  9760. .fontColor(this.themeColor)
  9761. .margin({ left: 8 })
  9762. }
  9763. }
  9764. .height('100%')
  9765. .width(100)
  9766. .layoutWeight(1)
  9767. .justifyContent(FlexAlign.Center)
  9768. .alignItems(HorizontalAlign.Start)
  9769. Column() {
  9770. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9771. Row(){
  9772. SymbolGlyph($r('sys.symbol.picture'))
  9773. .fontSize(18)
  9774. .fontColor([Color.White])
  9775. Text('获取封面')
  9776. .margin({ left: 4 })
  9777. .fontSize(11)
  9778. .fontColor(Color.White)
  9779. .fontWeight(480)
  9780. .textAlign(TextAlign.Center)
  9781. }
  9782. .justifyContent(FlexAlign.Center)
  9783. }
  9784. .height(38)
  9785. .width(100)
  9786. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9787. .backgroundColor(this.themeColor)
  9788. .stateEffect(true)
  9789. .margin({ right: 35 })
  9790. .onClick(async () => {
  9791. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  9792. this.showTipsDialog();
  9793. return; // Return empty string when no API is configured
  9794. }
  9795. const imagePath:string | undefined = await this.doSearchCover(item,
  9796. this.titleStr,this.artistStr);
  9797. console.info('onecold imagePath = '+imagePath)
  9798. if (StrUtil.isNotEmpty(imagePath)) {
  9799. //用户更改过图片
  9800. this.imagePathStr = imagePath
  9801. ToastUtil.showToast('获取封面成功')
  9802. }else{
  9803. ToastUtil.showToast('获取封面失败,请重试')
  9804. }
  9805. })
  9806. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9807. Row(){
  9808. SymbolGlyph($r('sys.symbol.input_mode'))
  9809. .fontSize(18)
  9810. .fontColor([Color.White])
  9811. Text('获取歌词')
  9812. .margin({ left: 4 })
  9813. .fontSize(11)
  9814. .fontColor(Color.White)
  9815. .fontWeight(480)
  9816. .textAlign(TextAlign.Center)
  9817. }
  9818. .justifyContent(FlexAlign.Center)
  9819. }
  9820. .height(38)
  9821. .width(100)
  9822. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9823. .backgroundColor(this.themeColor)
  9824. .stateEffect(true)
  9825. .margin({ top: 9, right: 35 })
  9826. .onClick(async () => {
  9827. //判断有没有设置api
  9828. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  9829. if (StrUtil.isEmpty(apiUrl)) {
  9830. this.isLyricSetting = false
  9831. this.showTipsDialog()
  9832. return
  9833. }
  9834. let res: string | undefined = await getApiLyric(apiUrl,
  9835. this.titleStr, this.artistStr, false);
  9836. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  9837. this.lyricConStr = res;
  9838. ToastUtil.showToast('获取歌词成功')
  9839. }else{
  9840. ToastUtil.showToast('获取歌词失败,请重试')
  9841. }
  9842. })
  9843. }
  9844. .justifyContent(FlexAlign.Start)
  9845. }
  9846. .height('100%')
  9847. .justifyContent(FlexAlign.Start)
  9848. .layoutWeight(1)
  9849. }
  9850. .width('100%')
  9851. .height(98)
  9852. Row() {
  9853. Text('标题:')
  9854. .fontSize(14)
  9855. .fontColor($r('app.color.text_color'))
  9856. .margin({ left: 22 })
  9857. TextInput({ text: this.titleStr })
  9858. .height(40)
  9859. .maxLines(1)
  9860. .fontSize(14)
  9861. .layoutWeight(1)
  9862. .fontColor($r('app.color.text_color'))
  9863. .margin({ right: 15, left: 10 })
  9864. .onChange((val: string) => {
  9865. this.titleStr = val
  9866. })
  9867. Button('修复乱码',{ type: ButtonType.Capsule, stateEffect: true})
  9868. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9869. .backgroundColor(this.themeColor)
  9870. .fontSize(10)
  9871. .margin({ right: 20})
  9872. .onClick(async () => {
  9873. let hwTags = await extractHwMediaMetadata(item.filePath)
  9874. let artist = hwTags?.artist|| '';
  9875. let title = hwTags?.title|| '';
  9876. let album = hwTags?.album|| '';
  9877. console.info('onecold 乱码修正 artist='+artist);
  9878. console.info('onecold 乱码修正 title='+title);
  9879. console.info('onecold 乱码修正 album='+album);
  9880. this.titleStr = title;
  9881. this.artistStr = artist;
  9882. this.ablumStr = album;
  9883. })
  9884. }
  9885. .width('100%')
  9886. .margin({ top: 10, bottom: 10 })
  9887. .justifyContent(FlexAlign.Start)
  9888. Row() {
  9889. Text('艺术家:')
  9890. .fontSize(14)
  9891. .fontColor($r('app.color.text_color'))
  9892. .margin({ left: 22 })
  9893. TextInput({ text: this.artistStr })
  9894. .height(40)
  9895. .maxLines(1)
  9896. .fontSize(14)
  9897. .layoutWeight(1)
  9898. .fontColor($r('app.color.text_color'))
  9899. .margin({ right: 20, left: 10 })
  9900. .onChange((val: string) => {
  9901. this.artistStr = val
  9902. })
  9903. }
  9904. .width('100%')
  9905. .margin({ top: 10, bottom: 10 })
  9906. .justifyContent(FlexAlign.Start)
  9907. Row() {
  9908. Text('专辑名:')
  9909. .fontSize(14)
  9910. .fontColor($r('app.color.text_color'))
  9911. .margin({ left: 22 })
  9912. TextInput({ text: this.ablumStr})
  9913. .height(40)
  9914. .maxLines(1)
  9915. .fontSize(14)
  9916. .layoutWeight(1)
  9917. .fontColor($r('app.color.text_color'))
  9918. .margin({ right: 20, left: 10 })
  9919. .onChange((val: string) => {
  9920. this.ablumStr = val
  9921. })
  9922. }
  9923. .width('100%')
  9924. .margin({ top: 10, bottom: 10 })
  9925. .justifyContent(FlexAlign.Start)
  9926. Row() {
  9927. Column(){
  9928. Column(){
  9929. Text('歌词:')
  9930. .fontSize(14)
  9931. .fontColor($r('app.color.text_color'))
  9932. .margin({ top:9,left: 22 })
  9933. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9934. SymbolGlyph($r('sys.symbol.trash_fill'))
  9935. .fontSize(25)
  9936. .alignSelf(ItemAlign.Center)
  9937. .margin({ left: 22,top:25})
  9938. }
  9939. .backgroundColor(Color.Transparent)
  9940. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  9941. Visibility.None:Visibility.Visible)
  9942. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9943. .onClick(()=>{
  9944. this.lyricConStr = ''
  9945. this.lyricContent = ''
  9946. this.tempLyricContent = ''
  9947. })
  9948. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9949. SymbolGlyph($r('sys.symbol.plus'))
  9950. .fontSize(25)
  9951. .alignSelf(ItemAlign.Center)
  9952. .margin({ left: 22,top:25})
  9953. }
  9954. .backgroundColor(Color.Transparent)
  9955. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9956. .onClick( ()=>{
  9957. this.callFilePickerSelectFileForLyric()
  9958. })
  9959. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9960. SymbolGlyph($r('sys.symbol.traditional_square'))
  9961. .fontSize(25)
  9962. .alignSelf(ItemAlign.Center)
  9963. .margin({ left: 22,top:25})
  9964. }
  9965. .backgroundColor(Color.Transparent)
  9966. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  9967. Visibility.None:Visibility.Visible)
  9968. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9969. .onClick( ()=>{
  9970. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  9971. this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
  9972. })
  9973. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9974. Image($r('app.media.jianti'))
  9975. .height(25)
  9976. .fillColor($r('app.color.text_color'))
  9977. .alignSelf(ItemAlign.Center)
  9978. .margin({ left: 22,top:25})
  9979. }
  9980. .backgroundColor(Color.Transparent)
  9981. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  9982. Visibility.None:Visibility.Visible)
  9983. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9984. .onClick( ()=>{
  9985. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  9986. this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
  9987. })
  9988. }
  9989. .layoutWeight(1)
  9990. }
  9991. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  9992. this.tempLyricContent })
  9993. .type(TextAreaType.NORMAL)
  9994. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
  9995. .fontSize(14)
  9996. .layoutWeight(1)
  9997. .fontColor($r('app.color.text_color'))
  9998. .margin({ right: 20, left: 10 })
  9999. .onChange((val: string) => {
  10000. this.lyricConStr = val
  10001. })
  10002. }
  10003. .width('100%')
  10004. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
  10005. .margin({ top: 10, bottom: 10 })
  10006. .justifyContent(FlexAlign.Start)
  10007. Row() {
  10008. Text('年份:')
  10009. .fontSize(14)
  10010. .fontColor($r('app.color.text_color'))
  10011. .margin({ left: 22 })
  10012. TextInput({ text: item.year })
  10013. .height(40)
  10014. .maxLines(1)
  10015. .fontSize(14)
  10016. .type(InputType.Number)
  10017. .layoutWeight(1)
  10018. .fontColor($r('app.color.text_color'))
  10019. .margin({ right: 20, left: 10 })
  10020. .onChange((val: string) => {
  10021. this.yearStr = val
  10022. })
  10023. }
  10024. .width('100%')
  10025. .margin({ top: 10, bottom: 10 })
  10026. .justifyContent(FlexAlign.Start)
  10027. Row() {
  10028. Text('音轨号:')
  10029. .fontSize(14)
  10030. .fontColor($r('app.color.text_color'))
  10031. .margin({ left: 22 })
  10032. TextInput({ text:item.track=='未知'?'': item.track })
  10033. .height(40)
  10034. .maxLines(1)
  10035. .fontSize(14)
  10036. .type(InputType.Number)
  10037. .layoutWeight(1)
  10038. .fontColor($r('app.color.text_color'))
  10039. .margin({ right: 20, left: 10 })
  10040. .onChange((val: string) => {
  10041. this.trackStr = val
  10042. })
  10043. }
  10044. .width('100%')
  10045. .margin({ top: 10, bottom: 10 })
  10046. .justifyContent(FlexAlign.Start)
  10047. Row() {
  10048. Text('碟号:')
  10049. .fontSize(14)
  10050. .fontColor($r('app.color.text_color'))
  10051. .margin({ left: 22 })
  10052. TextInput({ text:item.disc })
  10053. .height(40)
  10054. .maxLines(1)
  10055. .fontSize(14)
  10056. .type(InputType.Number)
  10057. .layoutWeight(1)
  10058. .fontColor($r('app.color.text_color'))
  10059. .margin({ right: 20, left: 10 })
  10060. .onChange((val: string) => {
  10061. this.discStr = val
  10062. })
  10063. }
  10064. .width('100%')
  10065. .margin({ top: 10, bottom: 10 })
  10066. .justifyContent(FlexAlign.Start)
  10067. Row() {
  10068. Text('风格:')
  10069. .fontSize(14)
  10070. .fontColor($r('app.color.text_color'))
  10071. .margin({ left: 22 })
  10072. TextInput({ text: item.genre })
  10073. .height(40)
  10074. .maxLines(1)
  10075. .fontSize(14)
  10076. .layoutWeight(1)
  10077. .fontColor($r('app.color.text_color'))
  10078. .margin({ right: 20, left: 10 })
  10079. .onChange((val: string) => {
  10080. this.genreStr = val
  10081. })
  10082. }
  10083. .width('100%')
  10084. .margin({ top: 10, bottom: 10 })
  10085. .justifyContent(FlexAlign.Start)
  10086. Row() {
  10087. Text('专辑艺术家:')
  10088. .fontSize(14)
  10089. .fontColor($r('app.color.text_color'))
  10090. .margin({ left: 22 })
  10091. TextInput({ text: item.ALBUMARTIST })
  10092. .height(40)
  10093. .maxLines(1)
  10094. .fontSize(14)
  10095. .layoutWeight(1)
  10096. .fontColor($r('app.color.text_color'))
  10097. .margin({ right: 20, left: 10 })
  10098. .onChange((val: string) => {
  10099. this.albumArtistStr = val
  10100. })
  10101. }
  10102. .width('100%')
  10103. .margin({ top: 10, bottom: 10 })
  10104. .justifyContent(FlexAlign.Start)
  10105. Row() {
  10106. Text('作曲:')
  10107. .fontSize(14)
  10108. .fontColor($r('app.color.text_color'))
  10109. .margin({ left: 22 })
  10110. TextInput({ text: item.COMPOSER })
  10111. .height(40)
  10112. .maxLines(1)
  10113. .fontSize(14)
  10114. .layoutWeight(1)
  10115. .fontColor($r('app.color.text_color'))
  10116. .margin({ right: 20, left: 10 })
  10117. .onChange((val: string) => {
  10118. this.composerStr = val
  10119. })
  10120. }
  10121. .width('100%')
  10122. .margin({ top: 10, bottom: 10 })
  10123. .justifyContent(FlexAlign.Start)
  10124. Row() {
  10125. Text('作词:')
  10126. .fontSize(14)
  10127. .fontColor($r('app.color.text_color'))
  10128. .margin({ left: 22 })
  10129. TextInput({ text: item.LYRICIST })
  10130. .height(40)
  10131. .maxLines(1)
  10132. .fontSize(14)
  10133. .layoutWeight(1)
  10134. .fontColor($r('app.color.text_color'))
  10135. .margin({ right: 20, left: 10 })
  10136. .onChange((val: string) => {
  10137. this.lyricistStr = val
  10138. })
  10139. }
  10140. .width('100%')
  10141. .margin({ top: 10, bottom: 10 })
  10142. .justifyContent(FlexAlign.Start)
  10143. Row() {
  10144. Text('注释:')
  10145. .fontSize(14)
  10146. .fontColor($r('app.color.text_color'))
  10147. .margin({ left: 22 })
  10148. TextInput({ text: item.COMMENT })
  10149. .height(40)
  10150. .maxLines(1)
  10151. .fontSize(14)
  10152. .layoutWeight(1)
  10153. .fontColor($r('app.color.text_color'))
  10154. .margin({ right: 20, left: 10 })
  10155. .onChange((val: string) => {
  10156. this.commentStr = val
  10157. })
  10158. }
  10159. .width('100%')
  10160. .margin({ top: 10, bottom: 10 })
  10161. .justifyContent(FlexAlign.Start)
  10162. Row() {
  10163. Button('保存')
  10164. .fontColor(Color.White)
  10165. .layoutWeight(1)
  10166. .height(50)
  10167. .width(100)
  10168. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  10169. .backgroundColor(this.themeColor)
  10170. .stateEffect(true)
  10171. .margin({ right: 20, bottom: 20 })
  10172. .onClick(async () => {
  10173. this.doEdit(item)
  10174. })
  10175. Button('取消')
  10176. .fontColor(Color.White)
  10177. .layoutWeight(1)
  10178. .height(50)
  10179. .width(100)
  10180. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  10181. .backgroundColor(this.themeColor)
  10182. .stateEffect(true)
  10183. .margin({ left: 20, bottom: 20 })
  10184. .onClick(async () => {
  10185. if(this.isGridMusic){
  10186. this.longItemFilePath =''
  10187. }else{
  10188. this.isShowEdit = false
  10189. }
  10190. this.setEditStrEmpty()
  10191. if(this.isShowPlay){
  10192. this.isShowEdit = false
  10193. }
  10194. })
  10195. }
  10196. .margin({
  10197. left: 38,
  10198. right: 38,
  10199. top: 10,
  10200. bottom: 10
  10201. })
  10202. .width(250)
  10203. .height(60)
  10204. }
  10205. }
  10206. .margin({ bottom: 20 })
  10207. }
  10208. setEditStrEmpty(){
  10209. this.imagePathStr = ''
  10210. this.lyricConStr = ''
  10211. this.artistStr = ''
  10212. this.titleStr = ''
  10213. this.ablumStr = ''
  10214. this.genreStr = ''
  10215. this.yearStr = ''
  10216. this.trackStr = ''
  10217. this.albumArtistStr = ''
  10218. this.composerStr = ''
  10219. this.lyricistStr = ''
  10220. this.commentStr = ''
  10221. this.discStr = ''
  10222. }
  10223. initEditFields(item?: VideoItem) {
  10224. if (!item) {
  10225. this.setEditStrEmpty()
  10226. return
  10227. }
  10228. this.imagePathStr = ''
  10229. this.titleStr = item.name ?? ''
  10230. this.artistStr = item.artist ?? ''
  10231. this.ablumStr = item.album ?? ''
  10232. this.genreStr = item.genre ?? ''
  10233. this.yearStr = item.year ?? ''
  10234. this.trackStr = item.track ?? ''
  10235. this.albumArtistStr = item.ALBUMARTIST ?? ''
  10236. this.composerStr = item.COMPOSER ?? ''
  10237. this.lyricistStr = item.LYRICIST ?? ''
  10238. this.commentStr = item.COMMENT ?? ''
  10239. this.discStr = item.disc ?? ''
  10240. this.lyricConStr = item.lyricContent ?? ''
  10241. }
  10242. private syncEditedFields(target?: VideoItem) {
  10243. if (!target) {
  10244. return
  10245. }
  10246. target.name = this.titleStr
  10247. target.artist = this.artistStr
  10248. target.album = this.ablumStr
  10249. target.lyricContent = this.lyricConStr
  10250. target.year = this.yearStr
  10251. target.genre = this.genreStr
  10252. target.track = this.trackStr
  10253. target.ALBUMARTIST = this.albumArtistStr
  10254. target.COMPOSER = this.composerStr
  10255. target.LYRICIST = this.lyricistStr
  10256. target.COMMENT = this.commentStr
  10257. target.disc = this.discStr
  10258. }
  10259. private replaceItemInList(list: Array<VideoItem> | undefined, filePath: string,
  10260. apply?: (next: Array<VideoItem>) => void) {
  10261. if (!list || ArrayUtil.isEmpty(list)) {
  10262. return
  10263. }
  10264. const index = list.findIndex((video: VideoItem) => video.filePath === filePath)
  10265. if (index < 0) {
  10266. return
  10267. }
  10268. const nextList = [...list]
  10269. this.syncEditedFields(nextList[index])
  10270. apply?.(nextList)
  10271. }
  10272. private syncListsAfterEdit(filePath: string) {
  10273. this.replaceItemInList(this.videoLocalList, filePath, (next: Array<VideoItem>) => {
  10274. this.videoLocalList = next
  10275. this.dataSource.pushArrayData(next)
  10276. })
  10277. this.replaceItemInList(this.songList, filePath, (next: Array<VideoItem>) => {
  10278. this.songList = next
  10279. this.sonDataSource.pushArrayData(next)
  10280. })
  10281. this.replaceItemInList(this.favList, filePath, (next: Array<VideoItem>) => {
  10282. this.favList = next
  10283. })
  10284. this.replaceItemInList(this.historyList, filePath, (next: Array<VideoItem>) => {
  10285. this.historyList = next
  10286. })
  10287. this.replaceItemInList(this.currentSongList, filePath, (next: Array<VideoItem>) => {
  10288. this.currentSongList = next
  10289. })
  10290. this.replaceItemInList(this.mediaKuList, filePath, (next: Array<VideoItem>) => {
  10291. this.mediaKuList = next
  10292. })
  10293. this.replaceItemInList(this.filteredList, filePath, (next: Array<VideoItem>) => {
  10294. this.filteredList = next
  10295. })
  10296. this.replaceItemInList(this.artistList, filePath, (next: Array<VideoItem>) => {
  10297. this.artistList = next
  10298. })
  10299. this.replaceItemInList(this.albumList, filePath, (next: Array<VideoItem>) => {
  10300. this.albumList = next
  10301. })
  10302. this.listRefreshKey++
  10303. }
  10304. private refreshLazyListViews(mainListUpdated: boolean, playlistUpdated: boolean): void {
  10305. if (!mainListUpdated && !playlistUpdated) {
  10306. return;
  10307. }
  10308. this.listRefreshKey++;
  10309. if (mainListUpdated) {
  10310. this.dataSource.notifyDataReload();
  10311. }
  10312. if (playlistUpdated) {
  10313. this.sonDataSource.notifyDataReload();
  10314. }
  10315. }
  10316. @Builder
  10317. detailSheet(item:VideoItem) {
  10318. Scroll() {
  10319. Column() {
  10320. this.songDetail(item)
  10321. }
  10322. }
  10323. .width('100%')
  10324. .height('100%')
  10325. }
  10326. @Builder
  10327. songDetail(currentItem:VideoItem) {
  10328. Column() {
  10329. if (currentItem) {
  10330. Row() {
  10331. Stack() {
  10332. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.alt') :
  10333. currentItem.pixelMapPath)
  10334. .fillColor(this.themeColor)
  10335. .height(80)
  10336. .width(80)
  10337. .borderRadius(10)
  10338. .opacity(this.opacityItem)// 绑定透明度
  10339. .margin({ left: 22 })
  10340. }
  10341. Column() {
  10342. Column() {
  10343. Text(currentItem.name)
  10344. .fontSize(16)
  10345. .maxLines(1)
  10346. .animation({
  10347. duration: 555,
  10348. curve: 'Linear',
  10349. })
  10350. .fontColor($r('app.color.text_color'))
  10351. .margin({ left: 15 })
  10352. }
  10353. .height('100%')
  10354. .width('100%')
  10355. .justifyContent(FlexAlign.Center)
  10356. .alignItems(HorizontalAlign.Start)
  10357. }
  10358. .height('100%')
  10359. }
  10360. .width('100%')
  10361. .height(90)
  10362. .justifyContent(FlexAlign.SpaceBetween)
  10363. Row() {
  10364. Text('艺术家:')
  10365. .fontSize(14)
  10366. .fontColor($r('app.color.text_color'))
  10367. .margin({ left: 22 })
  10368. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  10369. .fontSize(14)
  10370. .fontColor($r('app.color.text_color'))
  10371. .margin({ left: 10 })
  10372. .layoutWeight(1)
  10373. }
  10374. .width('100%')
  10375. .margin({ top: 10, bottom: 10 })
  10376. .justifyContent(FlexAlign.Start)
  10377. Row() {
  10378. Text('专辑名:')
  10379. .fontSize(14)
  10380. .fontColor($r('app.color.text_color'))
  10381. .margin({ left: 22 })
  10382. Text(currentItem?.album ?currentItem.album : '未知专辑')
  10383. .fontSize(14)
  10384. .margin({ left: 10 })
  10385. .fontColor($r('app.color.text_color'))
  10386. .layoutWeight(1)
  10387. }
  10388. .width('100%')
  10389. .margin({ top: 10, bottom: 10 })
  10390. .justifyContent(FlexAlign.Start)
  10391. Row() {
  10392. Text('时长:')
  10393. .fontSize(14)
  10394. .fontColor($r('app.color.text_color'))
  10395. .margin({ left: 22 })
  10396. Text(StrUtil.isEmpty(currentItem.duration)?
  10397. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  10398. .fontSize(14)
  10399. .margin({ left: 10 })
  10400. .fontColor($r('app.color.text_color'))
  10401. .layoutWeight(1)
  10402. }
  10403. .width('100%')
  10404. .margin({ top: 10, bottom: 10 })
  10405. .justifyContent(FlexAlign.Start)
  10406. Row() {
  10407. Text('采样率:')
  10408. .fontSize(14)
  10409. .fontColor($r('app.color.text_color'))
  10410. .margin({ left: 22 })
  10411. Text(Utility.convertToKHz(currentItem.sampleRate))
  10412. .fontSize(14)
  10413. .margin({ left: 10 })
  10414. .fontColor($r('app.color.text_color'))
  10415. .layoutWeight(1)
  10416. }
  10417. .width('100%')
  10418. .margin({ top: 10, bottom: 10 })
  10419. .justifyContent(FlexAlign.Start)
  10420. Row() {
  10421. Text('比特率:')
  10422. .fontSize(14)
  10423. .fontColor($r('app.color.text_color'))
  10424. .margin({ left: 22 })
  10425. Text(currentItem.bit_rate)
  10426. .fontSize(14)
  10427. .margin({ left: 10 })
  10428. .fontColor($r('app.color.text_color'))
  10429. .layoutWeight(1)
  10430. }
  10431. .width('100%')
  10432. .margin({ top: 10, bottom: 10 })
  10433. .justifyContent(FlexAlign.Start)
  10434. Row() {
  10435. Text('位深:')
  10436. .fontSize(14)
  10437. .fontColor($r('app.color.text_color'))
  10438. .margin({ left: 22 })
  10439. Text(`${currentItem.bits_per_raw_sample} bits`)
  10440. .fontSize(14)
  10441. .margin({ left: 10 })
  10442. .fontColor($r('app.color.text_color'))
  10443. .layoutWeight(1)
  10444. }
  10445. .width('100%')
  10446. .margin({ top: 10, bottom: 10 })
  10447. .justifyContent(FlexAlign.Start)
  10448. Row() {
  10449. Text('声道:')
  10450. .fontSize(14)
  10451. .fontColor($r('app.color.text_color'))
  10452. .margin({ left: 22 })
  10453. Text(`${currentItem.channels}`)
  10454. .fontSize(14)
  10455. .margin({ left: 10 })
  10456. .fontColor($r('app.color.text_color'))
  10457. .layoutWeight(1)
  10458. }
  10459. .width('100%')
  10460. .margin({ top: 10, bottom: 10 })
  10461. .justifyContent(FlexAlign.Start)
  10462. Row() {
  10463. Text('声道布局:')
  10464. .fontSize(14)
  10465. .fontColor($r('app.color.text_color'))
  10466. .margin({ left: 22 })
  10467. Text(`${currentItem.channel_layout}`)
  10468. .fontSize(14)
  10469. .margin({ left: 10 })
  10470. .fontColor($r('app.color.text_color'))
  10471. .layoutWeight(1)
  10472. }
  10473. .width('100%')
  10474. .margin({ top: 10, bottom: 10 })
  10475. .justifyContent(FlexAlign.Start)
  10476. Row() {
  10477. Text('起始播放点:')
  10478. .fontSize(14)
  10479. .fontColor($r('app.color.text_color'))
  10480. .margin({ left: 22 })
  10481. Text(`${currentItem.start_time}`)
  10482. .fontSize(14)
  10483. .margin({ left: 10 })
  10484. .fontColor($r('app.color.text_color'))
  10485. .layoutWeight(1)
  10486. }
  10487. .width('100%')
  10488. .margin({ top: 10, bottom: 10 })
  10489. .justifyContent(FlexAlign.Start)
  10490. Row() {
  10491. Text('风格:')
  10492. .fontSize(14)
  10493. .fontColor($r('app.color.text_color'))
  10494. .margin({ left: 22 })
  10495. Text(currentItem.genre)
  10496. .fontSize(14)
  10497. .margin({ left: 10 })
  10498. .fontColor($r('app.color.text_color'))
  10499. .layoutWeight(1)
  10500. }
  10501. .width('100%')
  10502. .margin({ top: 10, bottom: 10 })
  10503. .justifyContent(FlexAlign.Start)
  10504. Row() {
  10505. Text('发行时间:')
  10506. .fontSize(14)
  10507. .fontColor($r('app.color.text_color'))
  10508. .margin({ left: 22 })
  10509. Text(currentItem.year)
  10510. .fontSize(14)
  10511. .margin({ left: 10 })
  10512. .fontColor($r('app.color.text_color'))
  10513. .layoutWeight(1)
  10514. }
  10515. .width('100%')
  10516. .margin({ top: 10, bottom: 10 })
  10517. .justifyContent(FlexAlign.Start)
  10518. Row() {
  10519. Text('质量评分:')
  10520. .fontSize(14)
  10521. .fontColor($r('app.color.text_color'))
  10522. .margin({ left: 22 })
  10523. Text(currentItem.probe_score+"")
  10524. .fontSize(14)
  10525. .margin({ left: 10 })
  10526. .fontColor($r('app.color.text_color'))
  10527. .layoutWeight(1)
  10528. }
  10529. .width('100%')
  10530. .margin({ top: 10, bottom: 10 })
  10531. .justifyContent(FlexAlign.Start)
  10532. Row() {
  10533. Text('音轨号:')
  10534. .fontSize(14)
  10535. .fontColor($r('app.color.text_color'))
  10536. .margin({ left: 22 })
  10537. Text(currentItem.track)
  10538. .fontSize(14)
  10539. .margin({ left: 10 })
  10540. .fontColor($r('app.color.text_color'))
  10541. .layoutWeight(1)
  10542. }
  10543. .width('100%')
  10544. .margin({ top: 10, bottom: 10 })
  10545. .justifyContent(FlexAlign.Start)
  10546. Row() {
  10547. Text('碟号:')
  10548. .fontSize(14)
  10549. .fontColor($r('app.color.text_color'))
  10550. .margin({ left: 22 })
  10551. Text(currentItem.disc)
  10552. .fontSize(14)
  10553. .margin({ left: 10 })
  10554. .fontColor($r('app.color.text_color'))
  10555. .layoutWeight(1)
  10556. }
  10557. .width('100%')
  10558. .margin({ top: 10, bottom: 10 })
  10559. .justifyContent(FlexAlign.Start)
  10560. Row() {
  10561. Text('专辑艺术家:')
  10562. .fontSize(14)
  10563. .fontColor($r('app.color.text_color'))
  10564. .margin({ left: 22 })
  10565. Text(currentItem.ALBUMARTIST)
  10566. .fontSize(14)
  10567. .margin({ left: 10 })
  10568. .fontColor($r('app.color.text_color'))
  10569. .layoutWeight(1)
  10570. }
  10571. .width('100%')
  10572. .margin({ top: 10, bottom: 10 })
  10573. .justifyContent(FlexAlign.Start)
  10574. Row() {
  10575. Text('作曲家:')
  10576. .fontSize(14)
  10577. .fontColor($r('app.color.text_color'))
  10578. .margin({ left: 22 })
  10579. Text(currentItem.COMPOSER)
  10580. .fontSize(14)
  10581. .margin({ left: 10 })
  10582. .fontColor($r('app.color.text_color'))
  10583. .layoutWeight(1)
  10584. }
  10585. .width('100%')
  10586. .margin({ top: 10, bottom: 10 })
  10587. .justifyContent(FlexAlign.Start)
  10588. Row() {
  10589. Text('作词家:')
  10590. .fontSize(14)
  10591. .fontColor($r('app.color.text_color'))
  10592. .margin({ left: 22 })
  10593. Text(currentItem.LYRICIST)
  10594. .fontSize(14)
  10595. .margin({ left: 10 })
  10596. .fontColor($r('app.color.text_color'))
  10597. .layoutWeight(1)
  10598. }
  10599. .width('100%')
  10600. .margin({ top: 10, bottom: 10 })
  10601. .justifyContent(FlexAlign.Start)
  10602. Row() {
  10603. Text('注释:')
  10604. .fontSize(14)
  10605. .fontColor($r('app.color.text_color'))
  10606. .margin({ left: 22 })
  10607. Text(currentItem.COMMENT)
  10608. .fontSize(14)
  10609. .margin({ left: 10 })
  10610. .fontColor($r('app.color.text_color'))
  10611. .layoutWeight(1)
  10612. }
  10613. .width('100%')
  10614. .margin({ top: 10, bottom: 10 })
  10615. .justifyContent(FlexAlign.Start)
  10616. Row() {
  10617. Text('格式:')
  10618. .fontSize(14)
  10619. .fontColor($r('app.color.text_color'))
  10620. .margin({ left: 22 })
  10621. Text(Utility.formatMimeType(currentItem.mimeType))
  10622. .fontSize(14)
  10623. .margin({ left: 10 })
  10624. .fontColor($r('app.color.text_color'))
  10625. .layoutWeight(1)
  10626. }
  10627. .width('100%')
  10628. .margin({ top: 10, bottom: 10 })
  10629. .justifyContent(FlexAlign.Start)
  10630. Row() {
  10631. Text('播放次数:')
  10632. .fontSize(14)
  10633. .fontColor($r('app.color.text_color'))
  10634. .margin({ left: 22 })
  10635. Text(currentItem.playCount?.toString())
  10636. .fontSize(14)
  10637. .margin({ left: 10 })
  10638. .fontColor($r('app.color.text_color'))
  10639. .layoutWeight(1)
  10640. }
  10641. .width('100%')
  10642. .margin({ top: 10, bottom: 10 })
  10643. .justifyContent(FlexAlign.Start)
  10644. Row() {
  10645. Text('流数量:')
  10646. .fontSize(14)
  10647. .fontColor($r('app.color.text_color'))
  10648. .margin({ left: 22 })
  10649. Text(currentItem.nb_streams?.toString())
  10650. .fontSize(14)
  10651. .margin({ left: 10 })
  10652. .fontColor($r('app.color.text_color'))
  10653. .layoutWeight(1)
  10654. }
  10655. .width('100%')
  10656. .margin({ top: 10, bottom: 10 })
  10657. .justifyContent(FlexAlign.Start)
  10658. Row() {
  10659. Text('文件大小:')
  10660. .fontSize(14)
  10661. .fontColor($r('app.color.text_color'))
  10662. .margin({ left: 22 })
  10663. Text(currentItem.size)
  10664. .fontSize(14)
  10665. .margin({ left: 10 })
  10666. .fontColor($r('app.color.text_color'))
  10667. .layoutWeight(1)
  10668. }
  10669. .width('100%')
  10670. .margin({ top: 10, bottom: 10 })
  10671. .justifyContent(FlexAlign.Start)
  10672. Row() {
  10673. Text('文件名:')
  10674. .fontSize(14)
  10675. .fontColor($r('app.color.text_color'))
  10676. .margin({ left: 22 })
  10677. Text(currentItem.fileName)
  10678. .fontSize(14)
  10679. .margin({ left: 10 })
  10680. .fontColor($r('app.color.text_color'))
  10681. .layoutWeight(1)
  10682. }
  10683. .width('100%')
  10684. .margin({ top: 10, bottom: 10 })
  10685. .justifyContent(FlexAlign.Start)
  10686. Row() {
  10687. Text('修改时间:')
  10688. .fontSize(14)
  10689. .fontColor($r('app.color.text_color'))
  10690. .margin({ left: 22 })
  10691. Text(currentItem.cTime)
  10692. .fontSize(14)
  10693. .margin({ left: 10 })
  10694. .fontColor($r('app.color.text_color'))
  10695. .layoutWeight(1)
  10696. }
  10697. .width('100%')
  10698. .margin({ top: 10, bottom: 10 })
  10699. .justifyContent(FlexAlign.Start)
  10700. Row() {
  10701. Text('存放目录:')
  10702. .fontSize(14)
  10703. .fontColor($r('app.color.text_color'))
  10704. .margin({ left: 22 })
  10705. Text(currentItem.filePath)
  10706. .fontSize(12)
  10707. .margin({ left: 10 })
  10708. .fontColor($r('app.color.text_color'))
  10709. .layoutWeight(1)
  10710. }
  10711. .margin({ top: 10, bottom: 10 })
  10712. .width('100%')
  10713. .justifyContent(FlexAlign.Start)
  10714. Row() {
  10715. Text('内嵌歌词:')
  10716. .fontSize(14)
  10717. .fontColor($r('app.color.text_color'))
  10718. .margin({ left: 22 })
  10719. Text(currentItem.lyricContent)
  10720. .fontSize(12)
  10721. .copyOption(CopyOptions.InApp)
  10722. .margin({ left: 10 })
  10723. .fontColor($r('app.color.text_color'))
  10724. .layoutWeight(1)
  10725. }
  10726. .margin({ top: 10, bottom: 10 })
  10727. .width('100%')
  10728. .justifyContent(FlexAlign.Start)
  10729. }
  10730. }
  10731. .margin({ bottom: 20 })
  10732. }
  10733. //定时关闭布局
  10734. @Builder
  10735. TimeCloseSheet() {
  10736. Scroll() {
  10737. Column() {
  10738. this.TimeClose()
  10739. }
  10740. }
  10741. .width('100%')
  10742. .height('100%')
  10743. }
  10744. //倒计时关闭音乐,退出App功能实现。
  10745. @State selectedMinutes: number = 0 // 0表示未开启
  10746. @State remainingSeconds: number = 0
  10747. // 预设时间选项
  10748. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  10749. private formatTime(seconds: number): string {
  10750. const mins = Math.floor(seconds / 60)
  10751. const secs = seconds % 60
  10752. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  10753. }
  10754. // 开始倒计时
  10755. private handleTimeSelect(minutes: number) {
  10756. if (minutes === this.selectedMinutes) {
  10757. this.stopCountdown();
  10758. this.selectedMinutes = 0;
  10759. return;
  10760. }
  10761. this.selectedMinutes = minutes;
  10762. this.remainingSeconds = minutes * 60;
  10763. this.startCountdown(); // 新增调用
  10764. }
  10765. @Builder
  10766. TimeClose() {
  10767. Column() {
  10768. // 倒计时显示区域
  10769. Text(this.selectedMinutes > 0 ?
  10770. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  10771. "定时关闭未开启")
  10772. .fontSize(17)
  10773. .fontColor($r('app.color.text_color'))
  10774. .margin({ top: 2, bottom: 8 });
  10775. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  10776. ForEach(this.presetTimes, (minutes: number, index: number) => {
  10777. // 单行时间选项容器
  10778. Row() {
  10779. // 文字描述区域
  10780. Text(this.getDisplayText(minutes))
  10781. .fontSize(15)
  10782. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  10783. $r('app.color.text_color'))// 选中态颜色变化
  10784. .textAlign(TextAlign.Start)
  10785. .layoutWeight(1); // 占据剩余空间
  10786. // 复选框样式的选择器
  10787. Row() {
  10788. if (minutes === this.selectedMinutes) {
  10789. // 选中状态 - 带勾号的圆形复选框
  10790. Row() {
  10791. // 使用系统内置的勾号图标
  10792. Image($r('sys.media.ohos_ic_public_ok'))
  10793. .width(14)
  10794. .height(14)
  10795. .fillColor(Color.White)
  10796. }
  10797. .width(24)
  10798. .height(24)
  10799. .borderRadius(12)
  10800. .backgroundColor(this.themeColor)
  10801. .justifyContent(FlexAlign.Center)
  10802. .alignItems(VerticalAlign.Center)
  10803. } else {
  10804. // 未选中状态的圆形边框
  10805. Row()
  10806. .width(24)
  10807. .height(24)
  10808. .borderRadius(12)
  10809. .border({
  10810. width: 2,
  10811. color: $r('app.color.text_color'),
  10812. style: BorderStyle.Solid
  10813. })
  10814. .backgroundColor(Color.Transparent)
  10815. }
  10816. }
  10817. .width(24)
  10818. .height(24)
  10819. .margin({ left: 20 })
  10820. .justifyContent(FlexAlign.Center)
  10821. .alignItems(VerticalAlign.Center)
  10822. }
  10823. .width('100%')
  10824. .padding({
  10825. top: 18,
  10826. bottom: 18,
  10827. left: 18,
  10828. right: 18
  10829. })
  10830. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  10831. $r('app.color.bottom_control_background')) // 选中背景高亮
  10832. .borderRadius(12)
  10833. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10834. .margin({ bottom: 18 })
  10835. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  10836. });
  10837. }
  10838. .width('100%')
  10839. .padding(16)
  10840. }
  10841. }
  10842. // 获取显示文本
  10843. private getDisplayText(minutes: number): string {
  10844. if (minutes === -1) {
  10845. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  10846. }
  10847. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  10848. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  10849. }
  10850. // 处理选择事件
  10851. private handleSelect(minutes: number): void {
  10852. if (minutes === -1) { // 自定义
  10853. // 弹出自定义时间对话框
  10854. DialogHelper.showTextInputDialog({
  10855. title: '自定义时间',
  10856. maskColor: Color.Transparent,
  10857. inputType: InputType.Number,
  10858. text: '',
  10859. onChange: (text) => {
  10860. console.error("onChange: " + text);
  10861. },
  10862. onAction: (action, dialogId, content) => {
  10863. if (action == DialogAction.TWO) {
  10864. const customMinutes = Number(content);
  10865. if (customMinutes > 0) {
  10866. this.handleTimeSelect(customMinutes); // 设置自定义时间
  10867. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  10868. }
  10869. }
  10870. }
  10871. });
  10872. } else {
  10873. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  10874. }
  10875. }
  10876. // 添加定时器引用
  10877. private timerId: number = -1;
  10878. // 启动/重置倒计时
  10879. private startCountdown() {
  10880. // 清除旧定时器
  10881. if (this.timerId !== -1) {
  10882. clearInterval(this.timerId);
  10883. }
  10884. // 创建新定时器
  10885. if (this.selectedMinutes > 0) {
  10886. this.timerId = setInterval(() => {
  10887. if (this.remainingSeconds === 15) {
  10888. this.showConfirmationDialog();
  10889. }
  10890. if (this.remainingSeconds > 0) {
  10891. this.remainingSeconds -= 1;
  10892. } else {
  10893. this.stopCountdown();
  10894. this.handleTimeout();
  10895. }
  10896. }, 1000);
  10897. }
  10898. }
  10899. // 15倒计时后再次提示显示确认是否关闭App对话框
  10900. private showConfirmationDialog() {
  10901. DialogHelper.showAlertDialog({
  10902. backgroundColor: $r('app.color.btn_green'),
  10903. title: '确认关闭',
  10904. maskColor: Color.Transparent,
  10905. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  10906. borderStyle: BorderStyle.Dashed,
  10907. primaryButton: '暂不关闭',
  10908. secondaryButton: '确定',
  10909. onAction: (action) => {
  10910. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  10911. this.stopCountdown();
  10912. this.selectedMinutes = 0
  10913. } else if (action == DialogAction.TWO) {
  10914. }
  10915. }
  10916. })
  10917. }
  10918. // 停止倒计时
  10919. private stopCountdown() {
  10920. if (this.timerId !== -1) {
  10921. clearInterval(this.timerId);
  10922. this.timerId = -1;
  10923. }
  10924. }
  10925. // 超时处理
  10926. private handleTimeout() {
  10927. // 执行播放器关闭逻辑
  10928. this.selectedMinutes = 0;
  10929. ToastUtil.showToast(" 定时关闭已完成");
  10930. this.stop(); // 假设存在的播放器实例
  10931. //退出APP
  10932. const mContext = getContext(this) as common.UIAbilityContext
  10933. mContext.terminateSelf();
  10934. AvSessionController.getInstance(true).unregisterSessionListener()
  10935. }
  10936. //倒计时关闭音乐,退出App功能实现结束。
  10937. //播放列表的拖动List 重新排序
  10938. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  10939. //左滑操作 移动文件 重命名 删除等操作
  10940. @Builder
  10941. sonButton(item: VideoItem, index: number, filePath: string) {
  10942. Row() {
  10943. //加入下一首播放
  10944. Button() {
  10945. Image($r('app.media.next_to_play'))
  10946. .fillColor(Color.White)
  10947. .width(20)
  10948. }
  10949. .width(40)
  10950. .height(40)
  10951. .type(ButtonType.Circle)
  10952. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  10953. .backgroundColor(this.themeColor)
  10954. .margin(5)
  10955. .onClick(() => {
  10956. this.addToNextPlay(item);
  10957. })
  10958. Button() {
  10959. Image($r('app.media.close'))
  10960. .fillColor(Color.White)
  10961. .width(20)
  10962. }
  10963. .width(40)
  10964. .height(40)
  10965. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  10966. .type(ButtonType.Circle)
  10967. .backgroundColor(this.themeColor)
  10968. .margin(5)
  10969. .onClick(() => {
  10970. this.songList.splice(Number(index), 1)
  10971. this.sonDataSource.pushArrayData(this.songList)
  10972. })
  10973. Button() {
  10974. Image($r('app.media.share2'))
  10975. .fillColor(Color.White)
  10976. .width(20)
  10977. }
  10978. .width(40)
  10979. .height(40)
  10980. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  10981. .type(ButtonType.Circle)
  10982. .backgroundColor(this.themeColor)
  10983. .margin(5)
  10984. .onClick(() => {
  10985. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  10986. })
  10987. }
  10988. }
  10989. itemMoveSon(index: number, newIndex: number): void {
  10990. if (newIndex < 0 || newIndex >= this.songList.length) {
  10991. return;
  10992. }
  10993. let tmp = this.songList.splice(index, 1);
  10994. this.songList.splice(newIndex, 0, tmp[0]);
  10995. this.sonDataSource.pushArrayData(this.songList)
  10996. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  10997. if(this.modeType==4&&this.playlistTable){
  10998. updateAllSongsSortOrder(this.playlistTable, this.songList,this.currentSongListID)
  10999. }
  11000. }
  11001. @Builder
  11002. PlayList() {
  11003. List({ scroller: this.playListScroller }) {
  11004. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  11005. ListItem() {
  11006. this.MusicItemSon(item, index)
  11007. }
  11008. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  11009. .animation({
  11010. duration: 666,
  11011. curve: 'ease-in-out' // 可选动画曲线
  11012. })
  11013. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 600 }),
  11014. // TransitionEffect.scale({ x: 0, y: 0 })))
  11015. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  11016. //拖动List关键代码开始
  11017. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  11018. .zIndex(this.dragItem === index ? 1 : 0)
  11019. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  11020. .gesture(
  11021. GestureGroup(GestureMode.Sequence,
  11022. LongPressGesture({ repeat: true })
  11023. .onAction((event?: GestureEvent) => {
  11024. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  11025. this.scaleItem = index
  11026. })
  11027. })
  11028. .onActionEnd(() => {
  11029. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  11030. this.scaleItem = -1
  11031. })
  11032. }),
  11033. PanGesture({ fingers: 1, direction: null, distance: 0 })
  11034. .onActionStart(() => {
  11035. this.dragItem = index // 记录当前拖动项索引
  11036. this.dragRefOffset = 0 // 重置偏移基准
  11037. })
  11038. .onActionUpdate((event: GestureEvent) => {
  11039. this.offsetY = event.offsetY - this.dragRefOffset;
  11040. this.neighborItem = -1;
  11041. let indexA = this.songList.indexOf(item);
  11042. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  11043. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  11044. let value: number = 0;
  11045. if (this.offsetY < 0) {
  11046. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  11047. this.neighborItem = indexA - 1;
  11048. this.neighborScale = 1 - value / 20;
  11049. } else if (this.offsetY > 0) {
  11050. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  11051. this.neighborItem = indexA + 1;
  11052. this.neighborScale = 1 - value / 20;
  11053. }
  11054. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  11055. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  11056. this.offsetY -= this.ITEM_INTV;
  11057. this.dragRefOffset += this.ITEM_INTV;
  11058. this.itemMoveSon(indexA, indexA + 1);
  11059. });
  11060. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  11061. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  11062. this.offsetY += this.ITEM_INTV;
  11063. this.dragRefOffset -= this.ITEM_INTV;
  11064. this.itemMoveSon(indexA, indexA - 1);
  11065. });
  11066. }
  11067. })
  11068. .onActionEnd((event: GestureEvent) => {
  11069. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  11070. this.dragItem = -1
  11071. this.neighborItem = -1
  11072. })
  11073. animateTo({
  11074. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  11075. }, () => {
  11076. this.scaleItem = -1
  11077. })
  11078. })
  11079. )
  11080. .onCancel(() => {
  11081. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  11082. this.dragItem = -1
  11083. this.neighborItem = -1
  11084. })
  11085. animateTo({
  11086. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  11087. }, () => {
  11088. this.scaleItem = -1
  11089. })
  11090. })
  11091. ) //拖动List关键代码结束
  11092. .onClick(() => {
  11093. this.doPlay(item, index, true)
  11094. })
  11095. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  11096. }
  11097. .width('100%')
  11098. .height('100%')
  11099. .onReachEnd(() => {
  11100. if(this.modeType === 4 )
  11101. return;
  11102. // 检测是否是流媒体类型(Navidrome/Jellyfin/Emby/AudioStation/Plex),如果是则调用网盘加载更多逻辑
  11103. const isStreamingSong = this.currentSong && (
  11104. isNavidromeType(this.currentSong.type) ||
  11105. isJellyfinType(this.currentSong.type) ||
  11106. isEmbyType(this.currentSong.type) ||
  11107. isAudioStationType(this.currentSong.type) ||
  11108. isPlexType(this.currentSong.type)
  11109. );
  11110. if (isStreamingSong && hasMoreData()) {
  11111. Logger.info('heanup', '播放列表滚动到底部,加载更多流媒体歌曲');
  11112. void this.loadMoreNavidromeSongs();
  11113. } else {
  11114. void this.tryLoadNextPageForPlayback();
  11115. }
  11116. })
  11117. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  11118. // .animation({ duration: 500, curve: Curve.Ease }))
  11119. .cachedCount(10)
  11120. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  11121. .gesture(PinchGesture({ fingers: 2 })
  11122. .onActionEnd((event: GestureEvent) => {
  11123. this.setSonListTwoFingers()
  11124. })
  11125. .onActionUpdate(e => {
  11126. this.scaleValue = this.pinchValue * e.scale
  11127. })
  11128. .onActionStart(e => {
  11129. }))
  11130. .padding({
  11131. bottom: 0
  11132. })
  11133. }
  11134. setSonListTwoFingers() {
  11135. this.pinchValue = this.scaleValue;
  11136. Logger.info('this.pinchValue = ' + this.pinchValue);
  11137. if (this.pinchValue >= 1) {
  11138. this.sonTwoFingerType++
  11139. Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
  11140. if (this.sonTwoFingerType > 3) {
  11141. this.sonTwoFingerType = 1
  11142. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  11143. }
  11144. } else {
  11145. this.sonTwoFingerType--
  11146. Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
  11147. if (this.sonTwoFingerType < 1) {
  11148. this.sonTwoFingerType = 1
  11149. }
  11150. }
  11151. PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
  11152. this.pinchValue = 1;
  11153. this.scaleValue = 1;
  11154. }
  11155. @State sonTwoFingerType:number = 3
  11156. @Builder
  11157. private MusicItemSon(item: VideoItem, index?: number) {
  11158. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  11159. Row() {
  11160. Stack() {
  11161. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  11162. .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  11163. .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  11164. .alt($r('app.media.alt'))
  11165. .fillColor(this.themeColor)
  11166. .borderRadius(this.isCoverRectangle?11:'100%')
  11167. .clip(true)
  11168. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  11169. .draggable(false)// 禁止长按手势拖动
  11170. .autoResize(true) // 重采样,可减少内存占用
  11171. .margin({ left: 20 })
  11172. }
  11173. .width('15%')
  11174. Column() {
  11175. Column() {
  11176. Text(this.isShowFileName?item.fileName :item.name)
  11177. .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
  11178. .fontColor(this.curIndex === index ? this.themeColor :
  11179. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  11180. .maxLines(1)
  11181. .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
  11182. Row() {
  11183. Column(){
  11184. Text(item.md5Str?.includes('Lossless')?
  11185. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  11186. .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
  11187. .padding({ top: 3,right:6,left:6,bottom:3 })
  11188. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  11189. $r('app.color.text_color'))
  11190. .fontWeight(500)
  11191. .borderRadius(12)
  11192. .visibility(StrUtil.isEmpty(item.md5Str) ? Visibility.None : Visibility.Visible)
  11193. .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
  11194. .backgroundColor('#FFC107')
  11195. }
  11196. .padding({ top: 8 })
  11197. Text(StrUtil.isEmpty(item.artist) ? item.duration :
  11198. item.artist + ' ' + item?.duration)
  11199. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  11200. .padding({ top: 8 })
  11201. .maxLines(1)
  11202. .fontColor(this.curIndex === index ? this.themeColor :
  11203. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  11204. .margin({ left: StrUtil.isEmpty(item.md5Str)? 12 :this.sonTwoFingerType == 3 ? 5 : 3 })
  11205. Blank()
  11206. Text(item.size)
  11207. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  11208. .padding({ top: 8 })
  11209. .maxLines(1)
  11210. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  11211. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  11212. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  11213. .margin({ left: 10 })
  11214. }
  11215. }
  11216. .height('100%')
  11217. .width('100%')
  11218. .justifyContent(FlexAlign.Center)
  11219. .alignItems(HorizontalAlign.Start)
  11220. }
  11221. .height('100%')
  11222. .width('65%')
  11223. Column() {
  11224. PlayingIndicator({
  11225. isActive: this.videoUrl === item.filePath && !this.isMultiSelect,
  11226. indicatorSize: 18
  11227. })
  11228. }
  11229. .width('20%')
  11230. }
  11231. }
  11232. .backgroundColor(Color.Transparent)
  11233. .width('100%')
  11234. .reuseId('son_item')
  11235. .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
  11236. .shadow(this.scaleItem === index ? {
  11237. radius: 70,
  11238. color: '#15000000',
  11239. offsetX: 0,
  11240. offsetY: 0
  11241. } :
  11242. {
  11243. radius: 0,
  11244. color: '#15000000',
  11245. offsetX: 0,
  11246. offsetY: 0
  11247. })
  11248. .animation({ curve: Curve.Sharp, duration: 300 })
  11249. }
  11250. @Builder
  11251. private MusicPlayDismissProxyDot() {
  11252. Stack({ alignContent: Alignment.Center }) {
  11253. Image(StrUtil.isNotEmpty(this.cover) ? this.cover as string : $r('app.media.alt'))
  11254. .width('100%')
  11255. .height('100%')
  11256. .objectFit(ImageFit.Cover)
  11257. .alt($r('app.media.alt'))
  11258. }
  11259. .width(this.playDismissProxySize)
  11260. .height(this.playDismissProxySize)
  11261. .borderRadius(this.playDismissProxySize)
  11262. .clip(true)
  11263. .opacity(this.playDismissProxyOpacity)
  11264. .translate({ x: this.playDismissTranslateX, y: this.translateY })
  11265. .shadow({
  11266. radius: 18,
  11267. type: ShadowType.BLUR,
  11268. color: 'on_primary'
  11269. })
  11270. }
  11271. @Builder
  11272. MusicPlayBuilder() {
  11273. Stack({ alignContent: Alignment.Center }) {
  11274. Column() {
  11275. this.IjkMusicPlayerView()
  11276. }
  11277. .visualEffect(deviceInfo.sdkApiVersion>=20&&this.bgController&&this.playDismissOpacity>=1
  11278. && this.playDismissProxySize<=0 && this.playDismissBorderRadius<=0 ?
  11279. new hdsEffect.HdsEffectBuilder()
  11280. .shaderEffect({
  11281. effectType: hdsEffect.EffectType.UV_BACKGROUND_FLOW_LIGHT,
  11282. animation: {
  11283. duration: 10000,
  11284. iterations: -1,
  11285. autoPlay: true,
  11286. onFinish: ()=> {
  11287. console.info('Succeeded in finishing');
  11288. }
  11289. },
  11290. controller: this.bgController,
  11291. })
  11292. .buildEffect():null)
  11293. .height('100%')
  11294. .width('100%')
  11295. .borderRadius(this.playDismissBorderRadius)
  11296. .clip(true)
  11297. .translate({ x: this.playDismissTranslateX, y: this.translateY })
  11298. .scale({ x: this.playDismissScale, y: this.playDismissScaleY })
  11299. .opacity(this.playDismissOpacity)
  11300. if (this.playDismissProxySize > 0) {
  11301. this.MusicPlayDismissProxyDot()
  11302. }
  11303. }
  11304. .height('100%')
  11305. .width('100%')
  11306. .onAppear(() => {
  11307. this.startPlayerViewOpenAnimationIfNeeded()
  11308. })
  11309. .onDisAppear(() => {
  11310. this.resetMusicPlayDismissState()
  11311. })
  11312. .gesture(
  11313. PanGesture(this.panOption)
  11314. .onActionUpdate((event?: GestureEvent) => {
  11315. if (event) {
  11316. // 判断滑动方向
  11317. const offsetY = event.offsetY ?? 0;
  11318. const isSwipeUp = offsetY < 0;
  11319. if (isSwipeUp) {
  11320. // 向上滑动:不应用位移动画,保持 translateY = 0
  11321. this.translateY = 0;
  11322. this.scaleValueImage = 1
  11323. this.scaleValueText = 1
  11324. this.playDragUiOpacity = 1
  11325. } else {
  11326. if(this.isGeKongPlayNext){
  11327. return
  11328. }
  11329. // 向下滑动:应用位移动画
  11330. this.translateY = offsetY;
  11331. // 向下滑动时的缩放效果
  11332. this.getUIContext().animateTo({
  11333. duration: 500,
  11334. curve: Curve.Sharp
  11335. }, () => {
  11336. this.scaleValueImage = Math.min(1, Math.max(0.46, 1 - this.translateY / 900));
  11337. console.info('onecold scaleValueImage:', this.scaleValueImage)
  11338. this.scaleValueText = Math.min(1, Math.max(0.88, 1 - this.translateY / 2000));
  11339. this.playDragUiOpacity = Math.min(1, Math.max(0, 1 - this.translateY / 300));
  11340. })
  11341. }
  11342. }
  11343. })
  11344. .onActionEnd((event?: GestureEvent) => {
  11345. // 判断滑动方向
  11346. const offsetY = event?.offsetY ?? 0;
  11347. const isSwipeUp = offsetY < 0;
  11348. const minDistance = 300; // 最小滑动距离
  11349. const minVelocity = 500; // 最小滑动速度
  11350. const velocity = event?.velocityY ?? 0;
  11351. if (isSwipeUp) {
  11352. // 向上滑动:切换下一首
  11353. const shouldSwitch = this.isPlayPageSwipeNext &&
  11354. (Math.abs(offsetY) > minDistance || Math.abs(velocity) > minVelocity);
  11355. if (shouldSwitch) {
  11356. // 直接切换下一首,无需动画(因为界面没有移动)
  11357. this.playNext().catch(() => {
  11358. Logger.error('heanup MusicPlayBuilder', '向上滑动切换下一首失败');
  11359. });
  11360. }
  11361. } else {
  11362. //这里加个变量,是否开启隔空手势播放下一首
  11363. if(this.isGeKongPlayNext){
  11364. this.playNext()
  11365. return
  11366. }
  11367. // 向下滑动:关闭播放页
  11368. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  11369. if (shouldClose) {
  11370. this.closePlayerViewWithMiniBarAnimation()
  11371. } else {
  11372. // 回弹动画
  11373. this.getUIContext().animateTo({
  11374. duration: 600,
  11375. curve: Curve.Friction
  11376. }, () => {
  11377. this.scaleValueImage = 1
  11378. this.scaleValueText = 1
  11379. this.playDragUiOpacity = 1
  11380. this.translateY = 0;
  11381. })
  11382. }
  11383. }
  11384. })
  11385. )
  11386. }
  11387. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  11388. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  11389. HeightBreakpoint.HEIGHT_LG;
  11390. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  11391. @State topBarHeight: number = 50
  11392. @State barOpacity: number = 1
  11393. @State barBottomOpacity: number = 1
  11394. private hideDone: boolean = false;
  11395. @State currentYOffset: number = 0;
  11396. @State bottomBarHeight: number = 68;
  11397. private isHiding: boolean = false;
  11398. //是否是Pura X外屏,或者小屏幕
  11399. isPuraWP() {
  11400. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  11401. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  11402. }
  11403. //是否是Pura X外屏,或者小屏幕,手机横屏
  11404. /**
  11405. * 是否是Pura X外屏,或者小屏幕,手机横屏
  11406. * @returns
  11407. */
  11408. isCoverOpacity() {
  11409. if (this.isPuraWP()) {
  11410. return true
  11411. }
  11412. if (this.isPhoneLan()) {
  11413. return true
  11414. }
  11415. if (deviceInfo.marketName.includes('Pura X')
  11416. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  11417. return true
  11418. }
  11419. return false
  11420. }
  11421. //是不是手机横屏
  11422. isPhoneLan() {
  11423. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  11424. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  11425. logHiCarWindow(`isPhoneLan width=${this.windowWidth}`);
  11426. logHiCarWindow(`isPhoneLan height=${this.windowHeight}`);
  11427. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarStatus=${this.isHiCarStatus}`);
  11428. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, curDisplayIsHiCar=${this.curDisplayIsHiCar}`);
  11429. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall=${this.isHiCarSmall()}`);
  11430. if (this.isHiCarKuanBianPing()) {
  11431. return true
  11432. }
  11433. if (this.isHiCar()) {
  11434. return false
  11435. }
  11436. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  11437. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  11438. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  11439. return true
  11440. }
  11441. return false
  11442. }
  11443. //是不是1920x720的hicar的屏幕分辨率
  11444. isHiCarKuanBianPing(){
  11445. // if(!this.isHiCar()){
  11446. // return false
  11447. // }
  11448. const hiCarAspectRatios: HiCarAspectRatio[] = [
  11449. { ratio: 1920 / 720, name: "1920x720" },
  11450. ];
  11451. const currentRatio: number = this.windowWidth / this.windowHeight;
  11452. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  11453. logHiCarWindow(`HiCarKuanBianPing currentRatio=${currentRatio}`)
  11454. for (const hiCarRatio of hiCarAspectRatios) {
  11455. logHiCarWindow(`HiCarKuanBianPing hiCarRatio=${hiCarRatio.ratio}`)
  11456. logHiCarWindow(`HiCarKuanBianPing diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  11457. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  11458. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  11459. //宽扁平的尺寸设置列表展示
  11460. this.twoFingerType ==3
  11461. this.isGridMusic = false
  11462. return true;
  11463. }
  11464. }
  11465. return false;
  11466. }
  11467. //是不是hicar的屏幕分辨率
  11468. isHiCarSmall() {
  11469. if(!this.isHiCar()){
  11470. return false
  11471. }
  11472. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  11473. {
  11474. this.columns = 6
  11475. return false
  11476. }
  11477. const hiCarAspectRatios: HiCarAspectRatio[] = [
  11478. { ratio: 800 / 480, name: "800x480" },
  11479. { ratio: 1280 / 720, name: "1280x720" },
  11480. { ratio: 1920 / 1080, name: "1920x1080" },
  11481. ];
  11482. const currentRatio: number = this.windowWidth / this.windowHeight;
  11483. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  11484. logHiCarWindow(`HiCarSmall currentRatio=${currentRatio}`)
  11485. for (const hiCarRatio of hiCarAspectRatios) {
  11486. logHiCarWindow(`HiCarSmall hiCarRatio=${hiCarRatio.ratio}`)
  11487. logHiCarWindow(`HiCarSmall diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  11488. logHiCarWindow(`HiCarSmall isHiCarStatus=${this.isHiCarStatus}`);
  11489. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  11490. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  11491. //宽扁平的尺寸设置列表展示
  11492. return true;
  11493. }
  11494. }
  11495. return false;
  11496. }
  11497. isHiCar(): boolean {
  11498. return this.curDisplayIsHiCar;
  11499. }
  11500. //是不是正常的手机竖屏
  11501. isPhonePortrait() {
  11502. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  11503. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  11504. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  11505. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  11506. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  11507. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  11508. return true
  11509. }
  11510. return false
  11511. }
  11512. @State showSpeedDialog: boolean = false
  11513. @State longPressSpeed: number = 3 //长按默认倍数
  11514. @Builder
  11515. SpeedDialog() {
  11516. Stack() {
  11517. Column() {
  11518. Text('已切换至' + this.longPressSpeed + '倍速播放')
  11519. .fontColor(Color.White)
  11520. .visibility(Visibility.Hidden)
  11521. }
  11522. .backgroundColor(Color.Black)
  11523. .borderRadius(20)
  11524. .padding({
  11525. top: 10,
  11526. right: 20,
  11527. left: 15,
  11528. bottom: 20
  11529. })
  11530. .opacity(0.6)
  11531. Text('已切换至' + this.longPressSpeed + '倍速播放')
  11532. .fontColor(Color.White)
  11533. }
  11534. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  11535. .zIndex(5)
  11536. .margin({ top: 80 })
  11537. }
  11538. @Builder
  11539. IjkMusicPlayerView() {
  11540. Stack() {
  11541. if(canIUse("SystemCapability.UIDesign.HDSComponent.Core")
  11542. &&deviceInfo.sdkApiVersion>=20&&this.sceneBgController){
  11543. HdsVisualComponent()
  11544. .scene(HdsSceneType.DUAL_EDGE_FLOW_LIGHT_WITH_BACKGROUND_MASK, this.sceneBgController, () => {
  11545. console.info('Succeeded in finishing');
  11546. })
  11547. .width('100%')
  11548. .height('100%')
  11549. .visibility(this.isShowBgLiuGUANG?Visibility.Visible:Visibility.None)
  11550. }
  11551. Column() {
  11552. Column() {
  11553. //播放标题
  11554. Column() {
  11555. this.PlayTitle()
  11556. }
  11557. .opacity(this.playDragUiOpacity)
  11558. .position({ x: 0, y: this.isCoverOpacity() ? 10 : 40 })
  11559. .width('100%')
  11560. .margin({ top: 0 })
  11561. .height(PlayConstants.HEIGHT)
  11562. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  11563. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  11564. if (this.showSpeedDialog) {
  11565. this.SpeedDialog()
  11566. }
  11567. Stack() {
  11568. //手势拖动快进
  11569. Column()
  11570. .width(CommonConstants.FULL_PERCENT)
  11571. .height('100%')
  11572. .gesture(
  11573. GestureGroup(GestureMode.Parallel,
  11574. // 长按屏幕倍数播放
  11575. LongPressGesture({ repeat: true })
  11576. .onAction(() => {
  11577. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  11578. this.showSpeedDialog = true;
  11579. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  11580. }
  11581. })
  11582. .onActionEnd(() => {
  11583. this.showSpeedDialog = false;
  11584. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  11585. }),
  11586. )
  11587. )
  11588. }
  11589. .height('65%')
  11590. Swiper() {
  11591. this.CoverInfo()
  11592. this.PlayerLyrics()
  11593. }
  11594. .onChange((index: number) => {
  11595. this.currentSwiperIndex = index
  11596. if (index === 1) {
  11597. this.syncLyricPositionNow()
  11598. }
  11599. })
  11600. .indicator(false)
  11601. .displayCount(this.getPlayerSwiperDisplayCount())
  11602. .clip(false)
  11603. .loop(false)
  11604. .autoPlay(false)
  11605. // .interval(8000)
  11606. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  11607. .height('100%')
  11608. .hitTestBehavior(HitTestMode.Transparent)
  11609. Image($r('app.media.icon_replay'))
  11610. .objectFit(ImageFit.Auto)
  11611. .width('120px')
  11612. .height('120px')
  11613. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  11614. .border({ width: 0 })
  11615. .visibility(Visibility.None)
  11616. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  11617. .onClick(() => {
  11618. console.info('onecold startPlayOrResumePlay 6744')
  11619. this.startPlayOrResumePlay();
  11620. })
  11621. }
  11622. .width(CommonConstants.FULL_PERCENT)
  11623. .height(CommonConstants.FULL_PERCENT)
  11624. .justifyContent(FlexAlign.End)
  11625. }
  11626. .justifyContent(FlexAlign.End)
  11627. .margin({ bottom: 5 })
  11628. }
  11629. .backgroundImage(!this.isMusicBGCover||StrUtil.isEmpty(this.cover)?null: this.cover)
  11630. .backgroundImageSize(this.isPuraWP()||!this.isMusicBGCover ? { width: '100%' } : { height: '150%', width: '100%' })
  11631. .animation({
  11632. duration: 666,
  11633. curve: 'ease-in-out' // 可选动画曲线
  11634. })
  11635. .backgroundBlurStyle((this.isPuraWP() && this.currentSwiperIndex === 0) ||!this.isMusicBGCover
  11636. ? BlurStyle.NONE :
  11637. BlurStyle.BACKGROUND_ULTRA_THICK)
  11638. .hitTestBehavior(HitTestMode.Transparent)
  11639. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  11640. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  11641. .onClick(() => {
  11642. if(this.isHiCar())
  11643. return
  11644. if(this.is_auto_hide_progress){
  11645. this.is_auto_hide_progress = false
  11646. }
  11647. this.startAutoHide()
  11648. })
  11649. }
  11650. @Consume progressValue: number ;
  11651. @State currentTime: string = "00:00";
  11652. @State totalTime: string = "00:00";
  11653. @State loadingVisible: Visibility = Visibility.None;
  11654. @State replayVisible: Visibility = Visibility.None;
  11655. @State slideEnable: boolean = false;
  11656. @State aspRatio: number = 0.5;
  11657. @State mContext: object | undefined = undefined;
  11658. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  11659. @State mFirst: boolean = true;
  11660. @State mDestroyPage: boolean = false;
  11661. @State playSpeed: number = 1;
  11662. @State oldSeconds: number = 0;
  11663. @State isSeekTo: boolean = false;
  11664. @State isCurrentTime: boolean = false;
  11665. @State videoWidth: string = '100%';
  11666. @State videoHeight: string = '100%';
  11667. @State initAspectRatio: number = 1;
  11668. @State videoAspectRatio: number = this.initAspectRatio;
  11669. @State videoUrl: string = '';
  11670. private last: number = 0;
  11671. @State videoParentAspectRatio: number = this.initAspectRatio;
  11672. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  11673. @Consume CONTROL_PlayStatus: number ;
  11674. @State PROGRESS_MAX_VALUE: number = 100;
  11675. @State updateProgressTimer: number = 0;
  11676. private readonly progressUpdateIntervalMs: number = 120;
  11677. private readonly lyricUpdateMinDeltaMs: number = 24;
  11678. private lastLyricRenderPosition: number = Number.NaN;
  11679. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  11680. @State name: string = '';
  11681. // @State loop: boolean = false;
  11682. @State playType: number = 0; //0:连续循环播放 1:单片重复播放 2:正常播放 3:随机播放 4:连续播放不循环
  11683. @State multiple: string = '1.0X';
  11684. xcomponentController: XComponentController = new XComponentController()
  11685. private panOptionBright: PanGestureOptions =
  11686. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  11687. private panOptionVolume: PanGestureOptions =
  11688. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  11689. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  11690. //手势的音量控制和亮度控制
  11691. private positionX: number = PlayConstants.POSITION_X;
  11692. private positionY: number = PlayConstants.POSITION_Y;
  11693. private windowClass: window.Window = globalThis.windowClass
  11694. @State volume: number = 0.8;
  11695. @State volumeBoostPercent: number = 0
  11696. @State volumeSmall: boolean = false
  11697. @State autoParseMusicName: boolean = true
  11698. @State isShowFileName: boolean = false
  11699. @State isLongNameRoLL: boolean = true//长歌名滚动
  11700. private readonly volumeBoostPreferenceKey: string = 'volumeBoostPercent';
  11701. private readonly volumeBoostMaxPercent: number = 500;
  11702. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  11703. @State bright: number = PlayConstants.BRIGHT;
  11704. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  11705. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  11706. @State screenWidth: number = 0
  11707. @State screenHeight: number = 0
  11708. @State statusBarHeight: number = 0
  11709. @State isYesFull: boolean = false
  11710. private seekValue: number = 0
  11711. @State isVideoLock: boolean = false; // Whether the video playback is locked
  11712. private preloadNextRandomIndex: number = -1; // 预缓存的随机下一首索引
  11713. private playbackUrlRequestSerial: number = 0;
  11714. eventHub = getContext().eventHub;
  11715. private isAppForeground: boolean = true;
  11716. private lastBufferingLogTs: number = 0;
  11717. private readonly bufferingLogIntervalMs: number = 5000;
  11718. //投播组件
  11719. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  11720. // 新的投播控制器(封装了官方示例的逻辑)
  11721. private castControllerWrapper: CastController | undefined = undefined;
  11722. // 保留原始的 avCastController 引用(用于兼容旧代码)
  11723. private castController: avSession.AVCastController | undefined = undefined;
  11724. @State isCastPlaying: boolean = false;
  11725. @State currentTime2: number = 0;
  11726. @State currentStringTime: string = '00:00';
  11727. @State duration: number = 0;
  11728. @State isReady: boolean = false;
  11729. @State durationTime: number = 0;
  11730. @State durationStringTime: string = '00:00';
  11731. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  11732. // @State isPlaying: boolean = false;
  11733. private castSeek: boolean = false;
  11734. private castItem: avSession.AVQueueItem | undefined = undefined;
  11735. private castFile: fs.File | undefined = undefined; // 保持文件描述符引用,避免被垃圾回收
  11736. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  11737. @State rotateAngle2: number = -9
  11738. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  11739. @Consume cover: string | undefined ;
  11740. @State artist: string | undefined = ''
  11741. // 1.初始化controller
  11742. private lyricController: LyricController = new LyricController()
  11743. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  11744. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  11745. private parser = new LyricParser()
  11746. @State randomShakenX: number = 0
  11747. @State randomShakenY: number = 0
  11748. @State lyricTextSize: number = 24
  11749. @State lyricContent: string = ''
  11750. @State isDebug: boolean = false
  11751. @State isHightLightCenter: boolean = true
  11752. private syncWordByWordLyricMode(): void {
  11753. this.lyricController.setEnableWordByWordLyric(this.isEnableWordByWordLyric)
  11754. this.lyricControllerXF.setEnableWordByWordLyric(this.isEnableWordByWordLyric)
  11755. this.lyricControllerSingle.setEnableWordByWordLyric(this.isEnableWordByWordLyric)
  11756. }
  11757. private syncLyricLightTextMode(): void {
  11758. this.lyricController.setLightText(this.isLightText)
  11759. this.lyricControllerXF.setLightText(this.isLightText)
  11760. this.lyricControllerSingle.setLightText(this.isLightText)
  11761. }
  11762. /**
  11763. * 初始化歌词加载与展示逻辑
  11764. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  11765. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  11766. * @param isApi2 是否使用API2获取歌词(可选)
  11767. *
  11768. * 主要流程:
  11769. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  11770. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  11771. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  11772. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  11773. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  11774. * 6. 解析失败或读取失败时,清空歌词显示。
  11775. *
  11776. * 注意事项:
  11777. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  11778. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  11779. * - 歌词内容解析后通过lyricController驱动UI渲染。
  11780. */
  11781. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
  11782. if (StrUtil.isEmpty(lyricPath)) {
  11783. return
  11784. }
  11785. this.syncWordByWordLyricMode()
  11786. this.syncLyricLightTextMode()
  11787. this.initPipLyricSetting()
  11788. this.lyricControllerSingle
  11789. .setTextSize(15)
  11790. .setCacheSize(4)
  11791. .setTextColor("#FFFFFF")
  11792. .setHighlightColor(this.currentHighLightLyricColor)
  11793. .setHighlightScale(1.2)
  11794. .setEmptyHint("")
  11795. .setLineSpace(1)
  11796. .setAlignMode('center')
  11797. .setAnimationDuration(500)
  11798. .setSingleLine(true)
  11799. this.lyricContent = ''
  11800. this.lyricController
  11801. .setTextSize(this.currentLyricSize)
  11802. .setCacheSize(4)
  11803. .setTextColor("#DDDDDD")
  11804. .setHighlightColor("#FFFFFF")
  11805. .setEmptyHint("")
  11806. .setAnimationDuration(1000)
  11807. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  11808. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  11809. this.setBlurDegree(this.blurDegree, false)
  11810. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  11811. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  11812. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  11813. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  11814. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  11815. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  11816. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  11817. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  11818. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  11819. this.lyricController.setTextWeight(this.lyricTextWeight)
  11820. this.showSingleLyric = false
  11821. // 加载已保存的歌词时间偏移
  11822. this.loadLyricTimeOffset()
  11823. this.lyricController.setLyric(null)
  11824. this.lyricControllerSingle.setLyric(null)
  11825. console.log("onecold lyricPath =" + lyricPath)
  11826. // 1. 检查内嵌歌词
  11827. let neiqianLrc = ''
  11828. let lyContent = this.currentSong?.lyricContent
  11829. if(lyContent && StrUtil.isNotEmpty(lyContent)){
  11830. neiqianLrc = lyContent
  11831. }
  11832. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast && !isLocal) {
  11833. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  11834. // Navidrome JSON歌词转换
  11835. if (this.currentSong && isNavidromeType(this.currentSong.type)) {
  11836. const convertedLyric: string | undefined = LyricUtil.convertNavidromeJsonLyricToLrc(neiqianLrc);
  11837. if (convertedLyric) {
  11838. neiqianLrc = convertedLyric;
  11839. console.log("onecold Navidrome歌词转换成功");
  11840. }
  11841. }
  11842. this.setLyricToControllers(neiqianLrc);
  11843. return
  11844. }
  11845. // 2. 远程播放实时探测歌词: 优先探测内嵌歌词,失败后查找同路径同名 .lrc
  11846. if (this.currentSong && shouldResolveRemoteLyricOnPlay(this.currentSong) && !isOnLineAndToast && !isLocal) {
  11847. const remoteLyric: string = await tryResolveRemotePlaybackLyric({
  11848. song: this.currentSong,
  11849. playbackUrl: this.videoUrl,
  11850. manager: RemoteDriveManager.getInstance(),
  11851. detectEncoding: (data: ArrayBuffer): string => this.detect(data)
  11852. });
  11853. if (StrUtil.isNotEmpty(remoteLyric)) {
  11854. this.currentSong.lyricContent = remoteLyric;
  11855. this.setLyricToControllers(remoteLyric);
  11856. void this.persistRemoteMetadataToDb(this.currentSong);
  11857. return;
  11858. }
  11859. }
  11860. // 3. 尝试从服务器获取歌词 (Navidrome/Jellyfin/Emby/AudioStation/Plex)
  11861. if (this.currentSong && (isJellyfinType(this.currentSong.type)||isNavidromeType(this.currentSong.type)
  11862. || isEmbyType(this.currentSong.type) || isAudioStationType(this.currentSong.type)
  11863. || isPlexType(this.currentSong.type))) {
  11864. const manager = RemoteDriveManager.getInstance();
  11865. const getAccount = (accountId: string) => manager.getWebDavAccountById(accountId);
  11866. // 将currentSong转换为SongData接口
  11867. const songData: SongData = {
  11868. webdav_account_id: this.currentSong.webdav_account_id,
  11869. artist: this.currentSong.artist,
  11870. name: this.currentSong.name,
  11871. webdav_id: this.currentSong.webdav_id,
  11872. lyricIndex: this.currentSong.lyricIndex,
  11873. type: this.currentSong.type
  11874. };
  11875. let serverLyric = '';
  11876. if (!serverLyric && isNavidromeType(songData.type)) {
  11877. serverLyric = await lyricService.fetchNavidromeLyric(songData, getAccount,this.currentSong.id);
  11878. }
  11879. if (!serverLyric && isJellyfinType(songData.type)) {
  11880. serverLyric = await lyricService.fetchJellyfinLyric(songData, getAccount);
  11881. }
  11882. if (!serverLyric && isEmbyType(songData.type)) {
  11883. serverLyric = await lyricService.fetchEmbyLyric(songData, getAccount);
  11884. }
  11885. if (!serverLyric && isAudioStationType(songData.type)) {
  11886. serverLyric = await lyricService.fetchAudioStationLyric(songData, getAccount);
  11887. }
  11888. if (!serverLyric && isPlexType(songData.type)) {
  11889. serverLyric = await lyricService.fetchPlexLyric(songData, getAccount);
  11890. }
  11891. if (serverLyric) {
  11892. this.setLyricToControllers(serverLyric, lyricPath);
  11893. return;
  11894. }
  11895. }
  11896. // 4. 尝试在线歌词API
  11897. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath))
  11898. && !Utility.isVideoByExtension(this.videoUrl))) {
  11899. this.fetchOnlineLyric(lyricPath, isOnLineAndToast || false, isApi2);
  11900. return;
  11901. }
  11902. // 5. 从本地文件读取歌词
  11903. await this.loadLyricFromFile(lyricPath, isLocal || false);
  11904. }
  11905. /**
  11906. * 从本地文件加载歌词
  11907. */
  11908. private async loadLyricFromFile(lyricPath: string, isLocal: boolean): Promise<void> {
  11909. try {
  11910. let realLyricPath = lyricPath;
  11911. // 读取文件内容
  11912. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  11913. const stat = await fileIo.stat(file.fd);
  11914. const arrayBuffer = new ArrayBuffer(stat.size);
  11915. fs.read(file.fd, arrayBuffer)
  11916. .then((readLen: number) => {
  11917. console.info("read file data succeed");
  11918. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  11919. if (buf.length === 0) {
  11920. throw new Error("Buffer is empty after reading the file");
  11921. }
  11922. try {
  11923. // 检测文件编码
  11924. let detectedEncoding = this.detect(arrayBuffer);
  11925. console.info("onecoldT Detected encoding: " + detectedEncoding);
  11926. // 使用检测到的编码解码,解决中文乱码问题
  11927. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  11928. console.info("onecoldT Detected textDecoder: " + textDecoder);
  11929. let fileContent = textDecoder.decode(buf);
  11930. console.info(`onecoldT The content of file1: ${fileContent}`);
  11931. console.info(`onecold The content of file2: ${fileContent}`);
  11932. this.lyricContent = fileContent;
  11933. if(isLocal){
  11934. // 编辑标签选择本地歌词需要赋值给this.lyricConStr
  11935. this.lyricConStr = fileContent;
  11936. }
  11937. this.setLyricToControllers(fileContent);
  11938. console.info(`The content of file: ${fileContent}`);
  11939. } catch (chardetError) {
  11940. console.error("chardet.detect failed with error: " + chardetError.message);
  11941. this.clearLyricControllers();
  11942. }
  11943. })
  11944. .catch((err: BusinessError) => {
  11945. this.clearLyricControllers();
  11946. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  11947. })
  11948. .catch((err: Error) => {
  11949. this.clearLyricControllers();
  11950. console.error("read file 2 data failed with error message: " + err.message);
  11951. })
  11952. .finally(() => {
  11953. fs.closeSync(file);
  11954. });
  11955. } catch (error) {
  11956. this.clearLyricControllers();
  11957. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  11958. }
  11959. }
  11960. detect(data: ArrayBuffer): string {
  11961. //创建检测对象
  11962. let detector: UniversalDetector = new UniversalDetector();
  11963. // 限制检测数据大小,避免内存溢出
  11964. // 通常只需要检测文件前16KB就足够判断编码格式
  11965. const MAX_DETECT_SIZE = 16 * 1024; // 16KB
  11966. const detectSize = Math.min(data.byteLength, MAX_DETECT_SIZE);
  11967. // 传入检测数据并实时判断编码格式
  11968. detector.handleData(data, 0, detectSize);
  11969. // 标记检测数据 读取结束
  11970. detector.dataEnd();
  11971. // 获取检测结果
  11972. let detected: string = detector.getDetectedCharset();
  11973. // 释放资源
  11974. detector.reset();
  11975. Logger.info(TAG, "heanup detect encoding: " + detected + ", data size: " + data.byteLength + ", detect size: " + detectSize);
  11976. return detected;
  11977. }
  11978. /**
  11979. * 设置歌词到所有控制器
  11980. * @param lyricText 歌词文本
  11981. * @param savePath 可选,如果提供则保存到本地文件
  11982. */
  11983. private setLyricToControllers(lyricText: string, savePath?: string): void {
  11984. if (StrUtil.isEmpty(lyricText)) {
  11985. this.clearLyricControllers();
  11986. return;
  11987. }
  11988. this.lyricContent = lyricText;
  11989. const lines: string[] = lyricText.split('\n').map((line: string) => line.trim());
  11990. const lyric: Lyric = this.parser.parse(lines);
  11991. this.lyricController.setLyric(lyric);
  11992. this.lyricControllerXF.setLyric(lyric);
  11993. this.lyricControllerSingle.setLyric(lyric);
  11994. this.showSingleLyric = true;
  11995. // 如果提供了保存路径,保存歌词到本地
  11996. if (savePath) {
  11997. this.saveDataToFile(lyricText, savePath);
  11998. }
  11999. }
  12000. /**
  12001. * 清空所有歌词控制器
  12002. */
  12003. private clearLyricControllers(): void {
  12004. this.lyricController.setLyric(null);
  12005. this.lyricControllerXF.setLyric(null);
  12006. this.lyricControllerSingle.setLyric(null);
  12007. }
  12008. private extractLyricCopyLines(lyricText: string): string[] {
  12009. if (StrUtil.isEmpty(lyricText)) {
  12010. return [];
  12011. }
  12012. const normalizedLyric = LyricUtil.convertLyricToSimpleLrc(lyricText);
  12013. const source = StrUtil.isNotEmpty(normalizedLyric) ? normalizedLyric : lyricText;
  12014. const lines = source.split('\n');
  12015. const result: string[] = [];
  12016. const metaTagPattern = /^\[(ti|ar|al|by|offset|hash|sign|qq|total|tool|re|ve|length|au):?.*]$/i;
  12017. for (let i = 0; i < lines.length; i++) {
  12018. const line = lines[i].trim();
  12019. if (!line || metaTagPattern.test(line)) {
  12020. continue;
  12021. }
  12022. const pureLine = line
  12023. .replace(/\[\d{1,2}:\d{2}(?:\.\d{1,3})?]/g, '')
  12024. .replace(/<\d{1,2}:\d{2}(?:\.\d{1,3})?>/g, '')
  12025. .trim();
  12026. if (pureLine.length > 0) {
  12027. result.push(pureLine);
  12028. }
  12029. }
  12030. return result;
  12031. }
  12032. private openLyricCopySheet(): void {
  12033. const lines = this.extractLyricCopyLines(this.lyricContent);
  12034. if (ArrayUtil.isEmpty(lines)) {
  12035. ToastUtil.showToast('暂无可复制歌词');
  12036. return;
  12037. }
  12038. this.lyricCopyLines = lines;
  12039. this.lyricSelectedIndexes = [];
  12040. this.isShowLyricCopySheet = true;
  12041. }
  12042. private toggleLyricLineSelection(index: number): void {
  12043. const selectedIndex = this.lyricSelectedIndexes.indexOf(index);
  12044. if (selectedIndex >= 0) {
  12045. const nextSelectedIndexes = [...this.lyricSelectedIndexes];
  12046. nextSelectedIndexes.splice(selectedIndex, 1);
  12047. this.lyricSelectedIndexes = nextSelectedIndexes;
  12048. return;
  12049. }
  12050. this.lyricSelectedIndexes = [...this.lyricSelectedIndexes, index];
  12051. }
  12052. private toggleLyricSelectAll(): void {
  12053. if (this.lyricSelectedIndexes.length === this.lyricCopyLines.length) {
  12054. this.lyricSelectedIndexes = [];
  12055. return;
  12056. }
  12057. this.lyricSelectedIndexes = this.lyricCopyLines.map((_: string, index: number) => index);
  12058. }
  12059. private copySelectedLyricLines(): void {
  12060. const selectedLines = this.getSelectedLyricLines();
  12061. if (ArrayUtil.isEmpty(selectedLines)) {
  12062. ToastUtil.showToast('暂无可复制歌词');
  12063. return;
  12064. }
  12065. Utility.copyText(selectedLines.join('\n'));
  12066. ToastUtil.showToast(`已复制${selectedLines.length}行歌词`);
  12067. }
  12068. private getSelectedLyricLines(): string[] {
  12069. if (ArrayUtil.isEmpty(this.lyricSelectedIndexes)) {
  12070. return [];
  12071. }
  12072. const selectedIndexes = [...this.lyricSelectedIndexes].sort((a: number, b: number) => a - b);
  12073. const selectedLines: string[] = [];
  12074. for (let i = 0; i < selectedIndexes.length; i++) {
  12075. const index = selectedIndexes[i];
  12076. if (index >= 0 && index < this.lyricCopyLines.length) {
  12077. selectedLines.push(this.lyricCopyLines[index]);
  12078. }
  12079. }
  12080. return selectedLines;
  12081. }
  12082. private shareSelectedLyricLines(): void {
  12083. const selectedLines = this.getSelectedLyricLines();
  12084. if (ArrayUtil.isEmpty(selectedLines)) {
  12085. ToastUtil.showToast('暂无可分享歌词');
  12086. return;
  12087. }
  12088. const shareTitle = `${this.currentSong?.name ?? '歌词'}歌词`;
  12089. Utility.doShareText(selectedLines.join('\n'), this.context, shareTitle, '分享歌词');
  12090. }
  12091. /**
  12092. * 从在线API获取歌词
  12093. */
  12094. private fetchOnlineLyric(lyricPath: string, isOnLineAndToast: boolean, isApi2?: boolean): void {
  12095. if (!this.currentSong) {
  12096. this.clearLyricControllers();
  12097. if (isOnLineAndToast) {
  12098. ToastUtil.showShort('未获取到歌词!');
  12099. }
  12100. return;
  12101. }
  12102. let artist = this.currentSong.artist || '';
  12103. if (isApi2 === undefined) {
  12104. isApi2 = false;
  12105. }
  12106. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  12107. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  12108. this.setLyricToControllers(res, lyricPath);
  12109. } else {
  12110. this.clearLyricControllers();
  12111. if (isOnLineAndToast) {
  12112. ToastUtil.showShort('未获取到歌词!');
  12113. }
  12114. }
  12115. });
  12116. }
  12117. //初始化悬浮歌词的自定义设置
  12118. initPipLyricSetting() {
  12119. this.lyricControllerXF
  12120. .setTextSize(this.currentLyricSize)
  12121. .setCacheSize(4)
  12122. .setTextColor("#DDDDDD")
  12123. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  12124. .setEmptyHint("")
  12125. .setAnimationDuration(1000)
  12126. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  12127. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  12128. this.setBlurDegree(this.blurDegreePip, true)
  12129. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  12130. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  12131. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  12132. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  12133. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  12134. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  12135. this.lyricControllerXF.setHightLightCenter(true)
  12136. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  12137. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  12138. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  12139. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  12140. if (this.pipBgIndex === 0) {
  12141. if (this.cover) {
  12142. this.pipBg = this.cover
  12143. } else {
  12144. this.pipBg = this.imageColor
  12145. }
  12146. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  12147. }
  12148. }
  12149. //根据item返回歌词内容
  12150. async getLyricContent(item: VideoItem): Promise<string> {
  12151. let neiqianLrc = ''
  12152. let lyContent = item?.lyricContent
  12153. if(lyContent&&StrUtil.isNotEmpty(lyContent)){
  12154. neiqianLrc = lyContent
  12155. return neiqianLrc
  12156. }
  12157. try {
  12158. //取数据库里面的歌词lyContent
  12159. const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
  12160. if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
  12161. console.log("onecold Lyrics:", lyricContent);
  12162. neiqianLrc = lyricContent
  12163. return neiqianLrc
  12164. }
  12165. } catch (error) {
  12166. console.error("Error fetching lyrics:", error);
  12167. }
  12168. try {
  12169. let filePath = item.filePath;
  12170. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  12171. let realLyricPath = lyricPath;
  12172. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  12173. const stat = await fileIo.stat(file.fd);
  12174. const arrayBuffer = new ArrayBuffer(stat.size);
  12175. const readLen = await fs.read(file.fd, arrayBuffer);
  12176. console.info("read file data succeed");
  12177. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  12178. if (buf.length === 0) {
  12179. throw new Error("Buffer is empty after reading the file");
  12180. }
  12181. // let detectedEncoding = chardet.detect(buf);
  12182. let detectedEncoding = this.detect(arrayBuffer)
  12183. console.info("Detected encoding: " + detectedEncoding);
  12184. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  12185. let fileContent = textDecoder.decode(buf);
  12186. console.info(`onecold The content of file1: ${fileContent}`);
  12187. fs.closeSync(file);
  12188. return fileContent;
  12189. } catch (error) {
  12190. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  12191. return '';
  12192. }
  12193. }
  12194. async saveDataToFile(content: string, filePath: string) {
  12195. if (StrUtil.isEmpty(filePath)) {
  12196. return
  12197. }
  12198. try {
  12199. let lyricContent = ''
  12200. lyricContent = content
  12201. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  12202. // 清空文件内容
  12203. await fileIo.truncate(file.fd, 0);
  12204. await fileIo.write(file.fd, lyricContent);
  12205. await fileIo.close(file);
  12206. console.log('onecold lyric file Data saved successfully.');
  12207. } catch (error) {
  12208. console.error('onecold lyric file Failed to save data:', error);
  12209. }
  12210. }
  12211. // 定义开始旋转的方法
  12212. // 使用动画系统优化旋转性能,避免 setInterval 频繁更新导致卡顿
  12213. @State timer: number = 0
  12214. @State rotateAngle: number = 0
  12215. @State isRotationRunning: boolean = false // 旋转动画是否正在运行
  12216. @StorageProp('isPageVisible') @Watch('onPageVisibilityChange') isPageVisible: boolean = true // 页面可见性标志
  12217. // 页面可见性变化回调
  12218. onPageVisibilityChange() {
  12219. // 当页面可见性改变时,重新启动/停止旋转动画
  12220. this.animationRoFun()
  12221. }
  12222. //封面旋转动画
  12223. animationRoFun() {
  12224. if (this.isPlaying && !this.isCoverRectangle && this.isPageVisible) {
  12225. // 启动旋转动画
  12226. if (!this.isRotationRunning) {
  12227. this.isRotationRunning = true
  12228. this.startContinuousRotation()
  12229. }
  12230. this.startRotation()
  12231. } else {
  12232. // 停止旋转动画
  12233. this.isRotationRunning = false
  12234. clearInterval(this.timer)
  12235. this.stopRotation()
  12236. }
  12237. }
  12238. // 使用持续的动画进行旋转,避免频繁状态更新
  12239. private startContinuousRotation() {
  12240. clearInterval(this.timer)
  12241. // 改为每 1000ms 更新 36 度(10秒一圈),减少更新频率
  12242. // 不使用 % 360 取模,让角度持续累加,避免反转
  12243. this.timer = setInterval(() => {
  12244. if (this.isRotationRunning) {
  12245. this.rotateAngle = this.rotateAngle + 36
  12246. }
  12247. }, 1000)
  12248. }
  12249. // 定义开始旋转的方法
  12250. startRotation() {
  12251. if (this.isPlaying) {
  12252. animateTo({
  12253. duration: 777,
  12254. iterations: 1,
  12255. curve: Curve.Linear
  12256. }, () => {
  12257. this.rotateAngle2 = -9
  12258. })
  12259. }
  12260. }
  12261. // 回调,暂停和播放按钮回调,下一首和上一首
  12262. playChange() {
  12263. // if(this.isCoverRectangle){
  12264. // return
  12265. // }
  12266. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  12267. this.setIsPlaying(true)
  12268. this.animationState = AnimationStatus.Running
  12269. } else {
  12270. this.setIsPlaying(false)
  12271. this.animationState = AnimationStatus.Paused
  12272. }
  12273. AppStorage.setOrCreate('animationState', this.animationState);
  12274. }
  12275. // 定义停止旋转的方法
  12276. stopRotation() {
  12277. if (this.isCoverRectangle) {
  12278. this.rotateAngle = 0
  12279. } else {
  12280. //唱针以左上角为点选择逆时针40度
  12281. animateTo({
  12282. duration: 1000,
  12283. curve: Curve.Linear,
  12284. iterations: 1,
  12285. }, () => {
  12286. this.rotateAngle2 = -45;
  12287. });
  12288. }
  12289. }
  12290. @Builder
  12291. private LyricsTopItem() {
  12292. Row() {
  12293. Stack({ alignContent: Alignment.Center }) {
  12294. Image( StrUtil.isNotEmpty(this.cover)?
  12295. this.cover:$r('app.media.alt'))
  12296. .height(58)
  12297. .width(58)
  12298. .clip(true)
  12299. .sourceSize({width:38, height:38})
  12300. .alt($r('app.media.alt'))
  12301. .borderRadius(8)
  12302. .clickEffect({ level: ClickEffectLevel.HEAVY })
  12303. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  12304. .shadow({
  12305. radius: 22,
  12306. type: ShadowType.BLUR,
  12307. color: 'on_primary'
  12308. })
  12309. }
  12310. .width(62)
  12311. .height('100%')
  12312. Column() {
  12313. Column() {
  12314. Text(this.name)
  12315. .fontSize(16)
  12316. .maxLines(1)
  12317. .fontWeight(FontWeight.Bolder)
  12318. .fontColor(Color.White)
  12319. .textOverflow({ overflow: TextOverflow.Ellipsis })
  12320. .margin({ left: 10 })
  12321. Row() {
  12322. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  12323. .fontSize(13)
  12324. .fontWeight(FontWeight.Bolder)
  12325. .padding({ top: 8 })
  12326. .fontColor(Color.White)
  12327. .margin({ left: 10 })
  12328. Blank()
  12329. }
  12330. }
  12331. .height('100%')
  12332. .width('100%')
  12333. .justifyContent(FlexAlign.Center)
  12334. .alignItems(HorizontalAlign.Start)
  12335. }
  12336. .height('100%')
  12337. .layoutWeight(1)
  12338. .margin({ right: 8 })
  12339. Column() {
  12340. PointLightDefaultButton({
  12341. isSysBol:false,
  12342. pointColor:Color.White,
  12343. imageResource:$r('app.media.lyric'),
  12344. isPx: false,
  12345. builderHeight: 23,
  12346. builderWidth: 23,
  12347. })
  12348. .onClick(() => {
  12349. this.isLyricSetting = !this.isLyricSetting;
  12350. })
  12351. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  12352. height: '99%',
  12353. dragBar: true,
  12354. preferType: SheetType.CENTER,
  12355. showClose: true,
  12356. blurStyle: BlurStyle.Thin,
  12357. backgroundColor: Color.Transparent,
  12358. title: { title: $r('app.string.lyric_setting') }
  12359. })
  12360. }
  12361. .width(44)
  12362. .height('100%')
  12363. .justifyContent(FlexAlign.Center)
  12364. .alignItems(HorizontalAlign.End)
  12365. }
  12366. .width(this.currentLyricAlignModePip === 1?'98%':'90%%')
  12367. .padding({ left: 28, right: 28 })
  12368. .height(58)
  12369. .alignItems(VerticalAlign.Center)
  12370. }
  12371. //歌词显示
  12372. @Builder
  12373. PlayerLyrics() {
  12374. Column() {
  12375. Column() {
  12376. this.LyricsTopItem()
  12377. }
  12378. .height(this.isPuraWP() ? 15 : 58)
  12379. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  12380. Visibility.None : Visibility.Visible)
  12381. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  12382. .width("100%")
  12383. Column() {
  12384. LyricView2({
  12385. controller: this.lyricController,
  12386. enableSeek: true,
  12387. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  12388. seekLineColor: "#80ffffff", // 滑动定位线颜色
  12389. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  12390. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  12391. if (!this.isPlaying) {
  12392. console.info('onecold startPlayOrResumePlay 7527')
  12393. this.startPlayOrResumePlay()
  12394. }
  12395. else {
  12396. this.isSeekTo = true;
  12397. this.mDestroyPage = false;
  12398. // 只有播放网盘歌曲时才显示转圈圈
  12399. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  12400. this.showLoadIng();
  12401. }
  12402. this.seekTo(position + "");
  12403. }
  12404. return true
  12405. }
  12406. })
  12407. .width("100%")
  12408. .layoutWeight(1)
  12409. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  12410. .gesture(LongPressGesture()
  12411. .onAction(() => {
  12412. this.openLyricCopySheet();
  12413. }))
  12414. .bindSheet($$this.isShowLyricCopySheet, this.LyricCopySheetBuilder(), {
  12415. height: '99%',
  12416. dragBar: true,
  12417. showClose: true,
  12418. preferType: SheetType.CENTER,
  12419. blurStyle: BlurStyle.Thin,
  12420. title: { title: '歌词' }
  12421. })
  12422. if (this.isPhoneLan()) {
  12423. Column() {
  12424. if (this.isShowSpectrum) {
  12425. this.InlineSpectrumView()
  12426. }
  12427. this.playProgressView()
  12428. }
  12429. .margin({ bottom: 32, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  12430. }
  12431. }
  12432. .position({
  12433. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  12434. (this.isPuraWP() ? 58 : 99)
  12435. })
  12436. .justifyContent(FlexAlign.Center)
  12437. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  12438. }
  12439. }
  12440. @Builder
  12441. LyricCopySheetBuilder() {
  12442. LyricCopySheet({
  12443. lyricCopyLines: this.lyricCopyLines,
  12444. lyricSelectedIndexes: this.lyricSelectedIndexes,
  12445. isDarkMode: this.isDarkMode,
  12446. themeColor: this.themeColor,
  12447. bottomSafeHeight: this.bottomSafeHeight,
  12448. onToggleLyricLine: (index: number) => {
  12449. this.toggleLyricLineSelection(index);
  12450. },
  12451. onToggleSelectAll: () => {
  12452. this.toggleLyricSelectAll();
  12453. },
  12454. onCopySelectedLines: () => {
  12455. this.copySelectedLyricLines();
  12456. },
  12457. onShareSelectedLines: () => {
  12458. this.shareSelectedLyricLines();
  12459. }
  12460. })
  12461. }
  12462. @Builder
  12463. SingleLyricView() {
  12464. Column() {
  12465. Column() {
  12466. LyricView2({
  12467. controller: this.lyricControllerSingle,
  12468. enableSeek: false,
  12469. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  12470. seekLineColor: "#80ffffff", // 滑动定位线颜色
  12471. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  12472. })
  12473. .gesture(LongPressGesture()
  12474. .onAction(() => {
  12475. this.openLyricCopySheet();
  12476. }))
  12477. }
  12478. .height(82)
  12479. .margin({ bottom: 20 })
  12480. }
  12481. .opacity(this.playDragUiOpacity)
  12482. }
  12483. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  12484. @Builder
  12485. BottomControl() {
  12486. Column() {
  12487. if (this.isShowSpectrum) {
  12488. this.InlineSpectrumView()
  12489. }
  12490. this.TopPlayProgressView()
  12491. //播放 暂停,下一首,上一首
  12492. this.playCenterView()
  12493. if(!this.curDisplayIsHiCar){
  12494. //播放进度条
  12495. this.BottomView()
  12496. }
  12497. }
  12498. .justifyContent(FlexAlign.Center)
  12499. .alignItems(HorizontalAlign.Center)
  12500. .opacity(this.playDragUiOpacity)
  12501. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  12502. }
  12503. @Builder
  12504. playMenuBuilder(){
  12505. Image($r('app.media.menu'))
  12506. .width(24)
  12507. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12508. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  12509. height: '99%',
  12510. preferType:SheetType.CENTER,
  12511. dragBar: true,
  12512. showClose: true,
  12513. blurStyle: BlurStyle.Thin,
  12514. title: { title: $r('app.string.more') },
  12515. backgroundColor: Color.Transparent,
  12516. })
  12517. }
  12518. //播放控制上一首 下一首 暂停和播放
  12519. @Builder
  12520. playCenterView(){
  12521. Row() {
  12522. PointLightButton({
  12523. builder: () => {
  12524. this.playMenuBuilder()
  12525. },
  12526. isPx: false,
  12527. builderHeight: 26,
  12528. builderWidth: 26,
  12529. })
  12530. .onClick(async () =>{
  12531. this.isShowMoreView = !this.isShowMoreView;
  12532. })
  12533. PointLightButton({
  12534. builder: () => {
  12535. this.playPreviousBuilder()
  12536. },
  12537. isPx: false,
  12538. builderHeight: 26,
  12539. builderWidth: 26,
  12540. })
  12541. .onClick(async () =>{
  12542. await this.playPrevious()
  12543. })
  12544. PointLightButton({
  12545. builder: () => {
  12546. this.PlayOrPauseButton()
  12547. },
  12548. isPx: false,
  12549. builderHeight: this.isPhoneLan()?38:41,
  12550. builderWidth: this.isPhoneLan()?38:41,
  12551. })
  12552. .onClick(() =>{
  12553. this.playOrPause()
  12554. })
  12555. PointLightButton({
  12556. builder: () => {
  12557. this.playNextBuilder()
  12558. },
  12559. isPx: false,
  12560. builderHeight: 26,
  12561. builderWidth: 26,
  12562. })
  12563. .onClick(async () =>{
  12564. await this.playNext()
  12565. })
  12566. this.playModeButton()
  12567. }
  12568. .width('95%')
  12569. .margin({ bottom:this.isCoverOpacity()?0:15 })
  12570. .justifyContent(FlexAlign.SpaceEvenly)
  12571. }
  12572. @Builder
  12573. playPreviousBuilder(){
  12574. Image($r('app.media.ic_previous'))
  12575. .width(32)
  12576. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12577. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12578. }
  12579. @Builder
  12580. playNextBuilder(){
  12581. Image($r('app.media.ic_next'))
  12582. .width(32)
  12583. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12584. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12585. }
  12586. @Builder
  12587. PlayOrPauseButton(){
  12588. Stack() {
  12589. Column() {
  12590. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  12591. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  12592. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  12593. .width(this.isPhoneLan()?38:40)
  12594. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12595. .fillColor(Color.White)
  12596. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12597. }
  12598. // 加载进度圈
  12599. if (this.isPlayerLoading) {
  12600. Progress({value:0,total:100,type:ProgressType.Ring })
  12601. .width(this.isPhoneLan()?40:43)
  12602. .height(this.isPhoneLan()?40:43)
  12603. .color(Color.White)
  12604. .style({ strokeWidth: 5, status: ProgressStatus.LOADING })
  12605. }
  12606. }
  12607. .width(this.isPhoneLan()?38:41)
  12608. .height(this.isPhoneLan()?38:41)
  12609. }
  12610. @Builder
  12611. TopPlayProgressView(){
  12612. Column() {
  12613. Row(){
  12614. Stack(){
  12615. SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
  12616. .fontColor([Color.White])
  12617. .fontSize(21)
  12618. .effectStrategy(1)
  12619. Text(this.fastForwardSeconds)
  12620. .fontColor(Color.White)
  12621. .fontSize(10)
  12622. .fontWeight(FontWeight.Bold)
  12623. }
  12624. .padding({left:12,bottom:6})
  12625. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  12626. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  12627. .onClick(()=>{
  12628. this.backForward()
  12629. })
  12630. Slider({
  12631. value: this.progressValue,
  12632. min: 0,
  12633. max: this.PROGRESS_MAX_VALUE,
  12634. step: 1,
  12635. style: SliderStyle.InSet
  12636. })
  12637. .height(20)
  12638. .blockColor('rgba(255,255,255,1)')
  12639. .trackColor('rgba(255,255,255,0.3)')
  12640. .selectedColor(Color.White)
  12641. .trackThickness(4)
  12642. .showSteps(false)
  12643. .showTips(true)
  12644. .layoutWeight(1)
  12645. .enabled(this.slideEnable)
  12646. .onChange((value: number, mode: SliderChangeMode) => {
  12647. if (mode !== 2) {
  12648. return
  12649. }
  12650. if(this.isSeekTo)
  12651. return
  12652. this.isSeekTo = true;
  12653. this.mDestroyPage = false;
  12654. // 只有播放网盘歌曲时才显示转圈圈
  12655. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  12656. this.showLoadIng();
  12657. }
  12658. let seekValue = value * (this.getActiveDuration() / 100);
  12659. this.seekTo(seekValue + "", "top-progress-slider");
  12660. })
  12661. Stack(){
  12662. SymbolGlyph($r('sys.symbol.arrow_clockwise'))
  12663. .fontColor([Color.White])
  12664. .fontSize(21)
  12665. .effectStrategy(1)
  12666. Text(this.fastForwardSeconds)
  12667. .fontColor(Color.White)
  12668. .fontSize(10)
  12669. .fontWeight(FontWeight.Bold)
  12670. }
  12671. .padding({right:10,bottom:6})
  12672. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  12673. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  12674. .onClick(()=>{
  12675. this.fastForward()
  12676. })
  12677. }
  12678. .justifyContent(FlexAlign.Center)
  12679. .padding({left:20,right:20})
  12680. .width(this.isLandscape?'88%':'95%')
  12681. Row() {
  12682. Text(this.currentTime)
  12683. .fontSize(10)
  12684. .fontColor(Color.White)
  12685. .margin({left:25})
  12686. Blank()
  12687. Text(this.totalTime)
  12688. .fontSize(10)
  12689. .fontColor(Color.White)
  12690. .margin({right:25})
  12691. }
  12692. .width(this.isLandscape?'85%':'90%')
  12693. .height(10)
  12694. }
  12695. .width('100%')
  12696. .alignItems(HorizontalAlign.Center)
  12697. }
  12698. @Builder
  12699. playModeButton(){
  12700. PointLightButton({
  12701. builder: () => {
  12702. this.playModeBuilder()
  12703. },
  12704. isPx: false,
  12705. builderHeight: 26,
  12706. builderWidth: 26,
  12707. })
  12708. .onClick(async () =>{
  12709. this.setLoopMode()
  12710. })
  12711. }
  12712. @Builder
  12713. playModeBuilder(){
  12714. Column() {
  12715. if (this.playType === 0) {
  12716. Image($r('app.media.loop'))
  12717. .width(24)
  12718. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12719. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12720. } else if (this.playType === 1) {
  12721. Image($r('app.media.single'))
  12722. .width(24)
  12723. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12724. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12725. } else if (this.playType === 2) {
  12726. Image($r('app.media.normal_play'))
  12727. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12728. .width(24)
  12729. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12730. } else if (this.playType === 3) {
  12731. Image($r('app.media.random'))
  12732. .width(24)
  12733. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12734. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12735. } else if (this.playType === 4) {
  12736. Image($r('app.media.noloop'))
  12737. .width(24)
  12738. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12739. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12740. }
  12741. }
  12742. }
  12743. //播放进度条
  12744. @Builder
  12745. BottomView(){
  12746. Row() {
  12747. PointLightDefaultButton({
  12748. isSysBol:true,
  12749. pointColor:Color.White,
  12750. imageResource:$r('sys.symbol.rectangle_portrait_rotate'),
  12751. isPx: false,
  12752. builderHeight: 22,
  12753. builderWidth: 22,
  12754. })
  12755. .onClick(async () =>{
  12756. if (this.isLandscape) {
  12757. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  12758. } else {
  12759. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  12760. }
  12761. })
  12762. if(this.currentSong){
  12763. PointLightDefaultButton({
  12764. isSysBol:true,
  12765. pointColor:Color.White,
  12766. imageResource:$r('sys.symbol.rename'),
  12767. isPx: false,
  12768. builderHeight: 22,
  12769. builderWidth: 22,
  12770. })
  12771. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  12772. height: '99%',
  12773. dragBar: true,
  12774. showClose: true,
  12775. preferType: SheetType.BOTTOM,
  12776. title: { title: '编辑标签' }
  12777. })
  12778. .onClick(async () => {
  12779. this.initEditFields(this.currentSong)
  12780. this.tempLyricContent = this.lyricContent
  12781. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  12782. this.lyricConStr = this.tempLyricContent
  12783. }
  12784. this.isShowEdit = !this.isShowEdit;
  12785. })
  12786. }
  12787. PointLightDefaultButton({
  12788. isSysBol:true,
  12789. pointColor:Color.White,
  12790. imageResource:$r('sys.symbol.slider_vertical_3'),
  12791. isPx: false,
  12792. builderHeight: 22,
  12793. builderWidth: 22,
  12794. })
  12795. .onClick(async () => {
  12796. this.isEqualizerSheet = !this.isEqualizerSheet;
  12797. })
  12798. PointLightDefaultButton({
  12799. isSysBol:true,
  12800. pointColor:Color.White,
  12801. imageResource:Utility.getIsFav(this.favList,this.currentSong)?
  12802. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'),
  12803. isPx: false,
  12804. builderHeight: 22,
  12805. builderWidth: 22,
  12806. })
  12807. .onClick(async () => {
  12808. if(this.currentSong){
  12809. this.doFav(this.currentSong)
  12810. }
  12811. })
  12812. this.playListBuilder()
  12813. }
  12814. .width(this.isLandscape?'88%':'95%')
  12815. .justifyContent(FlexAlign.SpaceAround)
  12816. .visibility(this.showSimple?Visibility.None:Visibility.Visible)
  12817. .height(30)
  12818. .animation({
  12819. duration: 666,
  12820. curve: 'ease-in-out' // 可选动画曲线
  12821. })
  12822. }
  12823. @Builder
  12824. fullButton(){
  12825. Column() {
  12826. Image($r('app.media.full_4'))
  12827. .width(25)
  12828. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12829. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12830. }
  12831. }
  12832. @Builder
  12833. playListBuilder(){
  12834. PointLightDefaultButton({
  12835. isSysBol:true,
  12836. pointColor:Color.White,
  12837. imageResource:$r('sys.symbol.music_note_list'),
  12838. isPx: false,
  12839. builderHeight: 26,
  12840. builderWidth: 26,
  12841. })
  12842. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  12843. height: '95%',
  12844. dragBar: true,
  12845. showClose: true,
  12846. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  12847. blurStyle: BlurStyle.Thin,
  12848. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  12849. title: {
  12850. title:this.getPlayListDisplayCount()==0?Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  12851. :Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  12852. + `(${this.getPlayListDisplayCount()}首)`
  12853. }
  12854. })
  12855. .onClick(() => {
  12856. this.isShowSheetView = !this.isShowSheetView;
  12857. if(this.isPlayListBgGrass){
  12858. this.isFrontWhite = true
  12859. }else{
  12860. this.isFrontWhite = false
  12861. }
  12862. this.scrollIndex()
  12863. // 只有在播放本地音乐时才自动加载完整列表
  12864. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_LOCAL) {
  12865. void this.hydrateFullMediaPlayListIfNeeded();
  12866. }
  12867. })
  12868. }
  12869. //旧版本播放进度条(现在是手机横屏的播放条)
  12870. @Builder
  12871. playProgressView() {
  12872. Row() {
  12873. Column(){
  12874. PointLightDefaultButton({
  12875. isSysBol:true,
  12876. pointColor:Color.White,
  12877. imageResource:$r('sys.symbol.rectangle_portrait_rotate'),
  12878. isPx: false,
  12879. builderHeight: 26,
  12880. builderWidth: 26,
  12881. })
  12882. .onClick(async () =>{
  12883. if (this.isLandscape) {
  12884. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  12885. } else {
  12886. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  12887. }
  12888. })
  12889. }
  12890. .margin({ right: 10,bottom:6})
  12891. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  12892. .animation({
  12893. duration: 666,
  12894. curve: 'ease-in-out' // 可选动画曲线
  12895. })
  12896. Text(this.currentTime)
  12897. .fontSize($r('app.float.slider_font_size'))
  12898. .fontColor(Color.White)
  12899. .margin(3)
  12900. Slider({
  12901. value: this.progressValue,
  12902. min: 0,
  12903. max: this.PROGRESS_MAX_VALUE,
  12904. step: 1,
  12905. style: SliderStyle.InSet
  12906. })
  12907. .width('600px')
  12908. .blockColor('rgba(255,255,255,1)')
  12909. .trackColor('rgba(255,255,255,0.3)')
  12910. .selectedColor(Color.White)
  12911. .trackThickness(5)
  12912. .layoutWeight(1)
  12913. .margin({top:4, left: PlayConstants.PROGRESS_MARGIN_LEFT })
  12914. .showSteps(false)
  12915. .showTips(true)
  12916. .enabled(this.slideEnable)
  12917. .onChange((value: number, mode: SliderChangeMode) => {
  12918. if (mode !== 2) {
  12919. return
  12920. }
  12921. this.isSeekTo = true;
  12922. this.mDestroyPage = false;
  12923. // 只有播放网盘歌曲时才显示转圈圈
  12924. console.info("onecold this.currentSong.type:"+this.currentSong?.type)
  12925. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  12926. this.showLoadIng();
  12927. }
  12928. let seekValue = value * (this.getActiveDuration() / 100);
  12929. this.seekTo(seekValue + "", "landscape-progress-slider");
  12930. })
  12931. Text(this.totalTime)
  12932. .fontSize($r('app.float.slider_font_size'))
  12933. .fontColor(Color.White)
  12934. .margin(3)
  12935. //播放列表
  12936. Column(){
  12937. this.playListBuilder()
  12938. }
  12939. .margin({ left: 10,bottom:6})
  12940. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  12941. .animation({
  12942. duration: 666,
  12943. curve: 'ease-in-out' // 可选动画曲线
  12944. })
  12945. }
  12946. //x5的竖屏模式需要99%
  12947. .width(this.isPhonePortrait() ? '93.4%'
  12948. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  12949. .height(this.isPhoneLan() ? 25 : 33)
  12950. .alignItems(VerticalAlign.Bottom)
  12951. .animation({
  12952. duration: 666,
  12953. curve: 'ease-in-out' // 可选动画曲线
  12954. })
  12955. }
  12956. isBigScreen() {
  12957. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  12958. return true
  12959. }
  12960. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  12961. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  12962. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  12963. return false
  12964. } else {
  12965. return true
  12966. }
  12967. return false
  12968. }
  12969. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  12970. // 添加控制缩放的状态变量
  12971. @State scaleValueImage: number = 1
  12972. @State scaleValueText: number = 1
  12973. @State playDragUiOpacity: number = 1
  12974. @Builder
  12975. private CoverScaleGuideOverlay() {
  12976. Stack() {
  12977. Column({ space: 10 }) {
  12978. SymbolGlyph($r('sys.symbol.arrow_up_left_and_arrow_down_right'))
  12979. .fontSize(34)
  12980. .fontColor([Color.White])
  12981. Text('双指缩放封面')
  12982. .fontSize(16)
  12983. .fontWeight(FontWeight.Bold)
  12984. .fontColor(Color.White)
  12985. Text('在封面区域双指捏合,可调整封面大小')
  12986. .fontSize(12)
  12987. .fontColor(Color.White)
  12988. .opacity(0.88)
  12989. .textAlign(TextAlign.Center)
  12990. }
  12991. .padding({ left: 18, right: 18, top: 16, bottom: 16 })
  12992. .backgroundColor('#A6000000')
  12993. .borderRadius(18)
  12994. .width(this.isPhoneLan() ? 230 : 240)
  12995. }
  12996. .width('100%')
  12997. .height(this.isPhoneLan() ? 260 : 360)
  12998. .align(Alignment.Center)
  12999. .zIndex(10)
  13000. .visibility(this.isShowCoverScaleGuide ? Visibility.Visible : Visibility.None)
  13001. .onClick(() => {
  13002. this.dismissCoverScaleGuide()
  13003. })
  13004. }
  13005. @Builder
  13006. CoverInfo() {
  13007. Column() {
  13008. Stack() {
  13009. Column() {
  13010. //方形封面布局
  13011. if (this.isCoverRectangle) {
  13012. this.RectangleCoverView()
  13013. } else {
  13014. //圆形封面布局
  13015. this.CicleCoverView()
  13016. }
  13017. this.musicNameInfo(false)
  13018. if (this.isPhoneLan()) {
  13019. Text(this.name+"--"+this.artist)
  13020. .fontSize(18)
  13021. .fontWeight(FontWeight.Bold)
  13022. .margin({ top: 13 })
  13023. .textOverflow({ overflow: TextOverflow.Ellipsis })
  13024. .maxLines(1)
  13025. .width('99%')
  13026. .textAlign(TextAlign.Center)
  13027. .fontColor(Color.White)
  13028. }
  13029. }
  13030. .width('100%')
  13031. Column({ space: 8 }) {
  13032. Text(this.name)
  13033. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  13034. .fontWeight(FontWeight.Bold)
  13035. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  13036. .maxLines(1)
  13037. .width('85%')
  13038. .textAlign(TextAlign.Center)
  13039. .fontColor(Color.White)
  13040. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  13041. Text(this.artist)
  13042. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  13043. .fontColor(Color.White)
  13044. .fontWeight(FontWeight.Bold)
  13045. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  13046. }
  13047. .justifyContent(FlexAlign.Start)
  13048. .zIndex(1)
  13049. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  13050. this.CoverScaleGuideOverlay()
  13051. }
  13052. .margin({
  13053. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  13054. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  13055. top: this.isCoverOpacity() ? 0 : 20
  13056. })
  13057. if (this.isShowSingleLineLyric&&this.isPhonePortrait()) {
  13058. this.SingleLyricView()
  13059. }
  13060. if (this.isPhoneLan()) {
  13061. Column() {
  13062. this.playCenterView()
  13063. }
  13064. .position({ left: 28, bottom: 35 })
  13065. } else {
  13066. this.BottomControl()
  13067. }
  13068. }
  13069. .width(CommonConstants.FULL_PERCENT)
  13070. .clip(true)
  13071. }
  13072. //方形封面布局
  13073. @Builder
  13074. RectangleCoverView(){
  13075. Stack({alignContent:Alignment.Center}){
  13076. Image( StrUtil.isNotEmpty(this.cover)?
  13077. this.cover:$r('app.media.alt'))
  13078. .height(this.getRectangleCoverHeight())
  13079. .width(this.getRectangleCoverWidth())
  13080. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  13081. .alt($r('app.media.alt'))
  13082. .margin({ right: 8, left: 8, top: 5 })
  13083. .aspectRatio(1)
  13084. .opacity(this.opacityValueImage)
  13085. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  13086. .bindContextMenu(this.MenuImageBuilder(this.cover), ResponseType.LongPress,
  13087. {
  13088. preview: MenuPreviewMode.IMAGE,
  13089. previewAnimationOptions: { scale: [0.8, 1.0] },
  13090. })
  13091. .bindContextMenu(this.MenuImageBuilder(this.cover), ResponseType.RightClick,
  13092. {
  13093. preview: MenuPreviewMode.IMAGE,
  13094. previewAnimationOptions: { scale: [0.8, 1.0] },
  13095. })
  13096. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  13097. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  13098. .clip(true)
  13099. .animation({
  13100. duration: 1000, // 与 setInterval 同步
  13101. curve: Curve.Linear,
  13102. iterations: 1
  13103. })
  13104. .shadow({
  13105. radius: 22,
  13106. type: ShadowType.BLUR,
  13107. color: 'on_primary'
  13108. })
  13109. .onClick(() => {
  13110. this.isMusicBGCover = !this.isMusicBGCover
  13111. })
  13112. .gesture(PinchGesture({ fingers: 2 })
  13113. .onActionUpdate((event: GestureEvent) => {
  13114. this.updateRectangleCoverScaleByPinch(event.scale)
  13115. })
  13116. .onActionEnd(() => {
  13117. this.rectangleCoverPinchValue = this.rectangleCoverScale
  13118. PreferencesUtil.put(SettingPage.RECTANGLE_COVER_SCALE, this.rectangleCoverScale)
  13119. }))
  13120. }
  13121. .scale({ x: this.scaleValueImage, y: this.scaleValueImage})
  13122. }
  13123. private getRectangleCoverWidth(): string | number {
  13124. if (this.isHiCar() || this.isCoverOpacity()) {
  13125. return 'auto'
  13126. }
  13127. const baseWidth = this.isBigScreen() ? 72 : this.isCoverTopBig ? 100 : 88
  13128. return `${Math.min(100, Math.max(48, baseWidth * this.rectangleCoverScale))}%`
  13129. }
  13130. private getRectangleCoverHeight(): string | number {
  13131. if (this.isHiCar()) {
  13132. return px2vp(this.windowHeight) * 0.4 * this.rectangleCoverScale
  13133. }
  13134. if (this.isCoverOpacity()) {
  13135. return px2vp(this.windowHeight) * 0.54 * this.rectangleCoverScale
  13136. }
  13137. return 'auto'
  13138. }
  13139. private updateCoverScaleByPinch(scale: number): void {
  13140. this.rectangleCoverScale = Math.min(1.4, Math.max(0.7, this.rectangleCoverPinchValue * scale))
  13141. }
  13142. private updateRectangleCoverScaleByPinch(scale: number): void {
  13143. const dampedScale = 1 + (scale - 1) * 0.45
  13144. this.rectangleCoverScale = Math.min(1.4, Math.max(0.7, this.rectangleCoverPinchValue * dampedScale))
  13145. }
  13146. private persistCoverScaleAfterPinch(): void {
  13147. this.rectangleCoverPinchValue = this.rectangleCoverScale
  13148. PreferencesUtil.put(SettingPage.RECTANGLE_COVER_SCALE, this.rectangleCoverScale)
  13149. }
  13150. @Builder
  13151. CicleCoverView() {
  13152. //圆形封面布局
  13153. Stack({alignContent:Alignment.Center}) {
  13154. Image($r('app.media.ic_music_disc'))
  13155. .width(245)
  13156. .height(245)
  13157. .margin({ right: 20, left: 20 ,top:this.isLandscape?0:50 })
  13158. .aspectRatio(1)
  13159. .opacity(this.isCoverOpacity() ? 0 : 1)
  13160. .visibility(this.isCoverOpacity() ? Visibility.None : Visibility.Visible)
  13161. .borderRadius('100%')
  13162. .align(Alignment.Center)
  13163. .clip(true)
  13164. .rotate({
  13165. angle: this.rotateAngle,
  13166. centerX: "50%",
  13167. centerY: "50%",
  13168. })
  13169. .animation({
  13170. duration: 1000, // 改为 1000ms 与 setInterval 同步
  13171. curve: Curve.Linear,
  13172. iterations: 1 // 只执行一次,下一次更新会触发新的动画
  13173. })
  13174. .shadow({
  13175. radius: 22,
  13176. type: ShadowType.BLUR,
  13177. color: 'on_primary'
  13178. })
  13179. Image( StrUtil.isNotEmpty(this.cover)?
  13180. this.cover:$r('app.media.alt'))
  13181. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
  13182. (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 168))
  13183. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  13184. .alt($r('app.media.alt'))
  13185. .margin({ right: 20, left: 20,
  13186. top:this.isCoverRectangle||this.isLandscape?0:50})
  13187. .aspectRatio(1)
  13188. .opacity(this.opacityValueImage)
  13189. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  13190. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  13191. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  13192. .align(Alignment.Center)//
  13193. .clip(true)
  13194. .shadow({
  13195. radius: 22,
  13196. type: ShadowType.BLUR,
  13197. color: 'on_primary'
  13198. })
  13199. .rotate({
  13200. x: 0,
  13201. y: 0,
  13202. z: 1,
  13203. angle: this.rotateAngle
  13204. })
  13205. .animation({
  13206. duration: 1000, // 与 setInterval 同步
  13207. curve: Curve.Linear,
  13208. iterations: 1
  13209. })
  13210. .onClick(() => {
  13211. this.isMusicBGCover = !this.isMusicBGCover
  13212. })
  13213. // 唱针以左上角为点选择逆时针40度
  13214. Image($r('app.media.ic_music_cover_hand'))
  13215. .height(130)
  13216. .margin({ bottom: 200, top: 0 })
  13217. // .position({ x: this.windowWidth/2, y: 0 })
  13218. .align(Alignment.Top)
  13219. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  13220. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  13221. .visibility(this.isHiCar()||this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  13222. }
  13223. .scale({ x: this.scaleValueImage * this.rectangleCoverScale, y: this.scaleValueImage * this.rectangleCoverScale,
  13224. centerX: '50%',
  13225. centerY: '50%' })
  13226. .priorityGesture(PinchGesture({ fingers: 2 })
  13227. .onActionStart(() => {
  13228. this.rectangleCoverPinchValue = this.rectangleCoverScale
  13229. })
  13230. .onActionUpdate((event: GestureEvent) => {
  13231. this.updateCoverScaleByPinch(event.scale)
  13232. })
  13233. .onActionEnd(() => {
  13234. this.persistCoverScaleAfterPinch()
  13235. }))
  13236. }
  13237. @Builder
  13238. MenuImageBuilder(cover: string|undefined) {
  13239. Menu(){
  13240. MenuItem({
  13241. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.picture_2')),
  13242. content: '查看封面'
  13243. })
  13244. .onClick(async() => {
  13245. if (StrUtil.isEmpty(cover)) {
  13246. ToastUtil.showToast('当前没有可用封面')
  13247. return;
  13248. }
  13249. this.getUIContext().getRouter().pushUrl({
  13250. url: 'pages/WallpaperPreviewPage',
  13251. params: {
  13252. imageUri: cover
  13253. }
  13254. })
  13255. })
  13256. MenuItem({
  13257. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.picture')),
  13258. content: '更换封面'
  13259. })
  13260. .onClick(async() => {
  13261. await this.replaceCurrentSongCoverByAlbum();
  13262. })
  13263. }
  13264. }
  13265. @Builder
  13266. private musicNameInfo(isHidden: boolean) {
  13267. Row(){
  13268. Column({ space: 8 }) {
  13269. Text(this.name)
  13270. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 20)
  13271. .fontWeight(FontWeight.Bold)
  13272. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  13273. .maxLines(1)
  13274. .width('99%')
  13275. .textAlign(TextAlign.Start)
  13276. .fontColor(Color.White)
  13277. Text(this.artist + ' ' + this.currentSong?.album)
  13278. .fontSize(this.isCoverOpacity() ? 12 : 15)
  13279. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  13280. .fontColor(Color.White)
  13281. .textAlign(TextAlign.Start)
  13282. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  13283. .width('99%')
  13284. .maxLines(1)
  13285. }
  13286. .zIndex(1)
  13287. .layoutWeight(1)
  13288. .margin({ left: 15 })
  13289. Blank()
  13290. Row(){
  13291. PointLightDefaultButton({
  13292. isSysBol:true,
  13293. pointColor:Color.White,
  13294. imageResource:this.showSimple?
  13295. $r('sys.symbol.sun_max'):$r('sys.symbol.moon'),
  13296. isPx: false,
  13297. builderHeight: 26,
  13298. builderWidth: 26,
  13299. })
  13300. .onClick(async () => {
  13301. this.showSimple = !this.showSimple
  13302. PreferencesUtil.put('showSimple', this.showSimple)
  13303. })
  13304. }
  13305. .margin({ left: 8,right:8 })
  13306. }
  13307. .width(this.isLandscape?'83%':'90%')
  13308. .scale({ x: this.scaleValueText, y: this.scaleValueText }) // 添加缩放效果
  13309. .opacity(this.playDragUiOpacity)
  13310. .margin({ top:this.isCoverRectangle?10: 0 })
  13311. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  13312. }
  13313. @Builder
  13314. private PlayTitle() {
  13315. Row() {
  13316. Row() {
  13317. PointLightDefaultButton({
  13318. isSysBol: true,
  13319. pointColor: Color.White,
  13320. imageResource: $r('sys.symbol.chevron_down'),
  13321. isPx: false,
  13322. builderHeight: 26,
  13323. builderWidth: 26,
  13324. })
  13325. .onClick(() => {
  13326. this.setShowPlayFalse()
  13327. })
  13328. }
  13329. .width('100%')
  13330. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  13331. }
  13332. .width(PlayConstants.ROW_WIDTH)
  13333. }
  13334. @Builder
  13335. lyricSettingSheet(isPip: boolean) {
  13336. Scroll() {
  13337. this.lyricSetting(isPip)
  13338. }
  13339. .width('100%')
  13340. .height('100%')
  13341. }
  13342. @Builder
  13343. lyricSetting(isPip: boolean) {
  13344. Column() {
  13345. // 时间调节模块
  13346. if (!isPip) {
  13347. this.BuildTimeControls()
  13348. }
  13349. // 字号控制模块
  13350. this.BuildFontControls(isPip)
  13351. }
  13352. }
  13353. // 歌词时间偏移状态
  13354. @State timeOffset: number = 0.0
  13355. @State currentLyricColor: string = '#FFFFFF'
  13356. @State currentLyricColorPip: string = '#FFFFFF'
  13357. @State currentHighLightLyricColor: string = '#FF4081'
  13358. @State currentHighLightLyricColorPip: string = '#FF4081'
  13359. // 歌词字号状态
  13360. @State currentLyricSize: number = 20
  13361. @State currentLyricSizePip: number = 20
  13362. // 高亮歌词放大倍数
  13363. @State currentHightLyricSize: number = 1.2
  13364. @State currentHightLyricSizePip: number = 1.2
  13365. @State currentLyricLineSpace: number = 10
  13366. @State currentLyricLineSpacePip: number = 10
  13367. @State currentLyricAlignMode: number = 1
  13368. @State currentLyricAlignModePip: number = 1
  13369. @State blurDegree: number = 2
  13370. @State blurDegreePip: number = 2
  13371. @State isShowSelectColor: boolean = false
  13372. @State isShowHLSelectColor: boolean = false
  13373. @State isShowPipBgSelectColor: boolean = false
  13374. @State pipLyWidth: number = 330
  13375. @State pipLyHeight: number = 120
  13376. // 构建颜色选择器
  13377. @Builder
  13378. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  13379. Row({ space: 10 }) {
  13380. HSBColorPicker({
  13381. color: '#FFFFFF',
  13382. radius: 8,
  13383. layout: HSBColorPickerLayout.COLUMN,
  13384. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  13385. '#fa7105'],
  13386. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  13387. this.changeLyricColor(value, isPip, isBGPip)
  13388. })
  13389. .height(250)
  13390. .layoutWeight(1)
  13391. .padding(25)
  13392. }
  13393. .width('66%')
  13394. }
  13395. @State isOpenPip: boolean = false
  13396. @State pipBgIndex: number = 0
  13397. // 构建字号控制器
  13398. @Builder
  13399. BuildFontControls(isPip: boolean) {
  13400. Column() {
  13401. if (isPip) {
  13402. Column() {
  13403. Row() {
  13404. Text('悬浮歌词')
  13405. .margin({ left: 18 })
  13406. .fontSize(15)
  13407. .fontColor(Color.White)
  13408. .fontWeight(480)
  13409. .layoutWeight(1)
  13410. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  13411. .selectedColor(this.themeColor)
  13412. .switchPointColor(Color.White)
  13413. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13414. .margin({ right: 18 })
  13415. .onChange((checked: boolean) => {
  13416. this.isOpenPip = checked;
  13417. if (this.isOpenPip) {
  13418. this.startPip()
  13419. } else {
  13420. this.stopPip()
  13421. }
  13422. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  13423. })
  13424. .width(50)
  13425. .height(30);
  13426. }
  13427. .height(55)
  13428. }
  13429. .backgroundColor(Color.Transparent)
  13430. .borderRadius(15)
  13431. .margin({
  13432. left: 30,
  13433. right: 30,
  13434. top: 0,
  13435. bottom: 20
  13436. })
  13437. .padding(0)
  13438. .border({
  13439. color: Color.White,
  13440. width: 1.8
  13441. })
  13442. }else{
  13443. Row() {
  13444. Row() {
  13445. Text(`迷你歌词:`)
  13446. .fontSize(14)
  13447. .fontColor(Color.White)
  13448. .width(88)
  13449. Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
  13450. .selectedColor(this.themeColor)
  13451. .switchPointColor(Color.White)
  13452. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13453. .onChange((checked: boolean) => {
  13454. this.isShowSingleLineLyric = checked;
  13455. PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
  13456. })
  13457. .width(50)
  13458. .height(30)
  13459. .alignSelf(ItemAlign.Start)
  13460. .margin({ left: 12 })
  13461. Blank()
  13462. }
  13463. .layoutWeight(1)
  13464. Row() {
  13465. Text(`逐字歌词:`)
  13466. .fontSize(14)
  13467. .fontColor(Color.White)
  13468. .width(88)
  13469. Toggle({ type: ToggleType.Switch, isOn: this.isEnableWordByWordLyric })
  13470. .selectedColor(this.themeColor)
  13471. .switchPointColor(Color.White)
  13472. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13473. .onChange((checked: boolean) => {
  13474. this.isEnableWordByWordLyric = checked;
  13475. PreferencesUtil.putSync(SettingPage.IS_ENABLE_WORD_BY_WORD_LYRIC, this.isEnableWordByWordLyric)
  13476. this.syncWordByWordLyricMode()
  13477. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  13478. })
  13479. .width(50)
  13480. .height(30)
  13481. .alignSelf(ItemAlign.Start)
  13482. .margin({ left: 12 })
  13483. Blank()
  13484. }
  13485. .layoutWeight(1)
  13486. }
  13487. .width('100%')
  13488. .margin({
  13489. left: 20,
  13490. right: 15,
  13491. top: 10,
  13492. bottom: 10
  13493. })
  13494. }
  13495. if (!isPip) {
  13496. Row() {
  13497. Row() {
  13498. Text(`歌词发光:`)
  13499. .fontSize(14)
  13500. .fontColor(Color.White)
  13501. .width(88)
  13502. Toggle({ type: ToggleType.Switch, isOn: this.isLightText })
  13503. .selectedColor(this.themeColor)
  13504. .switchPointColor(Color.White)
  13505. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13506. .onChange((checked: boolean) => {
  13507. this.isLightText = checked;
  13508. PreferencesUtil.putSync(SettingPage.IS_LIGHT_TEXT, this.isLightText)
  13509. this.syncLyricLightTextMode()
  13510. })
  13511. .width(50)
  13512. .height(30)
  13513. .alignSelf(ItemAlign.Start)
  13514. .margin({ left: 12 })
  13515. Blank()
  13516. }
  13517. .layoutWeight(1)
  13518. Row() {
  13519. Text(`高亮居中:`)
  13520. .fontSize(14)
  13521. .fontColor(Color.White)
  13522. .width(88)
  13523. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  13524. .selectedColor(this.themeColor)
  13525. .switchPointColor(Color.White)
  13526. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13527. .onChange((checked: boolean) => {
  13528. this.isHightLightCenter = checked;
  13529. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  13530. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  13531. })
  13532. .width(50)
  13533. .height(30)
  13534. .alignSelf(ItemAlign.Start)
  13535. .margin({ left: 12 })
  13536. Blank()
  13537. }
  13538. .layoutWeight(1)
  13539. }
  13540. .width('100%')
  13541. .margin({
  13542. left: 20,
  13543. right: 15,
  13544. top: 10,
  13545. bottom: 10
  13546. })
  13547. }
  13548. Row() {
  13549. Text(`歌词居中:`)
  13550. .fontSize(14)
  13551. .fontColor(Color.White)
  13552. Row() {
  13553. ForEach(['居中', '居左'], (size: string, index: number) => {
  13554. Button(size)
  13555. .width(60)
  13556. .height(28)
  13557. .fontSize(12)
  13558. .fontColor('#FFFFFF')
  13559. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  13560. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  13561. .border({
  13562. color: (!isPip && this.currentLyricAlignMode === index) ||
  13563. (isPip && this.currentLyricAlignModePip === index) ?
  13564. '#007DFF' : '#DDDDDD',
  13565. width: 1.8
  13566. })
  13567. .onClick(() => {
  13568. this.setLyricAlignMode(index, isPip)
  13569. })
  13570. .margin({ left: 10, right: 8 })
  13571. })
  13572. }
  13573. .layoutWeight(1)
  13574. Blank()
  13575. }
  13576. .width('100%')
  13577. .margin({
  13578. top: 10,
  13579. bottom: 10,
  13580. right: 15,
  13581. left: 20
  13582. })
  13583. if (isPip) {
  13584. Row() {
  13585. Text(`悬浮背景:`)
  13586. .fontSize(14)
  13587. .fontColor(Color.White)
  13588. Select([
  13589. { value: CommonConstants.PIP_LYRIC_BG[0] },
  13590. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  13591. .font({ size: 13, weight: FontWeight.Medium })
  13592. .fontColor(Color.White)
  13593. .margin({ left: 10 })
  13594. .selected(this.pipBgIndex)
  13595. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  13596. .onSelect(async (_index: number, text?: string | undefined) => {
  13597. this.pipBgIndex = _index
  13598. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  13599. if (this.pipBgIndex === 0) {
  13600. if (this.cover) {
  13601. this.pipBg = this.cover
  13602. } else {
  13603. this.pipBg = this.imageColor
  13604. }
  13605. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  13606. } else {
  13607. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  13608. }
  13609. })
  13610. Column() {
  13611. }
  13612. .backgroundColor(this.pipBg)
  13613. .margin({ left: 10, right: 10 })
  13614. .borderRadius(20)
  13615. .height(28)
  13616. .width(28)
  13617. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13618. Row() {
  13619. SymbolGlyph($r('sys.symbol.paintbrush'))
  13620. .fontColor([Color.White])
  13621. .effectStrategy(1)
  13622. Text(`选择颜色`)
  13623. .fontSize(13)
  13624. .margin({ left: 10 })
  13625. .fontColor(Color.White)
  13626. }
  13627. }
  13628. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  13629. .backgroundColor(Color.Transparent)
  13630. .border({
  13631. color: '#FFFFFF',
  13632. radius: 20,
  13633. width: 1.8
  13634. })
  13635. .height(36)
  13636. .width(110)
  13637. .onClick(() => {
  13638. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  13639. })
  13640. .bindPopup(this.isShowPipBgSelectColor, {
  13641. builder: this.SelectColor(false, isPip, true),
  13642. placement: Placement.Top,
  13643. mask: { color: '#33000000' },
  13644. enableArrow: false, //是否显示箭头
  13645. showInSubWindow: false,
  13646. onStateChange: (e) => {
  13647. if (!e.isVisible) {
  13648. this.isShowPipBgSelectColor = false
  13649. }
  13650. }
  13651. })
  13652. }
  13653. .width('100%')
  13654. .margin({ bottom: 5, right: 15, left: 20 })
  13655. }
  13656. Row() {
  13657. Text(`歌词颜色:`)
  13658. .fontSize(14)
  13659. .fontColor(Color.White)
  13660. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  13661. .fontSize(15)
  13662. .fontColor(Color.White)
  13663. .margin({ left: 6, right: 6 })
  13664. Column() {
  13665. }
  13666. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  13667. .margin({ right: 12 })
  13668. .borderRadius(20)
  13669. .height(28)
  13670. .width(28)
  13671. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13672. Row() {
  13673. SymbolGlyph($r('sys.symbol.paintbrush'))
  13674. .fontColor([Color.White])
  13675. .effectStrategy(1)
  13676. Text(`选择颜色`)
  13677. .fontSize(13)
  13678. .margin({ left: 10 })
  13679. .fontColor(Color.White)
  13680. }
  13681. }
  13682. .backgroundColor(Color.Transparent)
  13683. .border({
  13684. color: '#FFFFFF',
  13685. radius: 20,
  13686. width: 1.8
  13687. })
  13688. .height(36)
  13689. .width(110)
  13690. .onClick(() => {
  13691. this.isShowSelectColor = !this.isShowSelectColor
  13692. })
  13693. .bindPopup(this.isShowSelectColor, {
  13694. builder: this.SelectColor(false, isPip),
  13695. placement: Placement.Top,
  13696. mask: { color: '#33000000' },
  13697. enableArrow: false, //是否显示箭头
  13698. showInSubWindow: false,
  13699. onStateChange: (e) => {
  13700. if (!e.isVisible) {
  13701. this.isShowSelectColor = false
  13702. }
  13703. }
  13704. })
  13705. }
  13706. .width('100%')
  13707. .margin({
  13708. top: 10,
  13709. bottom: 10,
  13710. right: 15,
  13711. left: 20
  13712. })
  13713. Row() {
  13714. Text(`高亮颜色:`)
  13715. .fontSize(14)
  13716. .fontColor(Color.White)
  13717. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  13718. .fontSize(15)
  13719. .fontColor(Color.White)
  13720. .margin({ left: 6, right: 6 })
  13721. Column() {
  13722. }
  13723. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  13724. .margin({ right: 12 })
  13725. .borderRadius(20)
  13726. .height(28)
  13727. .width(28)
  13728. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13729. Row() {
  13730. SymbolGlyph($r('sys.symbol.paintbrush'))
  13731. .fontColor([Color.White])
  13732. .effectStrategy(1)
  13733. Text(`选择颜色`)
  13734. .fontSize(13)
  13735. .margin({ left: 10 })
  13736. .fontColor(Color.White)
  13737. }
  13738. }
  13739. .backgroundColor(Color.Transparent)
  13740. .border({
  13741. color: '#FFFFFF',
  13742. radius: 20,
  13743. width: 1.8
  13744. })
  13745. .height(36)
  13746. .width(110)
  13747. .onClick(() => {
  13748. this.isShowHLSelectColor = !this.isShowHLSelectColor
  13749. })
  13750. .bindPopup(this.isShowHLSelectColor, {
  13751. builder: this.SelectColor(true, isPip),
  13752. placement: Placement.Top,
  13753. mask: { color: '#33000000' },
  13754. enableArrow: false, //是否显示箭头
  13755. showInSubWindow: false,
  13756. onStateChange: (e) => {
  13757. if (!e.isVisible) {
  13758. this.isShowHLSelectColor = false
  13759. }
  13760. }
  13761. })
  13762. }
  13763. .width('100%')
  13764. .margin({
  13765. top: 10,
  13766. bottom: 10,
  13767. right: 15,
  13768. left: 20
  13769. })
  13770. if (isPip) {
  13771. Row() {
  13772. Text(`显示宽度:`)
  13773. .fontSize(14)
  13774. .fontColor(Color.White)
  13775. Slider({
  13776. value: this.pipLyWidth,
  13777. min: 10,
  13778. max: 800,
  13779. step: 1,
  13780. style: SliderStyle.OutSet
  13781. })
  13782. .blockColor(this.themeColor)
  13783. .trackColor($r('app.color.speed_text_color'))
  13784. .selectedColor(Color.White)
  13785. .trackThickness(6)
  13786. .onChange((value: number) => {
  13787. this.pipLyWidth = value
  13788. if (this.pipController) {
  13789. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  13790. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  13791. }
  13792. })
  13793. .layoutWeight(1)
  13794. }
  13795. .justifyContent(FlexAlign.Start)
  13796. .margin({
  13797. left: 20,
  13798. right: 15,
  13799. top: 5,
  13800. bottom: 5
  13801. })
  13802. Row() {
  13803. Text(`显示高度:`)
  13804. .fontSize(14)
  13805. .fontColor(Color.White)
  13806. Slider({
  13807. value: this.pipLyHeight,
  13808. min: 10,
  13809. max: 1000,
  13810. step: 1,
  13811. style: SliderStyle.OutSet
  13812. })
  13813. .blockColor(this.themeColor)
  13814. .trackColor($r('app.color.speed_text_color'))
  13815. .selectedColor(Color.White)
  13816. .trackThickness(6)
  13817. .onChange((value: number) => {
  13818. this.pipLyHeight = value
  13819. if (this.pipController) {
  13820. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  13821. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  13822. }
  13823. })
  13824. .layoutWeight(1)
  13825. }
  13826. .justifyContent(FlexAlign.Start)
  13827. .margin({
  13828. left: 20,
  13829. right: 15,
  13830. top: 5,
  13831. bottom: 5
  13832. })
  13833. }
  13834. Row() {
  13835. Text(`歌词字号:`)
  13836. .fontSize(14)
  13837. .fontColor(Color.White)
  13838. Slider({
  13839. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  13840. min: 12,
  13841. max: 30,
  13842. step: 0.1,
  13843. style: SliderStyle.OutSet
  13844. })
  13845. .blockColor(this.themeColor)
  13846. .trackColor($r('app.color.speed_text_color'))
  13847. .selectedColor(Color.White)
  13848. .trackThickness(6)
  13849. .onChange((value: number) => {
  13850. this.setLyricTextSize(value, isPip)
  13851. })
  13852. .layoutWeight(1)
  13853. .margin({ right: 3 })
  13854. Text(this.getLyricSizeDisplayValue(isPip))
  13855. .fontSize(13)
  13856. .fontColor(Color.White)
  13857. .textAlign(TextAlign.Start)
  13858. }
  13859. .width('100%')
  13860. .margin({
  13861. left: 20,
  13862. right: 15,
  13863. top: 5,
  13864. bottom: 5
  13865. })
  13866. Row() {
  13867. Text(`高亮倍数:`)
  13868. .fontSize(14)
  13869. .fontColor(Color.White)
  13870. Slider({
  13871. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  13872. min: 1,
  13873. max: 2,
  13874. step: 0.1,
  13875. style: SliderStyle.OutSet
  13876. })
  13877. .blockColor(this.themeColor)
  13878. .trackColor($r('app.color.speed_text_color'))
  13879. .selectedColor(Color.White)
  13880. .trackThickness(6)
  13881. .onChange((value: number) => {
  13882. this.setHighLyricTextSize(value, isPip)
  13883. })
  13884. .layoutWeight(1)
  13885. .margin({ right: 3 })
  13886. Text(this.getHighLyricSizeDisplayValue(isPip))
  13887. .fontSize(13)
  13888. .fontColor(Color.White)
  13889. .textAlign(TextAlign.Start)
  13890. }
  13891. .width('100%')
  13892. .margin({
  13893. left: 20,
  13894. right: 15,
  13895. top: 5,
  13896. bottom: 5
  13897. })
  13898. Row() {
  13899. Text(`歌词间隙:`)
  13900. .fontSize(14)
  13901. .fontColor(Color.White)
  13902. Slider({
  13903. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  13904. min: 0,
  13905. max: 100,
  13906. step: 1,
  13907. style: SliderStyle.OutSet
  13908. })
  13909. .blockColor(this.themeColor)
  13910. .trackColor($r('app.color.speed_text_color'))
  13911. .selectedColor(Color.White)
  13912. .trackThickness(6)
  13913. .onChange((value: number) => {
  13914. this.setLyricLineSpace(value, isPip)
  13915. })
  13916. .layoutWeight(1)
  13917. .margin({ right: 3 })
  13918. Text(this.getLyricLineSpaceDisplayValue(isPip))
  13919. .fontSize(13)
  13920. .fontColor(Color.White)
  13921. .textAlign(TextAlign.Start)
  13922. }
  13923. .width('100%')
  13924. .margin({
  13925. left: 20,
  13926. right: 15,
  13927. top: 5,
  13928. bottom: 5
  13929. })
  13930. //取值间隔为100,默认为400,取值越大,字体越粗
  13931. Row() {
  13932. Text(`歌词字重:`)
  13933. .fontSize(14)
  13934. .fontColor(Color.White)
  13935. Slider({
  13936. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  13937. min: 100,
  13938. max: 900,
  13939. step: 100,
  13940. style: SliderStyle.OutSet
  13941. })
  13942. .blockColor(this.themeColor)
  13943. .trackColor($r('app.color.speed_text_color'))
  13944. .selectedColor(Color.White)
  13945. .trackThickness(6)
  13946. .onChange((value: number) => {
  13947. if (isPip) {
  13948. this.lyricTextWeightPip = value
  13949. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  13950. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  13951. } else {
  13952. this.lyricTextWeight = value
  13953. this.lyricController.setTextWeight(this.lyricTextWeight)
  13954. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  13955. }
  13956. })
  13957. .layoutWeight(1)
  13958. .margin({ right: 3 })
  13959. Text(this.getLyricTextWeightDisplayValue(isPip))
  13960. .fontSize(13)
  13961. .fontColor(Color.White)
  13962. .textAlign(TextAlign.Start)
  13963. }
  13964. .width('100%')
  13965. .margin({
  13966. left: 20,
  13967. right: 15,
  13968. top: 5,
  13969. bottom: 5
  13970. })
  13971. Row() {
  13972. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  13973. this.pushLyricButton($r('app.media.share2'), 2, '分享歌词')
  13974. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  13975. // this.pushLyricButton($r('app.media.white_search'), 1, '繁体转简体')
  13976. }
  13977. .justifyContent(FlexAlign.Center)
  13978. .margin({ top: 3, bottom: 10 })
  13979. }
  13980. .width('88%')
  13981. }
  13982. private getLyricSizeDisplayValue(isPip: boolean): string {
  13983. const lyricSize = isPip ? this.currentLyricSizePip : this.currentLyricSize;
  13984. return lyricSize.toFixed(1);
  13985. }
  13986. private getHighLyricSizeDisplayValue(isPip: boolean): string {
  13987. const highLyricSize = isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize;
  13988. return highLyricSize.toFixed(1);
  13989. }
  13990. private getLyricLineSpaceDisplayValue(isPip: boolean): string {
  13991. const lyricLineSpace = isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace;
  13992. return Math.round(lyricLineSpace).toString();
  13993. }
  13994. private getLyricTextWeightDisplayValue(isPip: boolean): string {
  13995. const lyricTextWeightValue = isPip ? this.lyricTextWeightPip : this.lyricTextWeight;
  13996. return Math.round(lyricTextWeightValue).toString();
  13997. }
  13998. private setBlurDegree(index: number, isPip: boolean) {
  13999. if (isPip) {
  14000. this.blurDegreePip = index
  14001. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  14002. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  14003. } else {
  14004. this.blurDegree = index
  14005. this.lyricController.setBlurDegree(this.blurDegree)
  14006. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  14007. }
  14008. }
  14009. private setLyricAlignMode(index: number, isPip: boolean) {
  14010. if (isPip) {
  14011. this.currentLyricAlignModePip = index
  14012. if (this.currentLyricAlignModePip === 1) {
  14013. this.lyricControllerXF.setAlignMode("left")
  14014. } else {
  14015. this.lyricControllerXF.setAlignMode("center")
  14016. }
  14017. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  14018. } else {
  14019. this.currentLyricAlignMode = index
  14020. if (this.currentLyricAlignMode === 1) {
  14021. this.lyricController.setAlignMode("left")
  14022. } else {
  14023. this.lyricController.setAlignMode("center")
  14024. }
  14025. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  14026. }
  14027. }
  14028. private setLyricTextSize(index: number, isPip: boolean) {
  14029. if (isPip) {
  14030. this.currentLyricSizePip = index
  14031. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  14032. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  14033. } else {
  14034. this.currentLyricSize = index
  14035. this.lyricController.setTextSize(this.currentLyricSize)
  14036. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  14037. }
  14038. }
  14039. private setHighLyricTextSize(scale: number, isPip: boolean) {
  14040. if (isPip) {
  14041. this.currentHightLyricSizePip = scale
  14042. this.lyricControllerXF
  14043. .setHighlightScale(this.currentHightLyricSizePip)
  14044. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  14045. } else {
  14046. this.currentHightLyricSize = scale
  14047. this.lyricController
  14048. .setHighlightScale(this.currentHightLyricSize)
  14049. PreferencesUtil.putSync('HighLyricTextSize', scale)
  14050. }
  14051. }
  14052. private setLyricLineSpace(index: number, isPip: boolean) {
  14053. if (isPip) {
  14054. this.currentLyricLineSpacePip = index
  14055. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  14056. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  14057. } else {
  14058. this.currentLyricLineSpace = index
  14059. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  14060. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  14061. }
  14062. }
  14063. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  14064. LogUtil.info('onecold isBG = ' + isBG)
  14065. if (isBG) { //如果是设置悬浮背景
  14066. this.pipBg = color
  14067. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  14068. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  14069. return
  14070. }
  14071. if (isPip) {
  14072. this.currentLyricColorPip = color
  14073. this.lyricControllerXF
  14074. .setTextColor(this.currentLyricColorPip)
  14075. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  14076. } else {
  14077. this.currentLyricColor = color
  14078. this.lyricController
  14079. .setTextColor(this.currentLyricColor)
  14080. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  14081. }
  14082. }
  14083. private changeLyricHightLightColor(color: string, isPip: boolean) {
  14084. if (isPip) {
  14085. this.currentHighLightLyricColorPip = color
  14086. this.lyricControllerXF
  14087. .setHighlightColor(this.currentHighLightLyricColorPip)
  14088. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  14089. } else {
  14090. this.currentHighLightLyricColor = color
  14091. this.lyricController
  14092. .setHighlightColor(this.currentHighLightLyricColor)
  14093. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  14094. }
  14095. }
  14096. // 构建时间控制器
  14097. @Builder
  14098. BuildTimeControls() {
  14099. Column() {
  14100. // 时间显示
  14101. Text(this.getTimeText())
  14102. .fontSize(18)
  14103. .fontColor(Color.White)
  14104. .margin({ bottom: 10 })
  14105. Row() {
  14106. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  14107. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  14108. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  14109. }
  14110. .justifyContent(FlexAlign.Center)
  14111. }
  14112. .margin({ top: 12, bottom: 8 })
  14113. }
  14114. // 精度按钮组件
  14115. @Builder
  14116. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  14117. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  14118. Column() {
  14119. Image(icon)
  14120. .width(28)
  14121. .margin({ bottom: 5 })
  14122. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  14123. Text(label)
  14124. .fontSize(12)
  14125. .fontColor('#FFFFFF')
  14126. }
  14127. }
  14128. .backgroundColor(Color.Transparent)
  14129. .enabled(!this.isButtonDisabled(step))
  14130. .onClick(() => this.handlePrecisionAdjust(step))
  14131. .padding(5)
  14132. .width(66)
  14133. .height(66)
  14134. .margin({ left: 18, right: 18 })
  14135. .border({
  14136. color: '#FFFFFF',
  14137. width: 1.8
  14138. })
  14139. }
  14140. private handlePrecisionAdjust(step: number) {
  14141. if (step === 0) {
  14142. this.timeOffset = 0
  14143. this.saveLyricTimeOffset()
  14144. return
  14145. }
  14146. // 精度处理:保留1位小数
  14147. const newOffset = Number((this.timeOffset + step).toFixed(5))
  14148. // 边界保护(±15.0秒)
  14149. if (newOffset < -30.0 || newOffset > 30.0) {
  14150. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  14151. return
  14152. }
  14153. // 状态更新
  14154. this.timeOffset = newOffset
  14155. // 保存歌词时间偏移
  14156. this.saveLyricTimeOffset()
  14157. }
  14158. // 按钮禁用逻辑
  14159. private isButtonDisabled(step: number): boolean {
  14160. const futureOffset = this.timeOffset + step
  14161. return (futureOffset < -30.0) || (futureOffset > 30.0)
  14162. }
  14163. // 时间显示文本升级
  14164. private getTimeText(): string {
  14165. const absValue = Math.abs(this.timeOffset)
  14166. return this.timeOffset === 0
  14167. ? '歌词时间已重置'
  14168. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  14169. }
  14170. /**
  14171. * 获取当前歌曲的唯一标识key
  14172. * 使用歌曲的filePath作为唯一标识
  14173. */
  14174. private getLyricOffsetKey(): string {
  14175. if (this.currentSong && StrUtil.isNotEmpty(this.currentSong.filePath)) {
  14176. // 使用MD5对filePath进行加密,作为存储key
  14177. return 'lyric_offset_' + MD5.digestSync(this.currentSong.filePath)
  14178. }
  14179. return ''
  14180. }
  14181. /**
  14182. * 保存当前歌曲的歌词时间偏移
  14183. */
  14184. private saveLyricTimeOffset(): void {
  14185. try {
  14186. const key = this.getLyricOffsetKey()
  14187. if (StrUtil.isEmpty(key)) {
  14188. console.warn('heanup saveLyricTimeOffset: key is empty')
  14189. return
  14190. }
  14191. PreferencesUtil.putSync(key, this.timeOffset)
  14192. console.info('heanup saveLyricTimeOffset: key=' + key + ', offset=' + this.timeOffset)
  14193. } catch (e) {
  14194. console.error('heanup saveLyricTimeOffset error: ' + JSON.stringify(e))
  14195. }
  14196. }
  14197. /**
  14198. * 加载当前歌曲的歌词时间偏移
  14199. */
  14200. private loadLyricTimeOffset(): void {
  14201. try {
  14202. const key = this.getLyricOffsetKey()
  14203. if (StrUtil.isEmpty(key)) {
  14204. console.warn('heanup loadLyricTimeOffset: key is empty')
  14205. return
  14206. }
  14207. const savedOffset = PreferencesUtil.getNumberSync(key, 0)
  14208. if (savedOffset !== 0) {
  14209. this.timeOffset = savedOffset
  14210. console.info('heanup loadLyricTimeOffset: key=' + key + ', offset=' + savedOffset)
  14211. }else{
  14212. this.timeOffset = 0
  14213. }
  14214. } catch (e) {
  14215. console.error('heanup loadLyricTimeOffset error: ' + JSON.stringify(e))
  14216. }
  14217. }
  14218. // 导入 本地歌词 搜索歌词
  14219. @Builder
  14220. pushLyricButton(icon: Resource, step: number, label: string) {
  14221. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  14222. Row() {
  14223. Image(icon)
  14224. .width(14)
  14225. .margin({ left: 13 })
  14226. Text(label)
  14227. .fontSize(12)
  14228. .margin({ left: 6 })
  14229. .fontColor('#FFFFFF')
  14230. }
  14231. }
  14232. .onClick(() => {
  14233. switch (step) {
  14234. case 0:
  14235. this.callFilePickerSelectFileForLyric()
  14236. break;
  14237. case 1:
  14238. //判断有没有设置api
  14239. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  14240. this.isLyricSetting = false
  14241. this.showTipsDialog()
  14242. return
  14243. }
  14244. if (StrUtil.isNotEmpty(this.videoUrl)) {
  14245. ToastUtil.showToast('正在获取')
  14246. this.isLyricSetting = false
  14247. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  14248. this.initLyric(lyricPath, true);
  14249. }
  14250. break;
  14251. case 2:
  14252. this.isLyricSetting = false
  14253. this.openLyricCopySheet()
  14254. break;
  14255. }
  14256. })
  14257. .padding(5)
  14258. .layoutWeight(1)
  14259. .backgroundColor(Color.Transparent)
  14260. .height(40)
  14261. .margin({ left: 4, right: 4 })
  14262. .border({
  14263. color: '#FFFFFF',
  14264. radius: 20,
  14265. width: 1.8
  14266. })
  14267. }
  14268. showVipDialog() {
  14269. DialogHelper.showCustomContentDialog({
  14270. dialogId: 'vip',
  14271. title: "友情提示",
  14272. autoCancel: false, //点击遮障层时,不关闭弹窗
  14273. backCancel: true, //点击返回键,不关闭弹窗
  14274. contentBuilder: () => {
  14275. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  14276. },
  14277. buttons: [],
  14278. })
  14279. }
  14280. //去赞助的自定义内容
  14281. @Builder
  14282. customVipBuilder(content: string) {
  14283. Column() {
  14284. Text(content)
  14285. .fontColor(Color.Gray)
  14286. .fontSize(16)
  14287. .alignSelf(ItemAlign.Start)
  14288. .margin({ bottom: 15 })
  14289. .fontSize(16)
  14290. Row() {
  14291. Button('取消')
  14292. .fontColor(Color.White)
  14293. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  14294. .height(50)
  14295. .layoutWeight(1)
  14296. .stateEffect(true)
  14297. .margin({ right: 6 })
  14298. .onClick(() => {
  14299. DialogHelper.closeDialog('vip'); //关闭弹框
  14300. })
  14301. Button('开通')
  14302. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  14303. .layoutWeight(1)
  14304. .height(50)
  14305. .backgroundColor(this.themeColor)
  14306. .stateEffect(true)
  14307. .margin({ left: 6 })
  14308. .onClick(() => {
  14309. DialogHelper.closeDialog('vip'); //关闭弹框
  14310. this.isShowPlay = false
  14311. this.mType = 1 //跳转到用户中心
  14312. // router.pushUrl({
  14313. // url: 'pages/VipPage'
  14314. // }, router.RouterMode.Single);
  14315. })
  14316. }
  14317. }
  14318. .width("100%")
  14319. .padding(10)
  14320. }
  14321. showTipsDialog() {
  14322. DialogHelper.showCustomContentDialog({
  14323. dialogId: 'tips',
  14324. title: "友情提示",
  14325. autoCancel: false, //点击遮障层时,不关闭弹窗
  14326. backCancel: true, //点击返回键,不关闭弹窗
  14327. contentBuilder: () => {
  14328. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  14329. },
  14330. buttons: [],
  14331. })
  14332. }
  14333. @Builder
  14334. customTipsBuilder(content: string) {
  14335. Column() {
  14336. Text(content)
  14337. .fontColor(Color.Gray)
  14338. .fontSize(16)
  14339. .alignSelf(ItemAlign.Start)
  14340. .margin({ bottom: 15 })
  14341. .fontSize(16)
  14342. Row() {
  14343. Button('取消')
  14344. .fontColor(Color.White)
  14345. .backgroundColor(this.themeColor)
  14346. .height(50)
  14347. .layoutWeight(1)
  14348. .stateEffect(true)
  14349. .margin({ right: 6 })
  14350. .onClick(() => {
  14351. DialogHelper.closeDialog('tips'); //关闭弹框
  14352. })
  14353. Button('跳转')
  14354. .fontColor(Color.White)//
  14355. .layoutWeight(1)
  14356. .height(50)
  14357. .backgroundColor(this.themeColor)
  14358. .stateEffect(true)
  14359. .margin({ left: 6 })
  14360. .onClick(() => {
  14361. DialogHelper.closeDialog('tips'); //关闭弹框
  14362. this.isShowEdit = false
  14363. this.longItemFilePath = ''
  14364. // if(this.isGridMusic&&!this.isShowPlay){
  14365. // this.longItemFilePath== ''
  14366. // }else{
  14367. // this.isShowEdit = false
  14368. // }
  14369. this.isShowMoreView = false;
  14370. this.isShowPlay = false
  14371. this.mType = 4
  14372. // router.pushUrl({
  14373. // url: 'pages/SettingPage'
  14374. // }, router.RouterMode.Single);
  14375. })
  14376. }
  14377. }
  14378. .width("100%")
  14379. .padding(10)
  14380. }
  14381. @Builder
  14382. PlayMoreSheet() {
  14383. Column() {
  14384. this.MoreList()
  14385. }
  14386. .width('100%')
  14387. .height('100%')
  14388. }
  14389. @Builder
  14390. MoreList() {
  14391. Scroll() {
  14392. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  14393. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  14394. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  14395. Row() {
  14396. if (more.id === 3&&this.currentSong) {
  14397. Image(more.image)
  14398. .width(24)
  14399. .height(24)
  14400. .margin({ left: 10, right: 10 })
  14401. Text(more.title)
  14402. .fontSize(16)
  14403. .fontColor(Color.White)
  14404. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  14405. height: '99%',
  14406. dragBar: true,
  14407. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  14408. showClose: true,
  14409. blurStyle: BlurStyle.Thin,
  14410. backgroundColor: Color.Transparent,
  14411. title: { title: '歌曲信息' }
  14412. })
  14413. } else if (more.id === 15 && this.currentSong) { //编辑标签
  14414. Image(more.image)
  14415. .width(24)
  14416. .height(24)
  14417. .margin({ left: 10, right: 10 })
  14418. Text(more.title)
  14419. .fontSize(16)
  14420. .fontColor(Color.White)
  14421. } else if (more.id === 5) { //定时关闭
  14422. Image(more.image)
  14423. .width(24)
  14424. .height(24)
  14425. .margin({ left: 10, right: 10 })
  14426. Text(more.title)
  14427. .fontSize(16)
  14428. .fontColor(Color.White)
  14429. .onClick(() => {
  14430. this.doMore(more.id)
  14431. })
  14432. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  14433. height: this.isCoverOpacity() ? '95%' : '95%',
  14434. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  14435. dragBar: true,
  14436. showClose: true,
  14437. title: { title: $r('app.string.time_close') }
  14438. })
  14439. } else if (more.id === 2) { //歌词设置
  14440. Image(more.image)
  14441. .width(24)
  14442. .height(24)
  14443. .margin({ left: 10, right: 10 })
  14444. Text(more.title)
  14445. .fontSize(16)
  14446. .fontColor(Color.White)
  14447. } else if (more.id === 16) { //悬浮歌词设置
  14448. Image(more.image)
  14449. .width(24)
  14450. .height(24)
  14451. .margin({ left: 10, right: 10 })
  14452. Text(more.title)
  14453. .fontSize(16)
  14454. .fontColor(Color.White)
  14455. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  14456. height: '99%',
  14457. dragBar: true,
  14458. preferType: SheetType.CENTER,
  14459. showClose: true,
  14460. blurStyle: BlurStyle.Thin,
  14461. backgroundColor: Color.Transparent,
  14462. title: { title: '悬浮歌词' }
  14463. })
  14464. } else if (more.id === 11) {
  14465. Image(more.image)
  14466. .width(24)
  14467. .height(24)
  14468. .margin({ left: 10, right: 10 })
  14469. Text(more.title)
  14470. .fontSize(16)
  14471. .fontColor(Color.White)
  14472. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  14473. height: this.isCoverOpacity() ? '95%' : '60%',
  14474. dragBar: true,
  14475. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  14476. showClose: true,
  14477. blurStyle: BlurStyle.Thin,
  14478. backgroundColor: Color.Transparent,
  14479. title: { title: '跳过头尾' }
  14480. })
  14481. } else if (more.id === 12) { //投播
  14482. AVCastPicker({
  14483. customPicker: (): void => this.TPImageBuilder(more),
  14484. onStateChange: (state) => {
  14485. if (state == AVCastPickerState.STATE_APPEARING) {
  14486. console.log(' The picker starts showing.');
  14487. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  14488. console.log(' The picker finishes presenting.');
  14489. }
  14490. },
  14491. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  14492. sessionType: 'video'
  14493. })
  14494. .id('AVCastPicker')
  14495. } else {
  14496. if(more.id >= 22){
  14497. SymbolGlyph(more.image)
  14498. .fontSize(24)
  14499. .fontColor([Color.White])
  14500. .alignSelf(ItemAlign.Center)
  14501. .margin({ left: 10, right: 10,bottom:5})
  14502. // .padding({bottom:4})
  14503. .onClick(() => {
  14504. this.doMore(more.id)
  14505. })
  14506. }else{
  14507. Image(more.image)
  14508. .width(24)
  14509. .height(24)
  14510. .fillColor(Color.White)
  14511. .margin({ left: 10, right: 10 })
  14512. .onClick(() => {
  14513. this.doMore(more.id)
  14514. })
  14515. }
  14516. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  14517. .fontSize(16)
  14518. .margin({top:more.id >= 22?3:0})
  14519. .fontColor(Color.White)
  14520. .onClick(() => {
  14521. this.doMore(more.id)
  14522. })
  14523. Select([//倍速
  14524. { value: '0.25x' },
  14525. { value: '0.5x' },
  14526. { value: '0.75x' },
  14527. { value: '1x' },
  14528. { value: '1.25x' },
  14529. { value: '1.5x' },
  14530. { value: '1.75x' },
  14531. { value: '2x' },
  14532. { value: '3x' }])
  14533. .font({ size: 16, weight: FontWeight.Medium })
  14534. .fontColor($r('sys.color.white'))
  14535. .margin({ left: 25 })
  14536. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  14537. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  14538. .value(Utility.optimizedFormat(this.playSpeed))
  14539. .onSelect(async (_index: number, text?: string | undefined) => {
  14540. let speed = parseFloat(text?.replace('x', '') || '1');
  14541. if (!CommonConstants.video_speed_list.includes(speed)) {
  14542. speed = 1;
  14543. }
  14544. this.playSpeed = speed
  14545. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  14546. })
  14547. Slider({
  14548. value: this.volume,
  14549. min: 0,
  14550. max: 1,
  14551. step: 0.1,
  14552. style: SliderStyle.OutSet
  14553. })
  14554. .margin({ left: 18, right: 8 })
  14555. .blockColor(this.themeColor)
  14556. .trackColor($r('app.color.speed_text_color'))
  14557. .selectedColor(Color.White)
  14558. .trackThickness(9)
  14559. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  14560. .onChange((value: number) => {
  14561. this.volume = value;
  14562. this.applyCurrentVolume();
  14563. PreferencesUtil.putSync('DefalutVolume',this.volume)
  14564. })
  14565. .layoutWeight(1)
  14566. Slider({
  14567. value: this.volumeBoostPercent,
  14568. min: 0,
  14569. max: this.volumeBoostMaxPercent,
  14570. step: 1,
  14571. style: SliderStyle.OutSet
  14572. })
  14573. .margin({ left: 18, right: 8 })
  14574. .blockColor(this.themeColor)
  14575. .trackColor($r('app.color.speed_text_color'))
  14576. .selectedColor(Color.White)
  14577. .trackThickness(9)
  14578. .visibility(more.id === 28 ? Visibility.Visible : Visibility.None)
  14579. .onChange((value: number) => {
  14580. this.volumeBoostPercent = Math.round(value);
  14581. this.applyCurrentVolume();
  14582. PreferencesUtil.putSync(this.volumeBoostPreferenceKey, this.volumeBoostPercent);
  14583. })
  14584. .layoutWeight(1)
  14585. Text(`${Math.round(this.volumeBoostPercent)}%`)
  14586. .fontSize(13)
  14587. .fontColor(Color.White)
  14588. .margin({ left: 8, right: 8 })
  14589. .visibility(more.id === 28 ? Visibility.Visible : Visibility.None)
  14590. Text(`${Math.round(this.volume*100)}%`)
  14591. .fontSize(13)
  14592. .fontColor(Color.White)
  14593. .margin({ left: 8, right: 8 })
  14594. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  14595. Blank()
  14596. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  14597. .selectedColor(this.themeColor)
  14598. .switchPointColor(Color.White)
  14599. .margin({ right: 15 })
  14600. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14601. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  14602. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14603. if (more.id == 6) {
  14604. this.isMusicMemoryPlay = checked;
  14605. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  14606. if (this.isMusicMemoryPlay) {
  14607. ToastUtil.showToast('记忆播放已开启')
  14608. } else {
  14609. ToastUtil.showToast('记忆播放已关闭')
  14610. }
  14611. }
  14612. })
  14613. .width(48)
  14614. .height(24);
  14615. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  14616. .selectedColor(this.themeColor)
  14617. .switchPointColor(Color.White)
  14618. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14619. .margin({ right: 15 })
  14620. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  14621. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14622. if (more.id == 7) {
  14623. this.isMusicBGCover = checked;
  14624. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  14625. if (this.isMusicBGCover) {
  14626. ToastUtil.showToast('播放背景随音乐封面已开启')
  14627. } else {
  14628. ToastUtil.showToast('播放背景随音乐封面已关闭')
  14629. }
  14630. }
  14631. })
  14632. .width(48)
  14633. .height(24);
  14634. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  14635. .selectedColor(this.themeColor)
  14636. .switchPointColor(Color.White)
  14637. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14638. .margin({ right: 15 })
  14639. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  14640. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14641. if (more.id == 8) {
  14642. this.isSavePlayMode = checked;
  14643. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  14644. if (this.isSavePlayMode) {
  14645. ToastUtil.showToast('保存播放模式已开启')
  14646. } else {
  14647. ToastUtil.showToast('保存播放模式已关闭')
  14648. }
  14649. }
  14650. })
  14651. .width(48)
  14652. .height(24);
  14653. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  14654. .selectedColor(this.themeColor)
  14655. .switchPointColor(Color.White)
  14656. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14657. .margin({ right: 15 })
  14658. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  14659. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14660. if (more.id == 13) {
  14661. this.isCoverRectangle = checked;
  14662. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  14663. if (this.isCoverRectangle) {
  14664. ToastUtil.showToast('封面方形已开启,双指缩放封面可以调整封面大小')
  14665. this.animationRoFun()
  14666. } else {
  14667. ToastUtil.showToast('封面圆形已开启,双指缩放封面可以调整封面大小')
  14668. this.animationRoFun()
  14669. }
  14670. }
  14671. })
  14672. .width(48)
  14673. .height(24);
  14674. Toggle({ type: ToggleType.Switch, isOn: this.isShowSpectrum })
  14675. .selectedColor(this.themeColor)
  14676. .switchPointColor(Color.White)
  14677. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14678. .margin({ right: 15 })
  14679. .visibility(more.id == 25 ? Visibility.Visible : Visibility.None)
  14680. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14681. if (more.id == 25) {
  14682. this.isShowSpectrum = checked;
  14683. PreferencesUtil.put("isShowSpectrum", this.isShowSpectrum)
  14684. }
  14685. })
  14686. .width(48)
  14687. .height(24);
  14688. // 频谱特效类型选择器
  14689. Select([
  14690. { value: '柱状' },
  14691. { value: '波形' },
  14692. { value: '水波纹' },
  14693. { value: '圆形' },
  14694. { value: '粒子' },
  14695. { value: '脉冲' },
  14696. { value: '镜像柱' },
  14697. { value: '影子柱' },
  14698. { value: '轨道线' },
  14699. { value: '点阵' },
  14700. { value: '星爆' },
  14701. { value: '心电图' },
  14702. { value: '特效' }
  14703. ])
  14704. .font({ size: 14, weight: FontWeight.Medium })
  14705. .fontColor(Color.White)
  14706. .margin({ left: 25 })
  14707. .margin({top:more.id >= 22?3:0})
  14708. .visibility(more.id === 26 ? Visibility.Visible : Visibility.None)
  14709. .selected(this.spectrumModeIndex)
  14710. .value(['柱状', '波形', '水波纹', '圆形', '粒子', '脉冲', '镜像柱', '影子柱', '轨道线', '点阵', '星爆', '心电图', '特效'][this.spectrumModeIndex])
  14711. .onSelect((index: number, _text?: string) => {
  14712. this.spectrumModeIndex = index;
  14713. // 使用同步方法保存,确保立即生效
  14714. PreferencesUtil.putSync('spectrumModeIndex', this.spectrumModeIndex);
  14715. AppStorage.setOrCreate<number>('spectrumMode', this.spectrumModeIndex);
  14716. const modeNames = ['柱状', '波形', '水波纹', '圆形', '粒子', '脉冲', '镜像柱', '影子柱', '轨道线', '点阵', '星爆', '心电图', '特效'];
  14717. Logger.info('heanup-LocalMusic', '频谱特效已切换为: ' + modeNames[index]);
  14718. });
  14719. Toggle({ type: ToggleType.Switch, isOn: this.showSimple })
  14720. .selectedColor(this.themeColor)
  14721. .switchPointColor(Color.White)
  14722. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14723. .margin({ right: 15 })
  14724. .visibility(more.id == 22 ? Visibility.Visible : Visibility.None)
  14725. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14726. if (more.id == 22) {
  14727. this.showSimple = checked;
  14728. PreferencesUtil.put('showSimple', this.showSimple)
  14729. }
  14730. })
  14731. .width(48)
  14732. .height(24);
  14733. Toggle({ type: ToggleType.Switch, isOn: this.enablePointLight })
  14734. .selectedColor(this.themeColor)
  14735. .switchPointColor(Color.White)
  14736. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14737. .margin({ right: 15 })
  14738. .visibility(more.id == 23 ? Visibility.Visible : Visibility.None)
  14739. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14740. if (more.id == 23) {
  14741. this.enablePointLight = checked;
  14742. PreferencesUtil.put('enablePointLight', this.enablePointLight)
  14743. AppStorage.setOrCreate('EnablePointLight', this.enablePointLight);
  14744. }
  14745. })
  14746. .width(48)
  14747. .height(24);
  14748. Toggle({ type: ToggleType.Switch, isOn: this.isGeKongPlayNext })
  14749. .selectedColor(this.themeColor)
  14750. .switchPointColor(Color.White)
  14751. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14752. .margin({ right: 15 })
  14753. .visibility(more.id == 27 ? Visibility.Visible : Visibility.None)
  14754. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14755. if (more.id == 27) {
  14756. this.isGeKongPlayNext = checked;
  14757. PreferencesUtil.put('isGeKongPlayNext', this.isGeKongPlayNext)
  14758. }
  14759. })
  14760. .width(48)
  14761. .height(24);
  14762. Toggle({ type: ToggleType.Switch, isOn: this.isShowBgLiuGUANG })
  14763. .selectedColor(this.themeColor)
  14764. .switchPointColor(Color.White)
  14765. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14766. .margin({ right: 15 })
  14767. .visibility(more.id == 21 ? Visibility.Visible : Visibility.None)
  14768. .onChange((checked: boolean) => { // 是否开启背景流光效果
  14769. if (more.id == 21) {
  14770. this.isShowBgLiuGUANG = checked;
  14771. PreferencesUtil.putSync('isShowBgLiuGUANG',this.isShowBgLiuGUANG)
  14772. }
  14773. })
  14774. .width(48)
  14775. .height(24);
  14776. }
  14777. }
  14778. .width('100%')
  14779. .height(45)
  14780. .padding(15)
  14781. .backgroundColor(Color.Transparent)
  14782. .borderRadius(12)
  14783. .margin({ bottom: 6 })
  14784. }
  14785. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  14786. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  14787. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  14788. .backgroundColor(Color.Transparent)
  14789. .onClick(() => {
  14790. this.doMore(more.id)
  14791. })
  14792. });
  14793. }
  14794. .width('100%')
  14795. .padding(16)
  14796. }.margin({ bottom: 18 })
  14797. }
  14798. @Builder
  14799. TPImageBuilder(more: MoreItem): void {
  14800. Row() {
  14801. Image($r('app.media.tuoping'))
  14802. .width(22)
  14803. .height(22)
  14804. .margin({ left: 10, right: 10 })
  14805. Text(more.title)
  14806. .fontSize(16)
  14807. .fontColor(Color.White)
  14808. }
  14809. .width('100%')
  14810. .layoutWeight(1)
  14811. .alignItems(VerticalAlign.Center)
  14812. .justifyContent(FlexAlign.Start)
  14813. }
  14814. private moreItems: MoreItem[] = [
  14815. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  14816. { id: 30, image: $r('sys.symbol.lyrics_square'), title: '歌词' },
  14817. { id: 24, image: $r('sys.symbol.slider_vertical_3'), title: '均衡器' },
  14818. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  14819. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  14820. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  14821. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  14822. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  14823. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  14824. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  14825. { id:20,image: $r("app.media.a_b"), title: 'AB循环' },
  14826. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  14827. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  14828. { id: 4, image: $r('app.media.share2'), title: '分享' },
  14829. { id: 9, image: $r('app.media.volume_white'), title: '音量减弱' },
  14830. { id: 28, image: $r('sys.symbol.speaker_wave_3'), title: '音量增强' },
  14831. { id: 25, image: $r('sys.symbol.ranking'), title: '音乐频谱' },
  14832. { id: 26, image: $r('sys.symbol.eight_diagram'), title: '频谱类型' },
  14833. { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  14834. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  14835. { id : 22, image: $r('sys.symbol.satellite_map'), title: '沉浸式' },
  14836. { id : 23, image: $r('sys.symbol.lightbulb'), title: '点光源效果' },
  14837. { id : 21, image: $r('app.media.kp_music'), title: '背景双边流光' },
  14838. { id : 27, image: $r('sys.symbol.hand'), title: '隔空手势切歌' },
  14839. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  14840. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  14841. ];
  14842. @State isShowBgLiuGUANG: boolean = false;
  14843. @State isShowMoreView: boolean = false;
  14844. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  14845. @State isShowTimeCloseMore: boolean = false
  14846. @State isShowDetailMore: boolean = false
  14847. @State isMusicBGCover: boolean = true
  14848. @State isSavePlayMode: boolean = true
  14849. @State isLyricSetting: boolean = false
  14850. @State isJumpSetting: boolean = false
  14851. @State isShowEdit: boolean = false
  14852. @State showPipLyric: boolean = false
  14853. @State isShowSpectrum: boolean = false//是否显示频谱
  14854. @State spectrumModeIndex: number = 0 //选中的频谱特效索引
  14855. private getEqualizerVolumeBoostRisk(): number {
  14856. const equalizerManager = EqualizerManager.getInstance();
  14857. if (!equalizerManager.enabled) {
  14858. return 0;
  14859. }
  14860. const gainStats = equalizerManager.getCurrentGainStats();
  14861. if (gainStats.maxPositiveGain <= 0 || gainStats.positiveGainSum <= 0) {
  14862. return 0;
  14863. }
  14864. const peakRisk = (gainStats.maxPositiveGain / 12) * 0.65;
  14865. const spreadRisk = (gainStats.positiveGainSum / 24) * 0.35;
  14866. return Math.max(0, Math.min(peakRisk + spreadRisk, 1));
  14867. }
  14868. private getSafeBoostPercent(): number {
  14869. const rawBoostPercent = Math.max(0, Math.min(this.volumeBoostPercent, this.volumeBoostMaxPercent));
  14870. let compressedBoostPercent = rawBoostPercent;
  14871. if (rawBoostPercent <= 150) {
  14872. compressedBoostPercent = rawBoostPercent;
  14873. } else if (rawBoostPercent <= 300) {
  14874. compressedBoostPercent = 150 + (rawBoostPercent - 150) * 0.45;
  14875. } else {
  14876. compressedBoostPercent = 217.5 + (rawBoostPercent - 300) * 0.15;
  14877. }
  14878. const equalizerRisk = this.getEqualizerVolumeBoostRisk();
  14879. if (equalizerRisk <= 0) {
  14880. return compressedBoostPercent;
  14881. }
  14882. const protectedBoostPercent = compressedBoostPercent * (1 - equalizerRisk * 0.45);
  14883. const cappedBoostPercent = 220 - equalizerRisk * 140;
  14884. return Math.max(0, Math.min(protectedBoostPercent, cappedBoostPercent));
  14885. }
  14886. private getVolumeBoostFactor(): number {
  14887. return 1 + this.getSafeBoostPercent() / 100;
  14888. }
  14889. private getCurrentOutputVolume(): number {
  14890. const baseVolume = Math.max(0, Math.min(this.volume, 1));
  14891. const boostedVolume = baseVolume * this.getVolumeBoostFactor();
  14892. const maxOutputVolume = this.getVolumeBoostFactor();
  14893. return Math.max(0, Math.min(boostedVolume, maxOutputVolume));
  14894. }
  14895. private applyCurrentVolume(forceDsfSafeVolume: boolean = false): void {
  14896. if (!this.mIjkMediaPlayer) {
  14897. return;
  14898. }
  14899. if (forceDsfSafeVolume && this.volumeSmall && this.videoUrl.toLowerCase().endsWith('.dsf')) {
  14900. this.mIjkMediaPlayer.setVolume('1', '1');
  14901. return;
  14902. }
  14903. const outputVolume = this.getCurrentOutputVolume();
  14904. this.mIjkMediaPlayer.setVolume(outputVolume.toString(), outputVolume.toString());
  14905. }
  14906. async setRingTone() {
  14907. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  14908. return
  14909. }
  14910. // 确定后的逻辑
  14911. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  14912. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  14913. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  14914. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  14915. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  14916. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  14917. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  14918. , this.videoUrl, this.name).then(res => {
  14919. LogUtil.info('onecold setFlag :' + res);
  14920. });
  14921. }
  14922. doMore(moreId: number) {
  14923. switch (moreId) {
  14924. case 30: //歌词
  14925. this.isLyricSetting = !this.isLyricSetting;
  14926. this.isShowMoreView = false
  14927. break;
  14928. case 3: //详情
  14929. this.isShowDetailMore = !this.isShowDetailMore;
  14930. break;
  14931. case 4: //分享
  14932. if (this.currentSong !== undefined) {
  14933. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  14934. }
  14935. this.isShowMoreView = false
  14936. break;
  14937. case 5: //定时关闭
  14938. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  14939. break;
  14940. case 10: //设为铃声
  14941. this.setRingTone()
  14942. this.isShowMoreView = false
  14943. break;
  14944. case 11: //跳过头尾
  14945. this.isJumpSetting = !this.isJumpSetting;
  14946. break;
  14947. case 13: //倍速
  14948. break;
  14949. case 14: //搜索封面
  14950. if (this.currentSong !== undefined) {
  14951. this.doSearchCover(this.currentSong)
  14952. }
  14953. this.isShowMoreView = false
  14954. break;
  14955. case 15: //编辑标签
  14956. this.initEditFields(this.currentSong)
  14957. this.tempLyricContent = this.lyricContent
  14958. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  14959. this.lyricConStr = this.tempLyricContent
  14960. }
  14961. this.isShowEdit = !this.isShowEdit;
  14962. break;
  14963. case 16: //悬浮歌词
  14964. this.showPipLyric = !this.showPipLyric;
  14965. break;
  14966. case 17: //横屏模式
  14967. if (this.isLandscape) {
  14968. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  14969. } else {
  14970. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  14971. }
  14972. this.isShowMoreView = false
  14973. break;
  14974. case 20://AB循环
  14975. this.isABSheet = !this.isABSheet
  14976. break;
  14977. case 24://均衡器
  14978. this.isEqualizerSheet = !this.isEqualizerSheet
  14979. break;
  14980. }
  14981. }
  14982. //AB循环
  14983. @State isOpenAB:boolean = false
  14984. @State jumpATime:number = 0
  14985. @State jumpBTime:number = 0
  14986. @State isABSheet:boolean = false
  14987. @State isEqualizerSheet: boolean = false
  14988. @State eqApplying: boolean = false
  14989. @State eqAppliedAt: number = 0
  14990. @State eqCurrentPresetName: string = '正常'
  14991. @State eqCurrentEnabled: boolean = false
  14992. @Builder
  14993. ABLoopSheet() {
  14994. ABLoopComptent({
  14995. jumpATime:this.jumpATime,
  14996. jumpBTime:this.jumpBTime,
  14997. onClickAItem: async ()=>{
  14998. if(this.mIjkMediaPlayer){
  14999. this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
  15000. }
  15001. },
  15002. onClickBItem: async ()=>{
  15003. if(this.mIjkMediaPlayer){
  15004. this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
  15005. if(this.jumpBTime<=this.jumpATime){
  15006. ToastUtil.showToast('设置B点时间不能小于A点时间')
  15007. this.jumpBTime = 0
  15008. }
  15009. }
  15010. },
  15011. onCancleButtonClick: async ()=>{
  15012. this.isOpenAB = false
  15013. this.isABSheet = false
  15014. },
  15015. onStartButtonClick: async ()=>{
  15016. if(this.jumpBTime<=this.jumpATime||this.stringForTime(this.jumpATime)==this.stringForTime(this.jumpBTime)){
  15017. ToastUtil.showToast('设置B点时间不能小于或等于A点时间')
  15018. return
  15019. }
  15020. this.isABSheet = false
  15021. this.startABLoop()
  15022. },
  15023. })
  15024. }
  15025. private syncEqualizerUi(): void {
  15026. const equalizerManager = EqualizerManager.getInstance();
  15027. this.eqCurrentEnabled = equalizerManager.enabled;
  15028. this.eqCurrentPresetName = equalizerManager.getPresetDisplayName(equalizerManager.currentPresetId);
  15029. if (this.CONTROL_PlayStatus === PlayStatus.INIT) {
  15030. this.eqAppliedAt = 0;
  15031. }
  15032. }
  15033. private markEqualizerApplied(): void {
  15034. const equalizerManager = EqualizerManager.getInstance();
  15035. this.eqCurrentEnabled = equalizerManager.enabled;
  15036. this.eqCurrentPresetName = equalizerManager.getPresetDisplayName(equalizerManager.currentPresetId);
  15037. this.eqAppliedAt = Date.now();
  15038. this.eqApplying = false;
  15039. }
  15040. private applyEqualizerToCurrentPlayback(): void {
  15041. if (this.eqApplying) {
  15042. return;
  15043. }
  15044. if (this.castControllerWrapper && this.isCastPlaying) {
  15045. ToastUtil.showToast('投播模式暂不支持实时均衡器');
  15046. return;
  15047. }
  15048. if (!this.currentSong || !this.mIjkMediaPlayer) {
  15049. ToastUtil.showToast('暂无可应用的播放');
  15050. return;
  15051. }
  15052. this.eqApplying = true;
  15053. try {
  15054. const equalizerManager = EqualizerManager.getInstance();
  15055. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  15056. this.applyCurrentVolume();
  15057. this.markEqualizerApplied();
  15058. ToastUtil.showToast('均衡器已实时生效');
  15059. } catch (error) {
  15060. this.eqApplying = false;
  15061. Logger.warn(TAG, `heanup 应用均衡器失败: ${(error as Error).message}`);
  15062. }
  15063. }
  15064. @Builder
  15065. private EqualizerApplyStatusBar(): void {
  15066. Row() {
  15067. Column() {
  15068. Text(`均衡器:${this.eqCurrentEnabled ? '开' : '关'} · ${this.eqCurrentPresetName}`)
  15069. .fontSize(12)
  15070. .fontColor($r('app.color.text_color'))
  15071. Text(this.eqAppliedAt > 0 ? '当前播放:已生效' : '当前播放:未应用')
  15072. .fontSize(10)
  15073. .fontColor(this.eqAppliedAt > 0 ? this.themeColor : Color.Gray)
  15074. }
  15075. .alignItems(HorizontalAlign.Start)
  15076. Blank()
  15077. Button('重新应用')
  15078. .fontSize(12)
  15079. .fontColor(Color.White)
  15080. .backgroundColor('#666666')
  15081. .height(28)
  15082. .padding({ left: 14, right: 14 })
  15083. .borderRadius(14)
  15084. .enabled(!this.eqApplying && this.CONTROL_PlayStatus !== PlayStatus.INIT)
  15085. .onClick(() => {
  15086. this.applyEqualizerToCurrentPlayback();
  15087. })
  15088. }
  15089. .width('100%')
  15090. .padding({ left: 12, right: 12, top: 8, bottom: 8 })
  15091. .backgroundColor($r('app.color.settings_background_main'))
  15092. .borderRadius(12)
  15093. }
  15094. @Builder
  15095. EqualizerSheet() {
  15096. Column() {
  15097. Column() {
  15098. EqualizerViewWithCallback({
  15099. onEqualizerChanged: () => {
  15100. this.syncEqualizerUi();
  15101. if (this.mIjkMediaPlayer) {
  15102. const equalizerManager = EqualizerManager.getInstance();
  15103. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  15104. this.applyCurrentVolume();
  15105. this.markEqualizerApplied();
  15106. }
  15107. }
  15108. })
  15109. }
  15110. .margin({ top: 8 })
  15111. Column() {
  15112. this.EqualizerApplyStatusBar()
  15113. }
  15114. .margin({ top: 8 })
  15115. }
  15116. .padding({ left: 12, right: 12, bottom: 20 })
  15117. .width('100%')
  15118. }
  15119. //开始AB循环
  15120. startABLoop(){
  15121. if(this.mIjkMediaPlayer){
  15122. this.seekTo(this.jumpATime+'')
  15123. this.isOpenAB = true
  15124. }
  15125. }
  15126. /**
  15127. * 切换横竖屏
  15128. *
  15129. */
  15130. setOrientation(orientation: number) {
  15131. this.windowClass.setPreferredOrientation(orientation).then(() => {
  15132. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  15133. }).catch((err: BusinessError) => {
  15134. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  15135. });
  15136. }
  15137. /**
  15138. * 画中画功能(悬浮歌词功能)
  15139. *
  15140. */
  15141. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  15142. pipController?: PiPWindow.PiPController;
  15143. navigationId: string = '';
  15144. @State curState: string = '';
  15145. @State curError: ResourceStr = '';
  15146. @State pipBg: string = '#E8E8E8'
  15147. @State buttonAction: string = '';
  15148. //开启画中画功能
  15149. async startPip() {
  15150. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  15151. if (!this.pipController) {
  15152. await this.createPipController();
  15153. }
  15154. if (!this.pipController) {
  15155. Logger.info(`[${TAG}] pipController create error`);
  15156. return;
  15157. }
  15158. await this.pipController.startPiP();
  15159. }
  15160. async stopPip() {
  15161. if (!this.pipController) {
  15162. Logger.info(`[${TAG}] pipController is not exist`);
  15163. return;
  15164. }
  15165. this.isOpenPip = false
  15166. await this.pipController.stopPiP();
  15167. }
  15168. async createPipController() {
  15169. this.pipController = await PiPWindow.create({
  15170. context: getContext(this),
  15171. componentController: this.xcomponentController,
  15172. navigationId: this.navigationId,
  15173. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  15174. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  15175. customUIController: this.nodeController,
  15176. });
  15177. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  15178. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  15179. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  15180. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  15181. this.onStateChange(state, reason);
  15182. });
  15183. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  15184. this.onActionEvent(event, status);
  15185. });
  15186. }
  15187. destroyPipController() {
  15188. if (!this.pipController) {
  15189. return;
  15190. }
  15191. this.pipController.off('stateChange');
  15192. this.pipController.off('controlPanelActionEvent');
  15193. this.pipController = undefined;
  15194. }
  15195. onStateChange(state: PiPWindow.PiPState, reason: string) {
  15196. switch (state) {
  15197. case PiPWindow.PiPState.ABOUT_TO_START:
  15198. this.curState = 'ABOUT_TO_START';
  15199. this.curError = $r('app.string.current_error_hint');
  15200. break;
  15201. case PiPWindow.PiPState.STARTED:
  15202. this.curState = 'STARTED';
  15203. this.curError = $r('app.string.current_error_hint');
  15204. break;
  15205. case PiPWindow.PiPState.ABOUT_TO_STOP:
  15206. this.curState = 'ABOUT_TO_STOP';
  15207. this.curError = $r('app.string.current_error_hint');
  15208. break;
  15209. case PiPWindow.PiPState.STOPPED:
  15210. this.curState = 'STOPPED';
  15211. this.curError = $r('app.string.current_error_hint');
  15212. this.stopPip()
  15213. this.destroyPipController()
  15214. break;
  15215. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  15216. this.curState = 'ABOUT_TO_RESTORE';
  15217. this.curError = $r('app.string.current_error_hint');
  15218. break;
  15219. case PiPWindow.PiPState.ERROR:
  15220. this.curState = 'ERROR';
  15221. this.curError = reason;
  15222. break;
  15223. default:
  15224. break;
  15225. }
  15226. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  15227. }
  15228. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  15229. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  15230. switch (event) {
  15231. case 'playbackStateChanged':
  15232. if (status === 0) {
  15233. this.pause();
  15234. } else {
  15235. console.info('onecold startPlayOrResumePlay 9869')
  15236. this.startPlayOrResumePlay();
  15237. }
  15238. break;
  15239. case 'nextVideo':
  15240. // 切换到下一个视频
  15241. this.playNext().catch(() => {
  15242. Logger.error('heanup onActionEvent playNext', `播放下一首失败`);
  15243. });
  15244. break;
  15245. case 'previousVideo':
  15246. // 切换到上一个视频
  15247. this.playPrevious().catch(() => {
  15248. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败`);
  15249. });
  15250. break;
  15251. case 'previousVideo':
  15252. // 切换到上一个视频
  15253. this.playPrevious().catch(() => {
  15254. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败:`);
  15255. });
  15256. break;
  15257. default:
  15258. }
  15259. this.buttonAction = event + `-status:${status}`;
  15260. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  15261. }
  15262. /**
  15263. * 画中画功能(悬浮歌词功能)结束
  15264. *
  15265. */
  15266. async doSearchCover(item: VideoItem,title?:string,artist?:string): Promise<string> {
  15267. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  15268. this.isShowMoreView = false;
  15269. this.showTipsDialog();
  15270. return ''; // Return empty string when no API is configured
  15271. }
  15272. if (!item) {
  15273. return ''; // Return empty string if item is undefined
  15274. }
  15275. const titleS = title||item?.name || '';
  15276. const artistS = artist||item?.artist || ''; // Use empty string if artist is missing
  15277. return this.searchCover(item, titleS, artistS, true); // Await is not needed here as we return the promise directly
  15278. }
  15279. /**
  15280. *api搜索封面
  15281. *item,根据title和artist
  15282. */
  15283. searchCover(item: VideoItem, title: string, artist: string, markAsCustomCover: boolean = false): Promise<string> {
  15284. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  15285. LogUtil.debug("onecold res =" + res);
  15286. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  15287. if (item.filePath == this.currentSong?.filePath) {
  15288. if (this.currentSong) {
  15289. mergeCoverWithPriority(this.currentSong, res, markAsCustomCover ? 1 : 0);
  15290. this.cover = this.currentSong.pixelMapPath || res;
  15291. }
  15292. }
  15293. if (isRemoteCloudType(item.type)) {
  15294. mergeCoverWithPriority(item, res, markAsCustomCover ? 1 : 0);
  15295. this.syncRemoteManagerSong(item);
  15296. try {
  15297. await this.persistRemoteMetadataToDb(item);
  15298. this.emitRemoteMetadataUpdated(item);
  15299. } catch (error) {
  15300. Logger.error(TAG, `searchCover 持久化网盘封面失败: ${(error as Error).message}`);
  15301. }
  15302. } else {
  15303. // Update pixel map path but always return res regardless of success
  15304. if (markAsCustomCover) {
  15305. item.isCustomCover = 1;
  15306. this.table.updateCustomCoverPath(item.filePath, res, (success: boolean, error?: string) => {
  15307. if (success) {
  15308. this.doUpdateData();
  15309. console.log("onecold 更新音乐封面成功,数据库已同步");
  15310. } else {
  15311. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  15312. }
  15313. });
  15314. } else {
  15315. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  15316. if (success) {
  15317. this.doUpdateData();
  15318. console.log("onecold 更新音乐封面成功,数据库已同步");
  15319. } else {
  15320. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  15321. }
  15322. });
  15323. }
  15324. }
  15325. LogUtil.debug("onecold this.cover =" + this.cover);
  15326. }
  15327. return res; // Always return res regardless of updatePixelMapPath result
  15328. });
  15329. }
  15330. @State jumpTopTime: number = 0
  15331. @State jumpEndTime: number = 0
  15332. @State isOpenJump: boolean = false
  15333. @Builder
  15334. JumpTopEndSheet() {
  15335. Scroll() {
  15336. Column() {
  15337. Column() {
  15338. Text('仅对本播放列表有效')
  15339. .fontSize(16)
  15340. .fontColor($r('app.color.text_color'))
  15341. // 跳过头尾
  15342. Column() {
  15343. Row() {
  15344. Text('跳过片头:')
  15345. .fontSize(16)
  15346. .fontColor($r('app.color.text_color'))
  15347. Text(this.jumpTopTime + 's')
  15348. .fontSize(16)
  15349. .fontColor($r('app.color.text_color'))
  15350. }
  15351. .margin({ bottom: 5 })
  15352. Row() {
  15353. Slider({
  15354. value: this.jumpTopTime,
  15355. min: 0,
  15356. max: 120,
  15357. step: 1,
  15358. style: SliderStyle.OutSet
  15359. })
  15360. .blockColor(this.themeColor)
  15361. .trackColor($r('app.color.speed_text_color'))
  15362. .selectedColor(Color.White)
  15363. .trackThickness(8)
  15364. .onChange((value: number) => {
  15365. this.jumpTopTime = value;
  15366. })
  15367. .width('85%')
  15368. }
  15369. .alignItems(VerticalAlign.Top)
  15370. }
  15371. .margin({ top: 10, bottom: 10 })
  15372. // 跳过头尾
  15373. Column() {
  15374. Row() {
  15375. Text('跳过片尾:')
  15376. .fontSize(16)
  15377. .fontColor($r('app.color.text_color'))
  15378. Text(this.jumpEndTime + 's')
  15379. .fontSize(16)
  15380. .fontColor($r('app.color.text_color'))
  15381. }
  15382. .margin({ bottom: 5 })
  15383. Row() {
  15384. Slider({
  15385. value: this.jumpEndTime,
  15386. min: 0,
  15387. max: 120,
  15388. step: 1,
  15389. style: SliderStyle.OutSet
  15390. })
  15391. .blockColor(this.themeColor)
  15392. .trackColor($r('app.color.speed_text_color'))
  15393. .selectedColor(Color.White)
  15394. .trackThickness(8)
  15395. .onChange((value: number) => {
  15396. this.jumpEndTime = value;
  15397. })
  15398. .width('85%')
  15399. }
  15400. .alignItems(VerticalAlign.Top)
  15401. }
  15402. .margin({ top: 10, bottom: 10 })
  15403. Row() {
  15404. Button('保存设置')
  15405. .fontColor(Color.White)
  15406. .layoutWeight(1)
  15407. .height(40)
  15408. .width(80)
  15409. .backgroundColor(this.themeColor)
  15410. .stateEffect(true)
  15411. .margin({ left: 0, bottom: 20 })
  15412. .onClick(async () => {
  15413. if (!Utility.isNoble()) {
  15414. this.isJumpSetting = false
  15415. this.isShowMoreView = false
  15416. this.showVipDialog()
  15417. return
  15418. }
  15419. if (this.currentSong === undefined) {
  15420. return
  15421. }
  15422. if (this.modeType === 0) {
  15423. let parentPath = FileUtil.getParentPath(this.videoUrl)
  15424. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  15425. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  15426. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  15427. } else if (this.modeType === 1) { //媒体库
  15428. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  15429. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  15430. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  15431. } else if (this.modeType === 2) { //艺术家
  15432. if (this.currentSong?.artist) {
  15433. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  15434. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  15435. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  15436. }
  15437. } else if (this.modeType === 3) { //专辑
  15438. if (this.currentSong?.album) {
  15439. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  15440. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  15441. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  15442. }
  15443. }
  15444. ToastUtil.showShort("保存成功")
  15445. this.isJumpSetting = false
  15446. })
  15447. }
  15448. .margin({
  15449. left: 38,
  15450. right: 38,
  15451. top: 10,
  15452. bottom: 10
  15453. })
  15454. .width(120)
  15455. .height(50)
  15456. }
  15457. }
  15458. }
  15459. .width('100%')
  15460. .height('100%')
  15461. }
  15462. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  15463. private onStateVastChange(state: AVCastPickerState) {
  15464. if (state == AVCastPickerState.STATE_APPEARING) {
  15465. console.log('The picker starts showing.');
  15466. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  15467. console.log('The picker finishes presenting.');
  15468. }
  15469. }
  15470. private showSelectLyric() {
  15471. DialogHelper.showActionSheetDialog({
  15472. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  15473. // sheets: ["本地歌词", "搜索歌词"],
  15474. sheets: [
  15475. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  15476. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  15477. ],
  15478. maskColor: Color.Transparent,
  15479. backgroundColor: $r('app.color.bg_card'),
  15480. transition: AnimationHelper.transitionInDown(666),
  15481. onAction: (index) => {
  15482. switch (index) {
  15483. case 0:
  15484. this.callFilePickerSelectFileForLyric()
  15485. break;
  15486. case 1:
  15487. if (StrUtil.isNotEmpty(this.videoUrl)) {
  15488. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  15489. this.initLyric(lyricPath);
  15490. }
  15491. break;
  15492. }
  15493. }
  15494. })
  15495. }
  15496. // 拉起picker选择文件管理器
  15497. async callFilePickerSelectFileForLyric(): Promise<void> {
  15498. try {
  15499. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  15500. DocumentSelectOptions.maxSelectNumber = 1
  15501. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  15502. let documentPicker = new picker.DocumentViewPicker();
  15503. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  15504. Logger.info(TAG,
  15505. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  15506. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  15507. this.saveVideoDatasLyric(DocumentSelectResult)
  15508. }
  15509. }).catch((err: BusinessError) => {
  15510. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  15511. });
  15512. } catch (err) {
  15513. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  15514. }
  15515. }
  15516. async saveVideoDatasLyric(uris: string[]) {
  15517. if (ArrayUtil.isEmpty(uris)) {
  15518. return
  15519. }
  15520. let newUris: string[] = [];
  15521. for (let i = 0; i < uris.length; i++) {
  15522. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  15523. Logger.info(TAG, 'filePath uri: ' + filePath);
  15524. newUris.push(filePath)
  15525. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  15526. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  15527. fileIo.copyFileSync(file.fd, file2.fd)
  15528. fileIo.closeSync(file);
  15529. fileIo.closeSync(file2);
  15530. this.initLyric(filePath,false,false,true)
  15531. }
  15532. }
  15533. private initDelayPlay(context: object) {
  15534. this.mContext = context;
  15535. }
  15536. startPipLyric() {
  15537. if (this.pipController) {
  15538. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  15539. PiPWindow.PiPControlStatus.PLAY);
  15540. }
  15541. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  15542. if (this.isOpenPip) {
  15543. this.startPip()
  15544. } else {
  15545. this.stopPip()
  15546. }
  15547. }
  15548. //startOffset 从cue分轨时间开始播
  15549. private startPlayOrResumePlay(startOffset?:number) {
  15550. let finalStartOffset = startOffset
  15551. if ((finalStartOffset === undefined || finalStartOffset === null) && this.currentSong && isCueSplitItem(this.currentSong)) {
  15552. finalStartOffset = 0
  15553. }
  15554. //新版本ijkplayer可以直接播放dsf歌,不需要转格式了。所以注释掉代码
  15555. //针对dsf文件高采样率,统一转wav播放
  15556. // const sampleRate = this.currentSong?.sampleRate||0
  15557. // if(this.videoUrl.toLowerCase().endsWith('.dsf')&&sampleRate>=441000){
  15558. // console.info('onecold 采样率 ='+sampleRate)
  15559. // let newDsfPath = this.context.filesDir + '/'+FileUtil.getFileName(this.videoUrl)+'.wav'
  15560. // console.info('onecold newDsfPath ='+newDsfPath)
  15561. // if(!FileUtil.accessSync(newDsfPath)){
  15562. // const task = new taskpool.Task(convertDsfToWav,this.videoUrl,newDsfPath);
  15563. // taskpool.execute(task, taskpool.Priority.HIGH).then((data)=>{
  15564. // this.videoUrl = newDsfPath
  15565. // this.startPlay(startOffset)
  15566. // }).catch((e:object)=>{
  15567. // console.info("task1 catch e: " + e);
  15568. // })
  15569. // }else{
  15570. // this.videoUrl = newDsfPath
  15571. // this.startPlay(startOffset)
  15572. // }
  15573. //
  15574. // }else{
  15575. // this.startPlay(startOffset)
  15576. // }
  15577. this.startPlay(finalStartOffset)
  15578. // 仅当前播放的是网盘歌曲时,才提前缓存下一首
  15579. // 排除用户拖动进度条的情况
  15580. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !this.isSeekTo) {
  15581. void this.preloadNextSongInternal();
  15582. }
  15583. }
  15584. startPlay(startOffset?:number) {
  15585. this.startPipLyric()
  15586. this.mDestroyPage = false;
  15587. this.animationState = AnimationStatus.Running
  15588. LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  15589. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  15590. this.stopProgressTask();
  15591. this.startProgressTask();
  15592. this.clearInitialSeekGuardTimer();
  15593. this.activePlaybackMemoryKey = this.getPlaybackMemoryKey();
  15594. this.remoteRestoreSeekToken++;
  15595. const shouldMemoryPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)
  15596. || (this.isMemoryLastPlay && this.isFirstStartPlay);
  15597. this.pendingMemorySeekPosition = shouldMemoryPlay ? PreferencesUtil.getNumberSync(this.getPlaybackMemoryKey(), 0) : 0;
  15598. const isRemoteStreamSong = this.currentSong && isRemoteCloudType(this.currentSong.type) &&
  15599. this.videoUrl.includes('://');
  15600. this.waitInitialSeekBeforeStart = !!isRemoteStreamSong && this.pendingMemorySeekPosition > 0;
  15601. // 网盘歌曲起播阶段统一显示加载圈,prepared/首帧后再收起
  15602. this.isPlayerLoading = !!isRemoteStreamSong;
  15603. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  15604. Logger.info(
  15605. TAG,
  15606. `[remote-play] startPlay type=${this.currentSong.type}, memory=${this.pendingMemorySeekPosition}, ` +
  15607. `waitInitial=${this.waitInitialSeekBeforeStart}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  15608. );
  15609. }
  15610. this.play(this.videoUrl.toString(),startOffset);
  15611. }
  15612. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  15613. this.mIjkMediaPlayer.start();
  15614. this.setProgress()
  15615. this.CONTROL_PlayStatus = PlayStatus.PLAY
  15616. }
  15617. this.setIsPlaying(true)
  15618. this.updateSessionPlayState(true)
  15619. this.watchStatus();
  15620. this.updateLastPlayTimeStr(this.videoUrl)
  15621. }
  15622. updateLastPlayTimeStr(filePath: string) {
  15623. const activeSong = this.currentSong;
  15624. let targetFilePath = this.currentSong?.filePath || filePath;
  15625. if (activeSong && isRemoteCloudType(activeSong.type)) {
  15626. const remoteStoragePath = this.resolveRemoteStoragePath(activeSong);
  15627. if (remoteStoragePath) {
  15628. targetFilePath = remoteStoragePath;
  15629. }
  15630. Logger.info(`heanup 检测到网络音频播放,改为更新远程歌曲最近播放: ${targetFilePath}`)
  15631. }
  15632. if (!targetFilePath) {
  15633. Logger.warn(TAG, `更新最近播放时间失败,目标路径为空: ${filePath}`);
  15634. return;
  15635. }
  15636. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  15637. const applyHistoryUpdate = (): void => {
  15638. this.table.updateLastPlayedStrByFilePath(targetFilePath, lastPlayTime, (success: boolean, error?: string) => {
  15639. if (success) {
  15640. if (activeSong && this.currentSong?.filePath === activeSong.filePath) {
  15641. this.currentSong.lastPlayedStr = lastPlayTime
  15642. this.currentSong.playCount = (this.currentSong.playCount || 0) + 1
  15643. }
  15644. this.getHistoryList(false)
  15645. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  15646. return;
  15647. }
  15648. if (activeSong && isRemoteCloudType(activeSong.type)) {
  15649. Logger.warn(TAG, `远程歌曲最近播放更新失败,准备补入库后重试: ${targetFilePath}, error=${error}`);
  15650. this.persistRemoteMetadataToDb(activeSong)
  15651. .then(() => {
  15652. this.table.updateLastPlayedStrByFilePath(targetFilePath, lastPlayTime, (retrySuccess: boolean,
  15653. retryError?: string) => {
  15654. if (retrySuccess) {
  15655. if (activeSong && this.currentSong?.filePath === activeSong.filePath) {
  15656. this.currentSong.lastPlayedStr = lastPlayTime
  15657. this.currentSong.playCount = (this.currentSong.playCount || 0) + 1
  15658. }
  15659. this.getHistoryList(false)
  15660. Logger.info(TAG, `远程歌曲最近播放补入库后更新成功: ${targetFilePath}`);
  15661. } else {
  15662. Logger.error(TAG,
  15663. `远程歌曲最近播放补入库后仍更新失败: ${targetFilePath}, error=${retryError}`);
  15664. }
  15665. });
  15666. })
  15667. .catch((persistError: Error) => {
  15668. Logger.error(TAG,
  15669. `远程歌曲最近播放补入库失败: ${targetFilePath}, error=${persistError.message}`);
  15670. });
  15671. return;
  15672. }
  15673. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  15674. });
  15675. };
  15676. applyHistoryUpdate();
  15677. }
  15678. private completionNum(num: number): string | number {
  15679. if (num < 10) {
  15680. return '0' + num;
  15681. } else {
  15682. return num;
  15683. }
  15684. }
  15685. private parseDurationToMs(duration?: string): number {
  15686. if (!duration) {
  15687. return 0;
  15688. }
  15689. const parts = duration.split(':').map((item) => Number(item));
  15690. if (parts.some((item) => Number.isNaN(item))) {
  15691. return 0;
  15692. }
  15693. if (parts.length === 2) {
  15694. return Math.floor((parts[0] * 60 + parts[1]) * 1000);
  15695. }
  15696. if (parts.length === 3) {
  15697. return Math.floor((parts[0] * 3600 + parts[1] * 60 + parts[2]) * 1000);
  15698. }
  15699. return 0;
  15700. }
  15701. private sanitizePlaybackUrl(url?: string): string {
  15702. if (!url) {
  15703. return '';
  15704. }
  15705. let sanitized = url.replace(/(access_token=)[^&]+/ig, '$1***');
  15706. sanitized = sanitized.replace(/(refresh_token=)[^&]+/ig, '$1***');
  15707. sanitized = sanitized.replace(/(Authorization=)[^&]+/ig, '$1***');
  15708. if (sanitized.length > 220) {
  15709. return `${sanitized.substring(0, 220)}...`;
  15710. }
  15711. return sanitized;
  15712. }
  15713. private sanitizePlaylistDebugPath(path?: string): string {
  15714. if (!path) {
  15715. return '';
  15716. }
  15717. return path.length > 48 ? `...${path.substring(path.length - 48)}` : path;
  15718. }
  15719. private buildSongDebugItem(item?: VideoItem): string {
  15720. if (!item) {
  15721. return 'unknown';
  15722. }
  15723. const title = item.name || item.fileName || '未知歌曲';
  15724. return `${title}|type=${item.type}|acc=${item.webdav_account_id || ''}|path=${this.sanitizePlaylistDebugPath(item.filePath)}`;
  15725. }
  15726. private buildSongListDebugLog(items: VideoItem[], limit: number = 5): string {
  15727. if (!items || items.length === 0) {
  15728. return '[]';
  15729. }
  15730. const parts: string[] = [];
  15731. const maxCount = Math.min(limit, items.length);
  15732. for (let i = 0; i < maxCount; i++) {
  15733. parts.push(this.buildSongDebugItem(items[i]));
  15734. }
  15735. return `[${parts.join('; ')}](${items.length})`;
  15736. }
  15737. private buildPathListDebugLog(paths: string[], limit: number = 5): string {
  15738. if (!paths || paths.length === 0) {
  15739. return '[]';
  15740. }
  15741. const parts: string[] = [];
  15742. const maxCount = Math.min(limit, paths.length);
  15743. for (let i = 0; i < maxCount; i++) {
  15744. parts.push(this.sanitizePlaylistDebugPath(paths[i]));
  15745. }
  15746. return `[${parts.join('; ')}](${paths.length})`;
  15747. }
  15748. private async dispatchPlaylistPlayRequest(playlistData: PlaylistPlayRequest): Promise<void> {
  15749. clearPendingPlaylistPlay();
  15750. Logger.info(
  15751. TAG,
  15752. `[remote-debug] dispatchPlaylistPlayRequest id=${playlistData.playlistId}, name=${playlistData.playlistName}, ` +
  15753. `songCount=${playlistData.songCount}, startIndex=${playlistData.startIndex}, playType=${playlistData.playType ?? -1}, ` +
  15754. `paths=${this.buildPathListDebugLog(playlistData.songFilePaths)}`
  15755. );
  15756. if (playlistData.playType !== undefined) {
  15757. this.applyRequestedPlayType(playlistData.playType);
  15758. }
  15759. await this.handlePlaylistPlayRequest(
  15760. playlistData.playlistId,
  15761. playlistData.playlistName,
  15762. playlistData.songFilePaths,
  15763. playlistData.startIndex,
  15764. playlistData.isJump ?? false,
  15765. playlistData.songCount
  15766. );
  15767. }
  15768. private async resolvePlaybackUrlForCurrentSong(source: string): Promise<string | null> {
  15769. const song = this.currentSong;
  15770. if (!song) {
  15771. Logger.warn(TAG, `[play-url] skip source=${source}, currentSong is null`);
  15772. return null;
  15773. }
  15774. const expectedFilePath = song.filePath || '';
  15775. const requestSerial = ++this.playbackUrlRequestSerial;
  15776. Logger.info(
  15777. TAG,
  15778. `[play-url] begin serial=${requestSerial}, source=${source}, song=${song.name}, path=${expectedFilePath}`
  15779. );
  15780. const resolvedUrl = await setVideoUrlForSong(song, {
  15781. context: this.context,
  15782. autoParseMusicName: this.autoParseMusicName
  15783. });
  15784. const currentFilePath = this.currentSong?.filePath || '';
  15785. if (requestSerial !== this.playbackUrlRequestSerial || currentFilePath !== expectedFilePath) {
  15786. Logger.warn(
  15787. TAG,
  15788. `[play-url] stale serial=${requestSerial}, source=${source}, expected=${expectedFilePath}, ` +
  15789. `current=${currentFilePath}, drop=${this.sanitizePlaybackUrl(resolvedUrl)}`
  15790. );
  15791. return null;
  15792. }
  15793. Logger.info(
  15794. TAG,
  15795. `[play-url] apply serial=${requestSerial}, source=${source}, song=${song.name}, ` +
  15796. `url=${this.sanitizePlaybackUrl(resolvedUrl)}`
  15797. );
  15798. return resolvedUrl;
  15799. }
  15800. private beginSeekTrace(source: string, requestMs: number): void {
  15801. this.lastSeekSource = source;
  15802. this.lastSeekRequestMs = requestMs;
  15803. this.seekTraceUntilTs = Date.now() + this.seekTraceLogWindowMs;
  15804. this.lastSeekTraceLogTs = 0;
  15805. }
  15806. private isSeekTraceActive(): boolean {
  15807. return this.seekTraceUntilTs > 0 && Date.now() <= this.seekTraceUntilTs;
  15808. }
  15809. private logSeekTrace(stage: string, position?: number, playerDuration?: number, force: boolean = false): void {
  15810. if (!force && !this.isSeekTraceActive()) {
  15811. return;
  15812. }
  15813. const now = Date.now();
  15814. if (!force && now - this.lastSeekTraceLogTs < this.seekTraceLogIntervalMs) {
  15815. return;
  15816. }
  15817. this.lastSeekTraceLogTs = now;
  15818. const currentPosition = typeof position === 'number' ? position : this.mIjkMediaPlayer.getCurrentPosition();
  15819. const resolvedPlayerDuration = typeof playerDuration === 'number' ? playerDuration : this.mIjkMediaPlayer.getDuration();
  15820. Logger.info(
  15821. TAG,
  15822. `[seek-trace] stage=${stage}, source=${this.lastSeekSource || 'unknown'}, req=${this.lastSeekRequestMs}, ` +
  15823. `current=${currentPosition}, playerDuration=${resolvedPlayerDuration}, uiDuration=${this.duration}, ` +
  15824. `activeDuration=${this.getActiveDuration()}, isPlaying=${this.mIjkMediaPlayer.isPlaying()}, ` +
  15825. `isSeekTo=${this.isSeekTo}, waitInitial=${this.waitInitialSeekBeforeStart}, ` +
  15826. `songType=${this.currentSong?.type ?? -1}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  15827. );
  15828. }
  15829. private shouldShowSeekBlockedToast(source: string): boolean {
  15830. return source === 'top-progress-slider' ||
  15831. source === 'landscape-progress-slider' ||
  15832. source === 'fast-forward-button' ||
  15833. source === 'rewind-button' ||
  15834. source === 'session-fast-forward' ||
  15835. source === 'session-rewind' ||
  15836. source === 'session-seek';
  15837. }
  15838. private handleBlockedSeek(seekPos: number, source: string): boolean {
  15839. const decision = resolveSeekGuardDecision(this.videoUrl, seekPos, this.currentSong?.type);
  15840. if (decision.allow) {
  15841. return false;
  15842. }
  15843. Logger.warn(
  15844. TAG,
  15845. `[seek] blocked source=${source}, target=${seekPos}, reason=${decision.reason}, ` +
  15846. `url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  15847. );
  15848. if (this.shouldShowSeekBlockedToast(source) && StrUtil.isNotEmpty(decision.toastMessage)) {
  15849. ToastUtil.showToast(decision.toastMessage);
  15850. }
  15851. if (this.waitInitialSeekBeforeStart) {
  15852. this.finishInitialSeekWait(`blocked-${decision.reason}`, true);
  15853. } else {
  15854. this.hideLoadIng();
  15855. }
  15856. this.isSeekTo = false;
  15857. this.logSeekTrace(`seek-blocked-${decision.reason}`, undefined, undefined, true);
  15858. return true;
  15859. }
  15860. private stringForTime(timeMs: number): string {
  15861. let totalSeconds: number | string = (timeMs / 1000);
  15862. let newSeconds: number | string = totalSeconds % 60;
  15863. let minutes: number | string = (totalSeconds / 60) % 60;
  15864. let hours: number | string = totalSeconds / 3600;
  15865. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  15866. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  15867. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  15868. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  15869. if (this.isCurrentTime) {
  15870. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  15871. this.oldSeconds = newSeconds
  15872. } else {
  15873. newSeconds = this.oldSeconds
  15874. }
  15875. }
  15876. newSeconds = this.completionNum(newSeconds);
  15877. if (hours > 0) {
  15878. return hours + ":" + minutes + ":" + newSeconds;
  15879. } else {
  15880. return minutes + ":" + newSeconds;
  15881. }
  15882. }
  15883. private getPlayerSwiperDisplayCount(): number {
  15884. return new BreakpointType<number>({
  15885. sm: 1,
  15886. md: 2,
  15887. lg: 2,
  15888. xl: 2,
  15889. xxl: 2
  15890. }).getValue(this.currentBreakpoint) ?? 1
  15891. }
  15892. private shouldUpdateMainLyricPanel(): boolean {
  15893. return this.getPlayerSwiperDisplayCount() > 1 || this.currentSwiperIndex === 1
  15894. }
  15895. private getActivePlaybackPositionMs(): number {
  15896. if (this.castControllerWrapper && this.isCastPlaying) {
  15897. return this.currentTime2 * 1000
  15898. }
  15899. return this.mIjkMediaPlayer.getCurrentPosition()
  15900. }
  15901. private syncLyricPositionNow(): void {
  15902. const position = this.getActivePlaybackPositionMs()
  15903. if (position < 0) {
  15904. return
  15905. }
  15906. this.updateLyricPosition(position + this.timeOffset * 1000)
  15907. }
  15908. private updateLyricPosition(lyricPosition: number): void {
  15909. if (!this.isAppForeground || !this.isPageVisible) {
  15910. return;
  15911. }
  15912. const shouldUpdateMainLyric = this.shouldUpdateMainLyricPanel()
  15913. const shouldUpdatePipLyric = this.showPipLyric
  15914. const shouldUpdateSingleLineLyric = this.isShowSingleLineLyric
  15915. if (!shouldUpdateMainLyric && !shouldUpdatePipLyric && !shouldUpdateSingleLineLyric) {
  15916. return
  15917. }
  15918. if (!Number.isNaN(this.lastLyricRenderPosition) &&
  15919. Math.abs(lyricPosition - this.lastLyricRenderPosition) < this.lyricUpdateMinDeltaMs) {
  15920. return;
  15921. }
  15922. this.lastLyricRenderPosition = lyricPosition;
  15923. if (shouldUpdateMainLyric) {
  15924. this.lyricController.updatePosition(lyricPosition);
  15925. }
  15926. if (shouldUpdatePipLyric) {
  15927. this.lyricControllerXF.updatePosition(lyricPosition);
  15928. }
  15929. if (shouldUpdateSingleLineLyric) {
  15930. this.lyricControllerSingle.updatePosition(lyricPosition);
  15931. }
  15932. }
  15933. private setProgress() {
  15934. if (this.castControllerWrapper && this.isCastPlaying) {
  15935. return;
  15936. }
  15937. const shouldRefreshUi = this.isAppForeground && this.isPageVisible;
  15938. const rawPosition = this.mIjkMediaPlayer.getCurrentPosition();
  15939. const rawDuration = this.mIjkMediaPlayer.getDuration();
  15940. const cueTrackItem = this.currentSong && isCueSplitItem(this.currentSong) ? this.currentSong : undefined;
  15941. const cueTrackStartOffset = cueTrackItem ? getCueTrackStartOffset(cueTrackItem) : 0;
  15942. const cueTrackEndOffset = cueTrackItem ? getCueTrackEndOffset(cueTrackItem) : 0;
  15943. const cueTrackDuration = cueTrackItem ? getCueTrackDuration(cueTrackItem) : 0;
  15944. let position = rawPosition;
  15945. let duration = rawDuration;
  15946. if (cueTrackItem) {
  15947. position = Math.max(0, rawPosition - cueTrackStartOffset);
  15948. if (cueTrackDuration > 0) {
  15949. duration = cueTrackDuration;
  15950. } else if (cueTrackEndOffset > cueTrackStartOffset) {
  15951. duration = cueTrackEndOffset - cueTrackStartOffset;
  15952. } else if (rawDuration > cueTrackStartOffset) {
  15953. duration = rawDuration - cueTrackStartOffset;
  15954. }
  15955. if (duration > 0 && position > duration) {
  15956. position = duration;
  15957. }
  15958. }
  15959. if (duration <= 0 && this.duration > 0) {
  15960. duration = this.duration;
  15961. }
  15962. let pos = 0;
  15963. if (duration > 0) {
  15964. this.slideEnable = true;
  15965. let curPercent = position / duration;
  15966. pos = curPercent * 100;
  15967. if (shouldRefreshUi) {
  15968. if (pos > this.PROGRESS_MAX_VALUE) {
  15969. this.progressValue = this.PROGRESS_MAX_VALUE
  15970. } else {
  15971. this.progressValue = pos;
  15972. }
  15973. }
  15974. }
  15975. this.logSeekTrace('progress-tick', position, duration);
  15976. // LogUtils.getInstance()
  15977. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  15978. if (shouldRefreshUi) {
  15979. this.totalTime = this.stringForTime(duration);
  15980. }
  15981. if (position > duration) {
  15982. position = duration;
  15983. }
  15984. if (shouldRefreshUi) {
  15985. const lyricPosition = (cueTrackItem ? rawPosition : position) + this.timeOffset * 1000;
  15986. this.isCurrentTime = true;
  15987. this.updateLyricPosition(lyricPosition);
  15988. // 蓝牙歌词更新逻辑
  15989. if (this.bluetoothLyricEnabled && this.isBluetoothConnected && this.lyricContent && this.currentSong) {
  15990. const currentLyricLine = LyricUtil.getCurrentLyricLine(this.lyricContent, lyricPosition);
  15991. // 仅在歌词行变化时更新,避免频繁调用
  15992. if (currentLyricLine !== this.lastBluetoothLyricLine) {
  15993. this.lastBluetoothLyricLine = currentLyricLine;
  15994. this.avSessionController.updateBluetoothLyric(
  15995. currentLyricLine,
  15996. this.currentSong.name || '',
  15997. this.currentSong.artist || '',
  15998. this.bluetoothLyricMode
  15999. );
  16000. }
  16001. }
  16002. this.currentTime = this.stringForTime(position);
  16003. this.isCurrentTime = false
  16004. }
  16005. if (this.mIjkMediaPlayer.isPlaying()) {
  16006. const isCueTrackCompleted = cueTrackItem &&
  16007. cueTrackEndOffset > cueTrackStartOffset &&
  16008. rawPosition >= cueTrackEndOffset;
  16009. //如果是开启AB循环
  16010. if(this.isOpenAB){
  16011. if(position >=this.jumpBTime){
  16012. this.seekTo(this.jumpATime+'')
  16013. return
  16014. }
  16015. }
  16016. // 判断是否播放到结束时间
  16017. if ((this.isOpenJump && duration > this.jumpEndTime * 1000 &&
  16018. position >= duration - this.jumpEndTime * 1000) || isCueTrackCompleted) {
  16019. if(this.playType == 1){//跳过尾部如果是单曲循环就选择单曲循环
  16020. this.CONTROL_PlayStatus = PlayStatus.INIT
  16021. this.startPlayOrResumePlay();
  16022. }else if (this.playType == 2) { //2:正常播放,单片播完
  16023. this.showRePlay();
  16024. this.currentTime = this.stringForTime(duration);
  16025. this.progressValue = this.PROGRESS_MAX_VALUE;
  16026. this.slideEnable = false;
  16027. this.stop();
  16028. // ToastUtil.showToast('开始重新播放')
  16029. }else if (this.playType == 4) { //4:连续播放不循环
  16030. // 检查是否是最后一首
  16031. if (this.curIndex >= this.songList.length - 1) {
  16032. // 已经是最后一首,停止播放
  16033. Logger.info('heanup setProgress', '连续播放不循环模式:已到达最后一首,停止播放');
  16034. ToastUtil.showToast('已经是最后一首了');
  16035. this.showRePlay();
  16036. this.currentTime = this.stringForTime(duration);
  16037. this.progressValue = this.PROGRESS_MAX_VALUE;
  16038. this.slideEnable = false;
  16039. this.stop();
  16040. } else {
  16041. // 不是最后一首,继续播放下一首
  16042. this.playNext().catch(() => {
  16043. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  16044. });
  16045. }
  16046. }else{
  16047. this.playNext().catch(() => {
  16048. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  16049. });
  16050. }
  16051. }
  16052. }
  16053. }
  16054. private startProgressTask() {
  16055. let that = this;
  16056. if (this.updateProgressTimer) {
  16057. clearInterval(this.updateProgressTimer);
  16058. this.updateProgressTimer = 0;
  16059. }
  16060. this.updateProgressTimer = setInterval(() => {
  16061. //LogUtils.getInstance().LOGI("startProgressTask");
  16062. if (!that.mDestroyPage) {
  16063. that.setProgress();
  16064. }
  16065. }, this.progressUpdateIntervalMs);
  16066. }
  16067. private stopProgressTask() {
  16068. LogUtils.getInstance().LOGI("stopProgressTask");
  16069. clearInterval(this.updateProgressTimer);
  16070. this.updateProgressTimer = 0;
  16071. }
  16072. private showLoadIng() {
  16073. this.isPlayerLoading = true;
  16074. this.loadingVisible = Visibility.Visible;
  16075. this.replayVisible = Visibility.None;
  16076. }
  16077. private hideLoadIng() {
  16078. this.isPlayerLoading = false;
  16079. this.loadingVisible = Visibility.None;
  16080. this.replayVisible = Visibility.None;
  16081. }
  16082. private showRePlay() {
  16083. this.isPlayerLoading = false;
  16084. this.loadingVisible = Visibility.None;
  16085. this.replayVisible = Visibility.Visible;
  16086. }
  16087. private beginRemoteSongSwitchLoading(song?: VideoItem): boolean {
  16088. const shouldShow = !!song && isRemoteCloudType(song.type);
  16089. if (shouldShow) {
  16090. this.showLoadIng();
  16091. }
  16092. return shouldShow;
  16093. }
  16094. private clearInitialSeekGuardTimer(): void {
  16095. if (this.initialSeekGuardTimer) {
  16096. clearTimeout(this.initialSeekGuardTimer);
  16097. this.initialSeekGuardTimer = 0;
  16098. }
  16099. }
  16100. private ensurePlayerStartedAfterInitialSeek(reason: string): void {
  16101. try {
  16102. if (!this.mIjkMediaPlayer.isPlaying()) {
  16103. this.mIjkMediaPlayer.start();
  16104. }
  16105. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  16106. this.setIsPlaying(true);
  16107. this.updateSessionPlayState(true);
  16108. Logger.info(TAG, `记忆播放恢复开播: ${reason}`);
  16109. } catch (error) {
  16110. Logger.error(TAG, `记忆播放恢复开播失败(${reason}): ${(error as Error).message}`);
  16111. }
  16112. }
  16113. private finishInitialSeekWait(reason: string, shouldStart: boolean): void {
  16114. this.clearInitialSeekGuardTimer();
  16115. const wasWaiting = this.waitInitialSeekBeforeStart;
  16116. this.waitInitialSeekBeforeStart = false;
  16117. this.pendingMemorySeekPosition = 0;
  16118. this.isPlayerLoading = false;
  16119. this.hideLoadIng();
  16120. if (wasWaiting) {
  16121. Logger.info(TAG, `结束记忆seek等待: ${reason}`);
  16122. }
  16123. if (shouldStart) {
  16124. this.ensurePlayerStartedAfterInitialSeek(reason);
  16125. }
  16126. }
  16127. private startInitialSeekGuardTimer(scene: string): void {
  16128. this.clearInitialSeekGuardTimer();
  16129. if (!this.waitInitialSeekBeforeStart || this.pendingMemorySeekPosition <= 0) {
  16130. return;
  16131. }
  16132. const token = this.remoteRestoreSeekToken;
  16133. this.initialSeekGuardTimer = setTimeout(() => {
  16134. if (token !== this.remoteRestoreSeekToken || !this.waitInitialSeekBeforeStart) {
  16135. return;
  16136. }
  16137. Logger.warn(TAG, `记忆seek超时兜底开播, scene=${scene}, pos=${this.pendingMemorySeekPosition}`);
  16138. this.finishInitialSeekWait('seek-timeout', true);
  16139. }, this.initialSeekGuardTimeoutMs);
  16140. }
  16141. private async play(url: string,startOffset?:number) {
  16142. this.lyricController.setLyric(null)
  16143. this.lyricControllerSingle.setLyric(null)
  16144. this.lastLyricRenderPosition = Number.NaN;
  16145. this.isShowBgLiuGUANG = PreferencesUtil.getBooleanSync('isShowBgLiuGUANG', false)
  16146. console.info('onecold this.url 1= '+url)
  16147. if(!url.toLowerCase().startsWith('http')){
  16148. let hasPermission = await PermissionUtil.activatePermission(url)
  16149. console.info('onecold this.hasPermission 1= '+hasPermission)
  16150. if(!url.includes(this.packName)){
  16151. const file = fs.openSync(url)
  16152. this.videoUrl = file.path
  16153. url= this.videoUrl
  16154. }
  16155. console.info('onecold this.hasPermission 1= '+hasPermission)
  16156. console.info('onecold this.videoUrl 1= '+this.videoUrl)
  16157. }
  16158. let that = this;
  16159. const isBaiduStreamingPlayback = isBaiduStreamingPlaybackUrl(url);
  16160. if (this.waitInitialSeekBeforeStart) {
  16161. that.showLoadIng();
  16162. } else {
  16163. that.hideLoadIng();
  16164. }
  16165. const startOnPreparedOption = this.waitInitialSeekBeforeStart ? "0" : "1";
  16166. this.isOpenAB = false
  16167. //设置XComponent回调的context
  16168. if (!!this.mContext) {
  16169. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  16170. }
  16171. // 每次播放前都先 reset,防止快速切换歌曲时崩溃
  16172. // 修复 SIGSEGV 崩溃:确保播放器在设置新数据源前完全停止并释放资源
  16173. try {
  16174. this.mIjkMediaPlayer.reset();
  16175. Logger.info(TAG, 'IjkPlayer reset 成功');
  16176. } catch (error) {
  16177. Logger.error(TAG, `IjkPlayer reset 失败: ${(error as Error).message}`);
  16178. }
  16179. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  16180. //设置debug模式(用于EQ日志采集)
  16181. this.mIjkMediaPlayer.setDebug(true);
  16182. //初始化配置
  16183. this.mIjkMediaPlayer.native_setup();
  16184. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  16185. this.applyCurrentVolume(true);
  16186. // 构建规范的HTTP请求头(统一一次性设置,避免未带认证提前发起连接)
  16187. const headers = new Map<string, string>();
  16188. headers.set("User-Agent", "TTMusic-WebDAV/1.0");
  16189. headers.set("Accept", "*/*");
  16190. if (this.currentSong&&StrUtil.isEmpty(this.currentSong.pixelMapPath)
  16191. &&PreferencesUtil.getStringSync('COVER_API', '') != '') {
  16192. //如果封面为空,则搜索封面
  16193. this.searchCover(this.currentSong, this.currentSong.name, this.currentSong.artist||'')
  16194. }
  16195. // 仅对确实需要额外认证头的远程类型补充请求头。
  16196. // Navidrome/Plex/AudioStation/DaoLiYu 等类型的播放链接已自带认证参数,这里不要再误走 WebDAV 认证分支。
  16197. if (this.currentSong
  16198. && (isWebDavType(this.currentSong.type) || isJellyfinType(this.currentSong.type) || isEmbyType(this.currentSong.type))) {
  16199. Logger.info(`heanup 远程歌曲认证头构建 - 歌曲名: ${this.currentSong.name}, webdav_account_id: ${this.currentSong.webdav_account_id || '未设置'}`);
  16200. if (this.currentSong.webdav_account_id) {
  16201. try {
  16202. const webdavManager = RemoteDriveManager.getInstance();
  16203. const webDavHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  16204. if (webDavHeaders && webDavHeaders.size > 0) {
  16205. webDavHeaders.forEach((value, key) => headers.set(key, value));
  16206. Logger.info(`heanup 成功通过webdav_account_id获取并合并远程认证头`);
  16207. } else {
  16208. Logger.warn(`heanup 通过webdav_account_id未获取到额外认证头`);
  16209. }
  16210. } catch (error) {
  16211. const err = error as Error;
  16212. Logger.error(`heanup 获取远程认证头时出错: ${err.message}`);
  16213. }
  16214. } else {
  16215. Logger.error(`heanup 远程歌曲 "${this.currentSong.name}" 缺少webdav_account_id,无法构建认证头`);
  16216. }
  16217. } else if (this.currentSong && isSmbType(this.currentSong.type)) {
  16218. Logger.info(`heanup SMB歌曲通过HTTP代理播放,无需认证头`);
  16219. }
  16220. // 统一设置带认证的请求头
  16221. // 百度类型也需要特殊请求头
  16222. if (this.currentSong && isBaiduType(this.currentSong.type)) {
  16223. try {
  16224. const webdavManager = RemoteDriveManager.getInstance();
  16225. const baiduHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  16226. baiduHeaders.forEach((value, key) => headers.set(key, value));
  16227. const headerSnapshot: Record<string, string> = {};
  16228. headers.forEach((value, key) => headerSnapshot[key] = value);
  16229. Logger.info(TAG, `Baidu播放请求头: ${JSON.stringify(headerSnapshot)}`);
  16230. } catch (error) {
  16231. Logger.error(`heanup 构建百度请求头失败: ${(error as Error).message}`);
  16232. }
  16233. }
  16234. //设置视频源(先准备好认证头,再设置数据源)
  16235. Logger.info(TAG, `IjkPlayer setDataSource url=${url}`);
  16236. this.mIjkMediaPlayer.setDataSource(url);
  16237. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  16238. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !isBaiduType(this.currentSong.type)) {
  16239. console.log(`heanup 为WebDAV播放设置IjkPlayer选项`);
  16240. // 网络超时设置(单位:微秒,文档显示应该是字符串格式)
  16241. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "30000000"); // 30秒
  16242. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "30000000"); // 连接超时30秒
  16243. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "listen_timeout", "30000000"); // 监听超时30秒
  16244. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "30000000"); // DNS缓存超时30秒
  16245. // 缓冲和播放优化设置
  16246. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "1024000"); // 增大缓冲区
  16247. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "50"); // 减少最小帧数
  16248. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", startOnPreparedOption); // 预加载启动
  16249. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0"); // 无缓冲播放
  16250. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "30000"); // 最大缓存30秒
  16251. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1"); // 无限制收流
  16252. // 网络相关设置
  16253. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1"); // 启用HTTP重定向
  16254. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", "TTMusic-WebDAV/1.0"); // 用户代理
  16255. // 重连设置
  16256. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "reconnect", "3"); // 重连3次
  16257. console.log(`heanup WebDAV IjkPlayer选项设置完成`);
  16258. } else if ((this.currentSong && isBaiduType(this.currentSong.type)) || isBaiduStreamingPlayback) {
  16259. console.log(`heanup 为百度网盘播放设置IjkPlayer选项`);
  16260. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "15000000");
  16261. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "15000000");
  16262. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1");
  16263. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "1");
  16264. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "2097152");
  16265. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "25");
  16266. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", BaiduConstants.USER_AGENT);
  16267. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", "3");
  16268. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http-detect-range-support", "1");
  16269. console.log(`heanup 百度网盘 IjkPlayer 选项设置完成`);
  16270. }
  16271. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  16272. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  16273. // }
  16274. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  16275. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  16276. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  16277. let bufferSize = 50 * 1024 ; // 默认缓冲区大小为1MB
  16278. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  16279. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  16280. //停止预读的最小帧数
  16281. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  16282. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  16283. // 设置其他缓冲相关选项
  16284. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  16285. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  16286. //启动预加载
  16287. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", startOnPreparedOption);
  16288. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  16289. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  16290. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  16291. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  16292. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  16293. // 因此需要播放器丢包,才不会累积延时
  16294. // 这个和第三个参数packet-buffering无关。
  16295. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  16296. // 无限制收流
  16297. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  16298. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  16299. // 屏幕常亮
  16300. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  16301. // 开启hls起播优化 默认是关闭的
  16302. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "fetch_first", "on");
  16303. // 设置超时
  16304. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  16305. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  16306. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  16307. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  16308. // 变速播放
  16309. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  16310. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  16311. let Speed = this.mIjkMediaPlayer.getSpeed()
  16312. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  16313. //是否开启循环播放
  16314. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  16315. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = new ImplOnVideoSizeChangedListener(
  16316. (width: number, height: number, sar_num: number, sar_den: number) => {
  16317. if (height === 0) {
  16318. return;
  16319. }
  16320. const va = width / height;
  16321. const vpa = that.videoParentAspectRatio;
  16322. if (vpa > va) {
  16323. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  16324. } else {
  16325. that.videoWidth = '100%';
  16326. }
  16327. if (width && height) {
  16328. that.videoAspectRatio = width / height;
  16329. }
  16330. LogUtils.getInstance()
  16331. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  16332. if (!that.waitInitialSeekBeforeStart) {
  16333. that.hideLoadIng();
  16334. }
  16335. }
  16336. );
  16337. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  16338. let mOnPreparedListener: OnPreparedListener = new ImplOnPreparedListener(
  16339. async () => {
  16340. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  16341. Logger.info(
  16342. TAG,
  16343. `[seek] prepared enter, waitInitial=${this.waitInitialSeekBeforeStart}, pendingMemory=${this.pendingMemorySeekPosition}, ` +
  16344. `songType=${this.currentSong?.type ?? -1}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  16345. );
  16346. if (!this.waitInitialSeekBeforeStart) {
  16347. // 无记忆seek时,prepared后可直接隐藏加载
  16348. this.isPlayerLoading = false;
  16349. }
  16350. try {
  16351. //保存碰一碰分享的当前的歌曲
  16352. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  16353. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  16354. await this.initLyric(lyricPath);
  16355. const applyDuration = (durationMs: number): void => {
  16356. const cueTrackDuration = this.currentSong && isCueSplitItem(this.currentSong)
  16357. ? getCueTrackDuration(this.currentSong)
  16358. : 0;
  16359. const effectiveDuration = cueTrackDuration > 0 ? cueTrackDuration : durationMs;
  16360. if (effectiveDuration <= 0) {
  16361. return;
  16362. }
  16363. this.duration = effectiveDuration;
  16364. this.durationTime = Math.floor(effectiveDuration / 1000);
  16365. this.durationStringTime = secondToTime(this.durationTime);
  16366. this.totalTime = this.stringForTime(effectiveDuration);
  16367. if (this.currentSong) {
  16368. this.currentSong.duration = this.totalTime;
  16369. try {
  16370. this.avSessionController.setAVMetadataMusic(this.currentSong, effectiveDuration, this.lyricContent);
  16371. } catch (metaError) {
  16372. Logger.warn(TAG, `heanup 首次播放写入AVSession失败: ${(metaError as Error).message}`);
  16373. }
  16374. }
  16375. };
  16376. const fetchBaiduM3u8Duration = async (url: string): Promise<number> => {
  16377. if (!url || !isBaiduType(this.currentSong?.type ?? -1)) {
  16378. return 0;
  16379. }
  16380. const httpRequest = http.createHttp();
  16381. try {
  16382. const response = await httpRequest.request(url, {
  16383. method: http.RequestMethod.GET,
  16384. connectTimeout: 8000,
  16385. readTimeout: 8000,
  16386. expectDataType: http.HttpDataType.STRING,
  16387. header: {
  16388. 'User-Agent': BaiduConstants.STREAMING_USER_AGENT,
  16389. 'Host': 'pan.baidu.com',
  16390. 'Referer': 'https://pan.baidu.com/disk/home',
  16391. 'Accept-Encoding': 'identity'
  16392. }
  16393. });
  16394. if (response.responseCode !== 200 || typeof response.result !== 'string') {
  16395. return 0;
  16396. }
  16397. const text = response.result;
  16398. if (text.indexOf('#EXTM3U') < 0) {
  16399. return 0;
  16400. }
  16401. const lines = text.split('\n');
  16402. let totalSeconds = 0;
  16403. for (let i = 0; i < lines.length; i++) {
  16404. const line = lines[i].trim();
  16405. if (line.startsWith('#EXTINF:')) {
  16406. const colonIndex = line.indexOf(':');
  16407. if (colonIndex < 0) {
  16408. continue;
  16409. }
  16410. const content = line.substring(colonIndex + 1);
  16411. const commaIndex = content.indexOf(',');
  16412. const numberPart = commaIndex >= 0 ? content.substring(0, commaIndex) : content;
  16413. const seconds = Number(numberPart);
  16414. if (!Number.isNaN(seconds) && seconds > 0) {
  16415. totalSeconds += seconds;
  16416. }
  16417. }
  16418. }
  16419. if (totalSeconds > 0) {
  16420. return Math.floor(totalSeconds * 1000);
  16421. }
  16422. return 0;
  16423. } catch (fetchError) {
  16424. Logger.warn(TAG, `heanup 解析百度M3U8时长失败: ${(fetchError as Error).message}`);
  16425. return 0;
  16426. } finally {
  16427. httpRequest.destroy();
  16428. }
  16429. };
  16430. const fetchDurationFallback = async (): Promise<void> => {
  16431. const durationMs = await fetchBaiduM3u8Duration(this.videoUrl);
  16432. if (durationMs > 0) {
  16433. Logger.info(TAG, `heanup 通过M3U8推导出时长: ${durationMs}ms`);
  16434. applyDuration(durationMs);
  16435. return;
  16436. }
  16437. Logger.warn(TAG, 'heanup 首次播放未拿到时长,保持未知');
  16438. };
  16439. const preparedDuration = this.mIjkMediaPlayer.getDuration();
  16440. Logger.info(
  16441. TAG,
  16442. `[seek] prepared duration snapshot, playerDuration=${preparedDuration}, metaDuration=${this.currentSong?.duration ?? ''}, ` +
  16443. `url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  16444. );
  16445. if (preparedDuration > 0) {
  16446. applyDuration(preparedDuration);
  16447. if (this.videoUrl.includes('method=streaming') && isBaiduType(this.currentSong?.type ?? -1)) {
  16448. const durationMs = await fetchBaiduM3u8Duration(this.videoUrl);
  16449. if (durationMs > 0 && Math.abs(durationMs - preparedDuration) > 1000) {
  16450. Logger.info(TAG, `heanup 使用M3U8时长覆盖播放器时长: ${preparedDuration}ms -> ${durationMs}ms`);
  16451. applyDuration(durationMs);
  16452. }
  16453. }
  16454. } else {
  16455. const metaDurationMs = this.parseDurationToMs(this.currentSong?.duration);
  16456. if (metaDurationMs > 0) {
  16457. Logger.info(TAG, `heanup 使用元数据时长: ${metaDurationMs}ms`);
  16458. applyDuration(metaDurationMs);
  16459. } else {
  16460. fetchDurationFallback();
  16461. }
  16462. }
  16463. setTimeout(() => {
  16464. this.avSessionController.initAvSession(false);
  16465. if (this.duration > 0) {
  16466. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  16467. }
  16468. this.setAvSessionListener();
  16469. this.updateSessionPlayState(true)
  16470. this.setCurrentPlayMode()
  16471. const cueTrackStartOffset = this.currentSong && isCueSplitItem(this.currentSong)
  16472. ? getCueTrackStartOffset(this.currentSong)
  16473. : 0;
  16474. if ((startOffset && startOffset > 0) || cueTrackStartOffset > 0) {//cue分轨播放
  16475. const cueSeekValue = cueTrackStartOffset > 0 && (!startOffset || startOffset <= 0) ? 0 : startOffset;
  16476. this.seekTo((cueSeekValue || 0) + "");
  16477. this.saveLastPlayList()
  16478. return
  16479. }
  16480. }, 500)
  16481. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  16482. let timeoutPlay = 0
  16483. if (StrUtil.isNotEmpty(this.videoUrl) &&
  16484. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  16485. timeoutPlay = 400
  16486. }
  16487. // 网盘流地址在prepare后立刻seek容易触发底层不稳定,统一延后记忆恢复
  16488. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.videoUrl.includes('://')) {
  16489. timeoutPlay = Math.max(timeoutPlay,
  16490. this.waitInitialSeekBeforeStart ? this.remoteMemorySeekInitialDelayMs : 700);
  16491. }
  16492. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  16493. if (this.modeType === 0) { //文件夹
  16494. let parentPath = FileUtil.getParentPath(this.videoUrl)
  16495. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  16496. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  16497. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  16498. } else if (this.modeType === 1) { //媒体库
  16499. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  16500. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  16501. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  16502. } else if (this.modeType === 2) { //艺术家
  16503. if (this.currentSong?.artist) {
  16504. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  16505. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  16506. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  16507. }
  16508. } else if (this.modeType === 3) { //专辑
  16509. if (this.currentSong?.album) {
  16510. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  16511. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  16512. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  16513. }
  16514. }
  16515. const playerDuration = this.mIjkMediaPlayer.getDuration()
  16516. if (playerDuration > 0 && (!this.currentSong || !isCueSplitItem(this.currentSong))) {
  16517. this.duration = playerDuration
  16518. }
  16519. const memoryPosition = this.pendingMemorySeekPosition > 0 ?
  16520. this.pendingMemorySeekPosition : PreferencesUtil.getNumberSync(this.getPlaybackMemoryKey(), 0);
  16521. if (this.waitInitialSeekBeforeStart && memoryPosition > 0) {
  16522. let targetSeekPosition = memoryPosition;
  16523. if (this.isOpenJump) {
  16524. targetSeekPosition = Math.max(targetSeekPosition, this.jumpTopTime * 1000);
  16525. }
  16526. this.pendingMemorySeekPosition = targetSeekPosition;
  16527. this.startInitialSeekGuardTimer('prepared-memory-seek');
  16528. Logger.info(TAG, `准备记忆播放seek: ${targetSeekPosition}ms, timeout=${timeoutPlay}ms`);
  16529. setTimeout(() => {
  16530. if (!this.waitInitialSeekBeforeStart) {
  16531. return;
  16532. }
  16533. this.restorePlaybackPosition();
  16534. }, timeoutPlay);
  16535. this.isFirstStartPlay = false
  16536. this.saveLastPlayList()
  16537. return
  16538. }
  16539. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  16540. if (this.mIjkMediaPlayer != null) {
  16541. let jumpTopTimeMs = this.jumpTopTime*1000;
  16542. if (jumpTopTimeMs <= this.duration) {
  16543. // 调用 seekTo 方法,跳到指定时间
  16544. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  16545. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  16546. this.seekTo(jumpTopTimeMs + ""); // 跳到开头或记忆进度中更靠后的位置
  16547. }
  16548. }, timeoutPlay)
  16549. } else {
  16550. // 提示用户无法跳过
  16551. ToastUtil.showToast('跳过时间超过视频时长');
  16552. }
  16553. }
  16554. } else {
  16555. this.jumpTopTime = 0
  16556. this.jumpEndTime = 0
  16557. // console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  16558. // console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  16559. // console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  16560. // PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  16561. //记忆播放(每一首都会记忆播放)
  16562. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  16563. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  16564. if (this.pendingMemorySeekPosition > 0 ||
  16565. PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  16566. this.restorePlaybackPosition() //读取播放记忆功能
  16567. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  16568. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  16569. this.restorePlaybackPosition() //读取播放记忆功能
  16570. }
  16571. this.isFirstStartPlay = false
  16572. }, timeoutPlay)
  16573. } else {
  16574. this.isFirstStartPlay = false
  16575. }
  16576. }
  16577. this.saveLastPlayList()
  16578. } catch (error) {
  16579. let err: BusinessError = error as BusinessError;
  16580. console.error('onecold failed with err: ' + JSON.stringify(err));
  16581. if (this.waitInitialSeekBeforeStart) {
  16582. this.finishInitialSeekWait('prepared-exception', true);
  16583. }
  16584. }
  16585. }
  16586. );
  16587. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  16588. let mOnTimedTextListener: OnTimedTextListener = new ImplOnTimedTextListener(
  16589. (text: string) => {
  16590. }
  16591. );
  16592. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  16593. let mOnCompletionListener: OnCompletionListener = new ImplOnCompletionListener(
  16594. () => {
  16595. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  16596. if (this.playType == 0) { //0:连续循环播放 1:单片重复播放 2:正常播放 4:连续播放不循环
  16597. // 异步调用playNext
  16598. this.playNext().catch(() => {
  16599. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  16600. });
  16601. } else if (this.playType == 1) { //1:单片重复播放
  16602. this.CONTROL_PlayStatus = PlayStatus.INIT
  16603. that.startPlayOrResumePlay();
  16604. } else if (this.playType == 2) { //2:正常播放,单曲播完
  16605. that.showRePlay();
  16606. that.currentTime = that.stringForTime(that.getActiveDuration());
  16607. that.progressValue = this.PROGRESS_MAX_VALUE;
  16608. that.slideEnable = false;
  16609. that.stop();
  16610. // ToastUtil.showToast('开始重新播放')
  16611. } else if (this.playType == 3) { //3:随机播放
  16612. // 异步调用randomPlay
  16613. this.randomPlay().catch(() => {
  16614. Logger.error('heanup OnCompletionListener randomPlay', `随机播放失败`);
  16615. });
  16616. } else if (this.playType == 4) { //4:连续播放不循环
  16617. // 异步调用playNext
  16618. this.playNext().catch(() => {
  16619. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  16620. });
  16621. }
  16622. }
  16623. );
  16624. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  16625. let mOnBufferingUpdateListener: OnBufferingUpdateListener = new ImplOnBufferingUpdateListener(
  16626. (percent: number) => {
  16627. if (this.isDebug) {
  16628. const now = Date.now();
  16629. if (now - this.lastBufferingLogTs > this.bufferingLogIntervalMs) {
  16630. this.lastBufferingLogTs = now;
  16631. Logger.info(TAG, `OnBufferingUpdateListener percent=${percent}`);
  16632. }
  16633. }
  16634. }
  16635. );
  16636. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  16637. let mOnSeekCompleteListener: OnSeekCompleteListener = new ImplOnSeekCompleteListener(
  16638. () => {
  16639. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  16640. that.logSeekTrace('seek-complete', undefined, undefined, true);
  16641. // seek 完成,延迟恢复播放,确保 ijkplayer 内部状态完全稳定
  16642. setTimeout(() => {
  16643. const waitingInitialSeek = that.waitInitialSeekBeforeStart;
  16644. that.isSeekTo = false;
  16645. if (waitingInitialSeek) {
  16646. that.finishInitialSeekWait('seek-complete', true);
  16647. } else {
  16648. that.hideLoadIng();
  16649. }
  16650. }, 200); // 延迟200ms,确保ijkplayer内部状态稳定
  16651. }
  16652. );
  16653. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  16654. let mOnInfoListener: OnInfoListener = new ImplOnInfoListener(
  16655. (what: number, extra: number) => {
  16656. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  16657. if (that.isSeekTraceActive()) {
  16658. Logger.info(
  16659. TAG,
  16660. `[seek] onInfo what=${what}, extra=${extra}, source=${that.lastSeekSource || 'unknown'}, ` +
  16661. `req=${that.lastSeekRequestMs}, url=${that.sanitizePlaybackUrl(that.videoUrl)}`
  16662. );
  16663. that.logSeekTrace(`info-${what}`, undefined, undefined, true);
  16664. }
  16665. if (!that.waitInitialSeekBeforeStart) {
  16666. that.hideLoadIng();
  16667. }
  16668. }
  16669. );
  16670. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  16671. let mOnErrorListener: OnErrorListener = new ImplOnErrorListener(
  16672. (what: number, extra: number) => {
  16673. this.finishInitialSeekWait('player-error', false);
  16674. this.stopProgressTask();
  16675. this.logSeekTrace(`error-${what}-${extra}`, undefined, undefined, true);
  16676. Logger.error(
  16677. TAG,
  16678. `[seek] onError what=${what}, extra=${extra}, url=${this.sanitizePlaybackUrl(this.videoUrl)}, ` +
  16679. `song=${JSON.stringify(this.currentSong)}`
  16680. );
  16681. // 检查是否为WebDAV播放错误
  16682. let isWebDavError = false;
  16683. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.currentSong.filePath) {
  16684. try {
  16685. const globalContext = GlobalContext.getContext();
  16686. const webDavAuthInfo = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
  16687. if (webDavAuthInfo) {
  16688. isWebDavError = true;
  16689. }
  16690. } catch (error) {
  16691. console.error('OnErrorListener-->go: 获取WebDAV认证信息失败');
  16692. }
  16693. }
  16694. if (isWebDavError) {
  16695. console.info(`heanup WebDAV播放错误 - what: ${what}, extra: ${extra}, URL: ${this.videoUrl}`);
  16696. // 播放失败时清空实例变量中的WebDAV认证信息,防止错误账户持续使用
  16697. // this.currentWebDavAuthInfo = null;
  16698. console.info('heanup WebDAV播放失败,保留认证信息用于后续歌曲切换');
  16699. // 根据错误代码提供更具体的错误信息
  16700. let errorMessage = "WebDAV播放失败";
  16701. if (what === -1) { // 网络错误
  16702. errorMessage = "网络连接失败,请检查WebDAV服务器连接";
  16703. } else if (what === -1004) { // HTTP 404
  16704. errorMessage = "文件未找到,请检查WebDAV服务器上的文件";
  16705. } else if (what === -1001) { // 超时
  16706. errorMessage = "连接超时,请检查网络或WebDAV服务器状态";
  16707. } else if (what === -1003) { // 无法解析主机
  16708. errorMessage = "无法连接到WebDAV服务器";
  16709. }
  16710. ToastUtil.showToast(errorMessage);
  16711. } else {
  16712. if (StrUtil.isNotEmpty(this.videoUrl) &&
  16713. !this.videoUrl.startsWith('http') &&
  16714. this.currentSong &&this.currentSong.type==CommonConstants.TYPE_LOCAL&&
  16715. !FileUtil.accessSync(this.videoUrl)) {
  16716. console.info('heanup 播放.文件不存在');
  16717. ToastUtil.showToast(Utility.resourceToString(this.context, $r('app.string.file_not_exist')))
  16718. }
  16719. }
  16720. that.hideLoadIng();
  16721. }
  16722. );
  16723. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  16724. this.mIjkMediaPlayer.setMessageListener();
  16725. // 应用均衡器设置
  16726. try {
  16727. const equalizerManager = EqualizerManager.getInstance();
  16728. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  16729. Logger.info(TAG, 'heanup 均衡器设置已应用');
  16730. this.markEqualizerApplied();
  16731. } catch (eqError) {
  16732. Logger.warn(TAG, `heanup 应用均衡器失败: ${(eqError as Error).message}`);
  16733. this.eqApplying = false;
  16734. }
  16735. this.mIjkMediaPlayer.prepareAsync();
  16736. this.mIjkMediaPlayer.start();
  16737. }
  16738. //保存最后播放的那首歌和已经对应的播放列表
  16739. saveLastPlayList() {
  16740. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  16741. PreferencesUtil.putSync('LastMusicList', this.songList)
  16742. PreferencesUtil.putSync('LastPlayQueueScope', this.playQueueScope)
  16743. PreferencesUtil.putSync('LastPlayModeType', this.modeType)
  16744. PreferencesUtil.putSync('LastPlayTotalCount', this.totalCount)
  16745. }
  16746. // 清空播放记录
  16747. clearVideoHistory() {
  16748. this.table.clearPlayHistory((success: boolean, error?: string) => {
  16749. if (success) {
  16750. this.historyList = [];
  16751. this.updateListData(this.historyList)
  16752. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  16753. ToastUtil.showToast('清空播放记录成功')
  16754. } else {
  16755. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  16756. }
  16757. });
  16758. }
  16759. public async setAvSessionListener() {
  16760. if (!this.avSessionController) {
  16761. return;
  16762. }
  16763. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  16764. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  16765. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  16766. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  16767. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  16768. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  16769. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  16770. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  16771. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  16772. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  16773. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  16774. }
  16775. setLoopMode() {
  16776. let itype = this.playType + 1
  16777. if (itype >= 5) {
  16778. this.playType = 0
  16779. ToastUtil.showToast('连续循环播放')
  16780. } else if (itype === 1) {
  16781. this.playType = 1
  16782. ToastUtil.showToast('单曲循环')
  16783. } else if (itype === 2) {
  16784. this.playType = 2
  16785. ToastUtil.showToast('单曲播完')
  16786. } else if (itype === 3) {
  16787. this.playType = 3
  16788. ToastUtil.showToast('随机播放')
  16789. } else if (itype === 4) {
  16790. this.playType = 4
  16791. ToastUtil.showToast('连续播放不循环')
  16792. } else if (itype === 0) {
  16793. this.playType = 0
  16794. ToastUtil.showToast('连续循环播放')
  16795. }
  16796. PreferencesUtil.putSync('musicPlayType', this.playType)
  16797. this.setCurrentPlayMode()
  16798. }
  16799. private sessionSetLoopModeCallback = (mode: number) => {
  16800. if (this.mIjkMediaPlayer != null) {
  16801. ToastUtil.showToast('当前播放模式:' + mode)
  16802. Logger.info('onecold 当前播放模式= ' + mode)
  16803. let hmPlayMode = mode + 1
  16804. if (hmPlayMode >= 4) {
  16805. hmPlayMode = 0
  16806. }
  16807. if (hmPlayMode === 1) {
  16808. this.playType = 1
  16809. ToastUtil.showToast('单曲循环')
  16810. } else if (hmPlayMode === 0) {
  16811. this.playType = 2
  16812. ToastUtil.showToast('单曲播完')
  16813. } else if (hmPlayMode === 3) {
  16814. this.playType = 3
  16815. ToastUtil.showToast('随机播放')
  16816. } else if (hmPlayMode === 2) {
  16817. this.playType = 0
  16818. ToastUtil.showToast('连续循环播放')
  16819. } else if (hmPlayMode === 4) {
  16820. this.playType = 4
  16821. ToastUtil.showToast('连续播放不循环')
  16822. }
  16823. PreferencesUtil.putSync('musicPlayType', this.playType)
  16824. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  16825. let playBackState: avSession.AVPlaybackState = {
  16826. loopMode: hmPlayMode,
  16827. };
  16828. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  16829. console.info(`set setLoopMode AVPlaybackState successfully`);
  16830. }).catch((err: BusinessError) => {
  16831. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  16832. });
  16833. }
  16834. }
  16835. setCurrentPlayMode() {
  16836. if (!this.avSessionController) {
  16837. return;
  16838. }
  16839. let mLoopMode = 0
  16840. switch (this.playType) {
  16841. case 0:
  16842. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续循环播放
  16843. break;
  16844. case 1:
  16845. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  16846. break;
  16847. case 2:
  16848. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  16849. break;
  16850. case 3:
  16851. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  16852. break;
  16853. case 4:
  16854. mLoopMode = avSession.LoopMode.LOOP_MODE_CUSTOM //连续播放不循环
  16855. break;
  16856. }
  16857. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  16858. let playBState: avSession.AVPlaybackState = {
  16859. loopMode: mLoopMode,
  16860. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  16861. };
  16862. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  16863. console.info(`set setLoopMode AVPlaybackState successfully`);
  16864. }).catch((err: BusinessError) => {
  16865. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  16866. });
  16867. }
  16868. private applyRequestedPlayType(playType: number): void {
  16869. if (playType < 0 || playType > 4 || this.playType === playType) {
  16870. return
  16871. }
  16872. this.playType = playType
  16873. PreferencesUtil.putSync('musicPlayType', this.playType)
  16874. this.setCurrentPlayMode()
  16875. }
  16876. private sessionToggleFavoriteCallback = (assetId: string) => {
  16877. if (this.mIjkMediaPlayer != null && this.currentSong) {
  16878. console.info(`on toggleFavorite `);
  16879. // 应用收到收藏命令,进行收藏处理。
  16880. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  16881. this.doFav(this.currentSong)
  16882. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  16883. let playbackState: avSession.AVPlaybackState = {
  16884. isFavorite: !this.isFac,
  16885. };
  16886. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  16887. console.info(`SetAVPlaybackState successfully`);
  16888. }).catch((err: BusinessError) => {
  16889. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  16890. });
  16891. }
  16892. }
  16893. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  16894. device: avSession.OutputDeviceInfo) => {
  16895. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  16896. // 将 connectState 转换为可读的字符串
  16897. let stateName = 'UNKNOWN';
  16898. switch (connectState) {
  16899. case avSession.ConnectionState.STATE_CONNECTED:
  16900. stateName = 'CONNECTED(1)';
  16901. break;
  16902. case avSession.ConnectionState.STATE_DISCONNECTED:
  16903. stateName = 'DISCONNECTED(2)';
  16904. break;
  16905. case avSession.ConnectionState.STATE_CONNECTING:
  16906. stateName = 'CONNECTING(3)';
  16907. break;
  16908. default:
  16909. stateName = `OTHER(${connectState})`;
  16910. }
  16911. Logger.info('heanup sessionOutputDeviceChange', `设备状态变化: connectState=${stateName}, castCategory=${currentDevice?.castCategory}, isCastPlaying=${this.isCastPlaying}`);
  16912. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  16913. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  16914. await this.startCasting();
  16915. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  16916. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  16917. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  16918. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  16919. if (device) {
  16920. Logger.info('heanup sessionOutputDeviceChange', '设备断开连接');
  16921. Logger.info('heanup sessionOutputDeviceChange', '用户主动断开连接或已停止播放,调用endCasting');
  16922. this.endCasting();
  16923. }
  16924. }
  16925. };
  16926. private async startCasting() {
  16927. try {
  16928. Logger.info('heanup startCasting', '========== 开始投播初始化 ==========');
  16929. // 获取原始的 AVCastController
  16930. let avCastCtrl = await this.avSessionController.getAvSession()?.getAVCastController();
  16931. if (!avCastCtrl) {
  16932. Logger.error('heanup startCasting', '获取 AVCastController 失败');
  16933. return;
  16934. }
  16935. this.castController = avCastCtrl;
  16936. Logger.info('heanup startCasting', '✅ 获取 AVCastController 成功');
  16937. // 创建新的 CastController 封装器
  16938. this.castControllerWrapper = new CastController(avCastCtrl);
  16939. Logger.info('heanup startCasting', '✅ 创建 CastController 成功');
  16940. // 设置回调函数
  16941. let callbacks: CastControllerCallbacks = {
  16942. onPlayNext: () => {
  16943. Logger.info('heanup CastController', '收到 playNext 回调');
  16944. this.playNext();
  16945. },
  16946. onPlayPrevious: () => {
  16947. Logger.info('heanup CastController', '收到 playPrevious 回调');
  16948. this.playPrevious();
  16949. },
  16950. onPositionChanged: (position: number) => {
  16951. this.positionChange(position);
  16952. },
  16953. onDurationChanged: (duration: number) => {
  16954. this.playDurationChange(duration);
  16955. }
  16956. };
  16957. this.castControllerWrapper.setCallbacks(callbacks);
  16958. Logger.info('heanup startCasting', '✅ 设置回调成功');
  16959. // 暂停本地播放
  16960. this.pause();
  16961. Logger.info('heanup startCasting', '✅ 暂停本地播放成功');
  16962. // 初始化投播会话
  16963. Logger.info('heanup startCasting', `准备调用 initAVCast: songList.length=${this.songList.length}, curIndex=${this.curIndex}, videoUrl=${this.videoUrl}`);
  16964. await this.castControllerWrapper.initAVCast(
  16965. this.songList,
  16966. this.curIndex,
  16967. this.mIjkMediaPlayer.getCurrentPosition(),
  16968. this.videoUrl,
  16969. this.getActiveDuration()
  16970. );
  16971. Logger.info('heanup startCasting', '✅ initAVCast 调用完成');
  16972. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  16973. refToIsCasting?.set(true);
  16974. this.castSeek = true;
  16975. // 从 CastController 获取投播状态
  16976. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  16977. if (this.isCastPlaying) {
  16978. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  16979. this.setIsPlaying(true);
  16980. this.updateSessionPlayState(true);
  16981. }
  16982. Logger.info('heanup startCasting', `✅ 投播初始化完成, isCastPlaying=${this.isCastPlaying}`);
  16983. } catch (error) {
  16984. Logger.error('heanup startCasting', `❌ 投播初始化失败: ${error}`);
  16985. }
  16986. }
  16987. async changeCasting() {
  16988. Logger.info('heanup changeCasting', '切换投播');
  16989. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  16990. this.initQueueItem();
  16991. await this.prepare();
  16992. this.setPlaybackStateChangeListener();
  16993. // isCastPlaying 会在 playbackStateChangeListener 中根据实际状态更新
  16994. this.castSeek = true;
  16995. }
  16996. public endCasting() {
  16997. Logger.info('heanup endCasting', 'endCasting被调用');
  16998. this.avSessionController.getAvSession()?.stopCasting();
  16999. this.stopCast();
  17000. // 关闭文件描述符
  17001. if (this.castFile) {
  17002. try {
  17003. fs.closeSync(this.castFile);
  17004. this.castFile = undefined;
  17005. Logger.info('heanup endCasting', '关闭投播文件描述符');
  17006. } catch (error) {
  17007. Logger.warn('heanup endCasting', `关闭文件描述符失败: ${error}`);
  17008. }
  17009. }
  17010. this.isCastPlaying = false;
  17011. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  17012. refToIsCasting?.set(false);
  17013. this.pause();
  17014. this.setIsPlaying(false);
  17015. // if (this.curIndex === this.curSource.index) {
  17016. // this.play
  17017. // this.seek(this.currentTime * 1000);
  17018. // this.setIsPlaying(true);
  17019. // } else {
  17020. // this.pauseVideo();
  17021. // this.setIsPlaying(false);
  17022. // }
  17023. }
  17024. public setIsPlaying(isPlayer: boolean) {
  17025. this.isPlaying = isPlayer;
  17026. // 发送播放状态变化事件给歌单详情页面
  17027. try {
  17028. const eventPlaybackStatus: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYBACK_STATUS }
  17029. const currentFilePath = this.currentSong?.filePath || ''
  17030. const eventData: emitter.EventData = {
  17031. data: {
  17032. isPlaying: this.isPlaying,
  17033. curIndex: this.curIndex,
  17034. currentFilePath: currentFilePath
  17035. }
  17036. };
  17037. emitter.emit(eventPlaybackStatus, eventData)
  17038. Logger.info(`heanup 发送播放状态变化事件: isPlaying=${this.isPlaying}, curIndex=${this.curIndex}, currentFilePath=${currentFilePath}`)
  17039. } catch (error) {
  17040. Logger.error('heanup 发送播放状态变化事件失败: ' + error)
  17041. }
  17042. }
  17043. private setPlaybackStateChangeListener(): void {
  17044. // 注意: HarmonyOS 的投播控制器可能不返回 state 字段
  17045. // 我们需要通过其他方式来判断播放状态
  17046. // 1. 监听位置变化
  17047. this.castController?.on('playbackStateChange', ['position'], (playbackState: avSession.AVPlaybackState) => {
  17048. if (playbackState.position && typeof playbackState.position.elapsedTime !== 'undefined') {
  17049. Logger.info('heanup playbackStateChange[position]', `elapsedTime=${playbackState.position.elapsedTime}`);
  17050. this.positionChange(playbackState.position.elapsedTime);
  17051. }
  17052. });
  17053. // 2. 监听时长变化
  17054. this.castController?.on('playbackStateChange', ['extras'], (playbackState: avSession.AVPlaybackState) => {
  17055. const duration = playbackState?.extras?.duration;
  17056. if (typeof duration === 'number') {
  17057. this.playDurationChange(duration);
  17058. }
  17059. });
  17060. // 3. 监听所有状态变化(用于调试和状态判断)
  17061. this.castController?.on('playbackStateChange', 'all', (playbackState: avSession.AVPlaybackState) => {
  17062. Logger.info('heanup playbackStateChange[all]', `完整状态=${JSON.stringify(playbackState)}`);
  17063. // 检查是否有 state 字段(某些设备可能返回)
  17064. if (playbackState.state !== undefined) {
  17065. Logger.info('heanup playbackStateChange', `state字段存在: ${playbackState.state}`);
  17066. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  17067. this.isCastPlaying = true;
  17068. }
  17069. }
  17070. });
  17071. // 4. 监听播放完成事件
  17072. this.castController?.on('endOfStream', this.playNextCallback);
  17073. this.castController?.on('playNext', this.playNextCallback);
  17074. this.castController?.on('playPrevious', this.playPreviousCallback);
  17075. // 5. 监听错误事件
  17076. this.castController?.on('error', (error: BusinessError) => {
  17077. Logger.error('heanup playbackStateChange', `投播错误: code=${error.code}, message=${error.message}`);
  17078. this.isCastPlaying = false;
  17079. });
  17080. }
  17081. private updateSessionPlayState(isPlay: boolean): void {
  17082. // if(!this.isBgPlayOpen)
  17083. // return
  17084. const elapsedTime = (this.castControllerWrapper && this.isCastPlaying) ? this.currentTime2 * 1000
  17085. : this.mIjkMediaPlayer.getCurrentPosition();
  17086. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  17087. this.setAVSessionPlayState({
  17088. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  17089. position: {
  17090. elapsedTime: elapsedTime,
  17091. updateTime: new Date().getTime()
  17092. }
  17093. });
  17094. }
  17095. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  17096. this.avSessionController.setAvSessionPlayState(playbackState)
  17097. }
  17098. private positionChange(position: number) {
  17099. this.currentTime2 = position / 1000;
  17100. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  17101. if (this.castControllerWrapper && this.isCastPlaying) {
  17102. this.updateCastProgress(position);
  17103. if (this.isSeekTo) {
  17104. this.isSeekTo = false;
  17105. }
  17106. }
  17107. }
  17108. private playDurationChange(duration: number) {
  17109. this.duration = duration;
  17110. this.durationTime = Math.floor(this.duration / 1000);
  17111. this.durationStringTime = secondToTime((this.durationTime));
  17112. if (this.castControllerWrapper && this.isCastPlaying) {
  17113. this.totalTime = this.stringForTime(this.duration);
  17114. }
  17115. }
  17116. // playbackStateChangeListener 方法已被删除,改用 setPlaybackStateChangeListener 中的内联函数
  17117. private reloadCasting = async () => {
  17118. Logger.info('heanup reloadCasting', '重新加载投播');
  17119. // 使用 initQueueItem() 方法来准备投播项目,保持逻辑一致
  17120. this.initQueueItem();
  17121. await this.prepare();
  17122. };
  17123. public playNextCallback = (): void => {
  17124. this.playNext().catch(() => {
  17125. Logger.error('heanup playNextCallback', `播放下一首失败`);
  17126. });
  17127. };
  17128. public playPreviousCallback = (): void => {
  17129. this.playPrevious().catch(() => {
  17130. Logger.error('heanup playNextCallback', `播放上一首失败`);
  17131. });
  17132. };
  17133. async prepare() {
  17134. try {
  17135. Logger.info('heanup prepare', `开始准备投播: ${this.castItem?.description?.title}`);
  17136. await this.castController?.prepare(this.castItem);
  17137. Logger.info('heanup prepare', '投播prepare成功');
  17138. await this.castController?.start(this.castItem);
  17139. Logger.info('heanup prepare', '投播start成功');
  17140. // 投播启动成功,设置为投播状态
  17141. this.isCastPlaying = true;
  17142. Logger.info('heanup prepare', '投播启动成功,设置isCastPlaying=true');
  17143. } catch (error) {
  17144. Logger.error('heanup prepare', `投播准备失败: ${error}`);
  17145. this.isCastPlaying = false;
  17146. }
  17147. }
  17148. public initQueueItem() {
  17149. let item = this.songList[this.curIndex];
  17150. // 判断是否是流媒体地址 - 使用 videoUrl 判断而不是 filePath
  17151. // 因为 filePath 可能是 navidrome:// 等自定义协议,而 videoUrl 才是真实的流地址
  17152. let isStreaming = this.isUrl(this.videoUrl);
  17153. Logger.info('heanup initQueueItem', `准备投播歌曲: ${item.name}, 是否流媒体: ${isStreaming}, videoUrl: ${this.videoUrl}`);
  17154. // 关闭之前的文件描述符
  17155. if (this.castFile) {
  17156. try {
  17157. fs.closeSync(this.castFile);
  17158. Logger.info('heanup initQueueItem', '关闭之前的文件描述符');
  17159. } catch (error) {
  17160. Logger.warn('heanup initQueueItem', `关闭文件描述符失败: ${error}`);
  17161. }
  17162. }
  17163. let description: avSession.AVMediaDescription = {
  17164. assetId: 'AUDIO-' + item.filePath,
  17165. title: item.name,
  17166. artist: item.artist || '',
  17167. // 该字段大写,音频'AUDIO',视频'VIDEO'
  17168. mediaType: 'AUDIO',
  17169. mediaSize: item.videoSize,
  17170. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  17171. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  17172. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  17173. duration: this.duration,
  17174. albumCoverUri: item.pixelMapPath, // 本地路径电视可能无法访问,暂时注释
  17175. appName: this.appName,
  17176. lyricContent: item.lyricContent,
  17177. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  17178. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  17179. };
  17180. console.log('heanup initQueueItem this.lyricContent', item.lyricContent);
  17181. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  17182. if (isStreaming) {
  17183. // 流媒体地址使用 mediaUri
  17184. description.mediaUri = this.videoUrl;
  17185. Logger.info('heanup initQueueItem', `使用流媒体地址投播: ${this.videoUrl}`);
  17186. } else {
  17187. // 本地文件使用 fdSrc
  17188. const localPath = this.videoUrl || item.filePath;
  17189. let uri = fileUri.getUriFromPath(localPath);
  17190. this.castFile = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  17191. let fdSrc: media.AVFileDescriptor = {
  17192. fd: this.castFile.fd
  17193. };
  17194. description.fdSrc = fdSrc;
  17195. Logger.info('heanup initQueueItem', `使用本地文件投播: ${localPath}, fd: ${this.castFile.fd}`);
  17196. }
  17197. this.castItem = {
  17198. itemId: this.curIndex,
  17199. description: description
  17200. };
  17201. Logger.info('heanup initQueueItem', `投播项目创建完成: ${JSON.stringify({
  17202. title: description.title,
  17203. mediaType: description.mediaType,
  17204. hasMediaUri: !!description.mediaUri,
  17205. hasFdSrc: !!description.fdSrc,
  17206. duration: description.duration
  17207. })}`);
  17208. }
  17209. // 判断是否是 URL 或流媒体地址
  17210. private isUrl(str: string): boolean {
  17211. if (!str) {
  17212. return false;
  17213. }
  17214. // 检查常见的流媒体协议
  17215. if (str.startsWith('http://') || str.startsWith('https://') ||
  17216. str.startsWith('rtmp://') || str.startsWith('rtsp://') ||
  17217. str.startsWith('rtp://') || str.startsWith('mms://')) {
  17218. return true;
  17219. }
  17220. // 扩展的URL正则表达式,支持多种协议
  17221. const urlPattern = new RegExp(
  17222. '^((https?|ftp|rtmp|rtsp|mms|ws|rtp|wss):\\/\\/)?' + // 支持多种协议
  17223. '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // 域名
  17224. '((\\d{1,3}\\.){3}\\d{1,3})|' + // 或IPv4地址
  17225. '\\[([a-f\\d]{1,4}:){7}[a-f\\d]{1,4}\\]|' + // 或IPv6地址
  17226. 'localhost)' + // 或localhost
  17227. '(\\:\\d+)?' + // 端口号(可选)
  17228. '(\\/[-a-z\\d%_.~+]*)*' + // 路径
  17229. '(\\?[;&a-z\\d%_.~+=-]*)?' + // 查询字符串(可选)
  17230. '(\\#[-a-z\\d_]*)?$', // 片段标识符(可选)
  17231. 'i' // 不区分大小写
  17232. );
  17233. return urlPattern.test(str);
  17234. }
  17235. async stopCast() {
  17236. try {
  17237. // 使用 CastController 释放资源
  17238. if (this.castControllerWrapper) {
  17239. await this.castControllerWrapper.releaseAVCast();
  17240. Logger.info('heanup stopCast', 'CastController 释放投播控制器成功');
  17241. }
  17242. // 清空引用
  17243. this.castControllerWrapper = undefined;
  17244. this.castController = undefined;
  17245. this.castItem = undefined;
  17246. this.castFile = undefined;
  17247. } catch (error) {
  17248. Logger.error('heanup stopCast', `停止投播失败: ${error}`);
  17249. }
  17250. }
  17251. private sessionPlayCallback = (): void => {
  17252. this.playOrPause()
  17253. };
  17254. private sessionPauseCallback = (): void => {
  17255. this.pause()
  17256. };
  17257. private async playOrPause() {
  17258. if (!this.debounce()) {
  17259. return;
  17260. }
  17261. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  17262. await this.pause();
  17263. } else {
  17264. // 如果是投播模式,使用 CastController 的 play 方法
  17265. if (this.castControllerWrapper && this.isCastPlaying) {
  17266. try {
  17267. Logger.info('heanup playOrPause', '投播模式播放');
  17268. await this.castControllerWrapper.setPlaying();
  17269. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  17270. this.setIsPlaying(true);
  17271. this.updateSessionPlayState(true);
  17272. Logger.info('heanup playOrPause', '投播播放成功');
  17273. this.playChange();
  17274. } catch (error) {
  17275. Logger.error('heanup playOrPause', `投播播放失败: ${error}`);
  17276. }
  17277. } else {
  17278. console.info('onecold startPlayOrResumePlay 11064')
  17279. this.startPlayOrResumePlay();
  17280. this.playChange()
  17281. }
  17282. }
  17283. }
  17284. private sessionPlayNextCallback = (): void => {
  17285. this.playNext().catch(() => {
  17286. Logger.error('heanup sessionPlayPreviousCallback', `播放下 一首失败`);
  17287. });
  17288. };
  17289. private sessionPlayPreviousCallback = (): void => {
  17290. this.playPrevious().catch(() => {
  17291. Logger.error('heanup sessionPlayPreviousCallback', `播放上一首失败`);
  17292. });
  17293. };
  17294. private sessionStopCallback = (): void => {
  17295. this.stop()
  17296. };
  17297. private sessionFastForwardCallback = async (time?: number) => {
  17298. if (!time) {
  17299. return;
  17300. }
  17301. let curPosition: number;
  17302. if (this.castController && this.isCastPlaying) {
  17303. // 投播模式,使用UI显示的时间
  17304. curPosition = this.currentTime2 * 1000;
  17305. } else if (this.mIjkMediaPlayer != null) {
  17306. // 本地播放器模式
  17307. curPosition = this.mIjkMediaPlayer.getCurrentPosition();
  17308. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17309. curPosition = Math.max(0, curPosition - getCueTrackStartOffset(this.currentSong));
  17310. }
  17311. } else {
  17312. return;
  17313. }
  17314. let seeTime = curPosition + time * 1000;
  17315. // 限制 seekValue 在合法范围内
  17316. if (seeTime < 0) {
  17317. seeTime = 0;
  17318. } else if (seeTime > this.duration) {
  17319. seeTime = this.duration;
  17320. }
  17321. Logger.info('heanup sessionFastForwardCallback', `快进: ${time}秒, 目标位置: ${seeTime}ms`);
  17322. this.setSeekToActionProgress(seeTime);
  17323. await this.seekTo(seeTime + "", 'session-fast-forward');
  17324. };
  17325. private getActiveDuration(): number {
  17326. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17327. const cueDuration = getCueTrackDuration(this.currentSong);
  17328. if (cueDuration > 0) {
  17329. return cueDuration;
  17330. }
  17331. }
  17332. let duration = this.mIjkMediaPlayer.getDuration();
  17333. if (this.castControllerWrapper && this.isCastPlaying) {
  17334. return this.duration > 0 ? this.duration : duration;
  17335. }
  17336. if (duration <= 0 && this.duration > 0) {
  17337. duration = this.duration;
  17338. }
  17339. return duration;
  17340. }
  17341. @Builder
  17342. InlineSpectrumView() {
  17343. SpectrumView({
  17344. isVisible: this.currentSwiperIndex === 0,
  17345. isPlaying: this.CONTROL_PlayStatus === PlayStatus.PLAY
  17346. })
  17347. .width( '83%')
  17348. .height(this.isCoverOpacity() ? 80 : 100)
  17349. .margin({bottom: 3 })
  17350. .clip(true)
  17351. .zIndex(-2)
  17352. .onClick(()=>{
  17353. this.cycleSpectrumMode();
  17354. })
  17355. }
  17356. private cycleSpectrumMode(): void {
  17357. const modeNames: string[] = ['柱状', '波形', '水波纹', '圆形', '粒子', '脉冲', '镜像柱', '影子柱', '轨道线', '点阵', '星爆', '心电图', '特效'];
  17358. if (modeNames.length <= 0) {
  17359. return;
  17360. }
  17361. const nextIndex: number = (this.spectrumModeIndex + 1) % modeNames.length;
  17362. this.spectrumModeIndex = nextIndex;
  17363. PreferencesUtil.putSync('spectrumModeIndex', nextIndex);
  17364. AppStorage.setOrCreate<number>('spectrumMode', nextIndex);
  17365. Logger.info('heanup-LocalMusic', `频谱特效已顺序切换为: ${modeNames[nextIndex]}`);
  17366. }
  17367. private getSongDurationMs(song?: VideoItem): number {
  17368. if (!song || !song.duration) {
  17369. return 0;
  17370. }
  17371. const raw = song.duration.trim();
  17372. if (!raw) {
  17373. return 0;
  17374. }
  17375. const parts = raw.split(':').map((part) => Number(part));
  17376. if (parts.some((part) => Number.isNaN(part))) {
  17377. return 0;
  17378. }
  17379. let seconds = 0;
  17380. if (parts.length === 3) {
  17381. seconds = parts[0] * 3600 + parts[1] * 60 + parts[2];
  17382. } else if (parts.length === 2) {
  17383. seconds = parts[0] * 60 + parts[1];
  17384. } else if (parts.length === 1) {
  17385. seconds = parts[0];
  17386. }
  17387. return seconds > 0 ? seconds * 1000 : 0;
  17388. }
  17389. private updateCastProgress(position: number): void {
  17390. const duration = this.getActiveDuration();
  17391. if (duration <= 0) {
  17392. return;
  17393. }
  17394. this.slideEnable = true;
  17395. let pos = (position / duration) * 100;
  17396. if (pos > this.PROGRESS_MAX_VALUE) {
  17397. this.progressValue = this.PROGRESS_MAX_VALUE;
  17398. } else if (pos < 0) {
  17399. this.progressValue = 0;
  17400. } else {
  17401. this.progressValue = pos;
  17402. }
  17403. this.totalTime = this.stringForTime(duration);
  17404. if (position > duration) {
  17405. position = duration;
  17406. }
  17407. this.isCurrentTime = true;
  17408. this.currentTime = this.stringForTime(position);
  17409. this.isCurrentTime = false;
  17410. const lyricPosition = position + this.timeOffset * 1000;
  17411. this.updateLyricPosition(lyricPosition);
  17412. }
  17413. /**
  17414. * Gesture method onActionUpdate.
  17415. *
  17416. * @param event Gesture event.手势拖动设置快进和后退
  17417. */
  17418. private setSeekToActionProgress(position: number) {
  17419. // 投播模式使用this.duration,本地模式使用播放器获取
  17420. let duration = this.getActiveDuration();
  17421. let pos = 0;
  17422. if (duration > 0) {
  17423. this.slideEnable = true;
  17424. let curPercent = position / duration;
  17425. pos = curPercent * 100;
  17426. if (pos > this.PROGRESS_MAX_VALUE) {
  17427. this.progressValue = this.PROGRESS_MAX_VALUE
  17428. } else {
  17429. this.progressValue = pos;
  17430. }
  17431. }
  17432. // LogUtils.getInstance()
  17433. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  17434. this.totalTime = this.stringForTime(duration);
  17435. if (position > duration) {
  17436. position = duration;
  17437. }
  17438. this.isCurrentTime = true;
  17439. this.currentTime = this.stringForTime(position);
  17440. this.isCurrentTime = false
  17441. }
  17442. private sessionRewindCallback = async (time?: number) => {
  17443. if (!time) {
  17444. return;
  17445. }
  17446. let curPosition: number;
  17447. if (this.castController && this.isCastPlaying) {
  17448. // 投播模式,使用UI显示的时间
  17449. curPosition = this.currentTime2 * 1000;
  17450. } else if (this.mIjkMediaPlayer != null) {
  17451. // 本地播放器模式
  17452. curPosition = this.mIjkMediaPlayer.getCurrentPosition();
  17453. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17454. curPosition = Math.max(0, curPosition - getCueTrackStartOffset(this.currentSong));
  17455. }
  17456. } else {
  17457. return;
  17458. }
  17459. let seeTime = curPosition - time * 1000;
  17460. // 限制 seekValue 在合法范围内
  17461. if (seeTime < 0) {
  17462. seeTime = 0;
  17463. } else if (seeTime > this.duration) {
  17464. seeTime = this.duration;
  17465. }
  17466. Logger.info('heanup sessionRewindCallback', `快退: ${time}秒, 目标位置: ${seeTime}ms`);
  17467. this.setSeekToActionProgress(seeTime);
  17468. await this.seekTo(seeTime + "", 'session-rewind');
  17469. };
  17470. private sessionSeekCallback = async (seekTime: number) => {
  17471. Logger.info('heanup sessionSeekCallback', `收到seek请求: ${seekTime}ms, 投播模式: ${this.isCastPlaying}`);
  17472. // 投播模式直接调用seekTo,它会自动处理投播控制器的seek命令
  17473. await this.seekTo(seekTime + "", 'session-seek');
  17474. };
  17475. private async getFileSize(filePath: string): Promise<number> {
  17476. try {
  17477. const stat = await fs.stat(filePath);
  17478. return stat.size;
  17479. } catch (err) {
  17480. console.error('Failed to get file size: ' + err.message);
  17481. return 0;
  17482. }
  17483. }
  17484. private async pause(clearInterruptResumeFlag: boolean = true) {
  17485. if (clearInterruptResumeFlag) {
  17486. this.audioInterruptResumePending = false;
  17487. }
  17488. // 如果是投播模式,使用 CastController 的 pause 方法
  17489. if (this.castControllerWrapper && this.isCastPlaying) {
  17490. try {
  17491. Logger.info('heanup pause', '投播模式暂停');
  17492. await this.castControllerWrapper.setPause();
  17493. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  17494. this.setIsPlaying(false);
  17495. this.updateSessionPlayState(false);
  17496. Logger.info('heanup pause', '投播暂停成功');
  17497. } catch (error) {
  17498. Logger.error('heanup pause', `投播暂停失败: ${error}`);
  17499. }
  17500. } else if (this.mIjkMediaPlayer.isPlaying() || this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  17501. // 本地播放器模式
  17502. this.savePlaybackPosition();
  17503. if (this.mIjkMediaPlayer.isPlaying()) {
  17504. this.mIjkMediaPlayer.pause();
  17505. this.setProgress();
  17506. }
  17507. this.mDestroyPage = true;
  17508. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  17509. this.updateSessionPlayState(false)
  17510. this.playChange()
  17511. if (this.pipController) {
  17512. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  17513. PiPWindow.PiPControlStatus.PAUSE);
  17514. }
  17515. }
  17516. }
  17517. private stop() {
  17518. this.audioInterruptResumePending = false;
  17519. this.clearInitialSeekGuardTimer();
  17520. this.waitInitialSeekBeforeStart = false;
  17521. this.pendingMemorySeekPosition = 0;
  17522. this.isPlayerLoading = false;
  17523. this.savePlaybackPosition();
  17524. this.CONTROL_PlayStatus = PlayStatus.INIT;
  17525. this.mIjkMediaPlayer.stop();
  17526. this.mIjkMediaPlayer.release();
  17527. this.stopProgressTask();
  17528. this.updateSessionPlayState(false)
  17529. this.playChange()
  17530. this.watchStatus();
  17531. }
  17532. //保持记忆播放功能
  17533. private savePlaybackPosition() {
  17534. if (this.mIjkMediaPlayer != null) {
  17535. let position = this.mIjkMediaPlayer.getCurrentPosition();
  17536. // ToastUtil.showToast('保存记忆播放 = ' + position)
  17537. let duration = this.mIjkMediaPlayer.getDuration();
  17538. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17539. position = Math.max(0, position - getCueTrackStartOffset(this.currentSong));
  17540. const cueDuration = getCueTrackDuration(this.currentSong);
  17541. if (cueDuration > 0) {
  17542. duration = cueDuration;
  17543. }
  17544. }
  17545. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  17546. // 如果播放位置接近视频末尾,则保存 position 为 0
  17547. const playbackPosition = (duration - position < threshold) ? 0 : position;
  17548. const memoryKey = this.activePlaybackMemoryKey || this.getPlaybackMemoryKey();
  17549. PreferencesUtil.putSync(memoryKey, playbackPosition);
  17550. }
  17551. }
  17552. private buildPlaybackMemoryKey(song?: VideoItem, playbackUrl?: string): string {
  17553. if (song && isRemoteCloudType(song.type)) {
  17554. const accountId = song.webdav_account_id || 'unknown';
  17555. const stablePath = song.remote_rel_path || song.id || song.baiduFsId || song.filePath || playbackUrl || '';
  17556. return `memory_play_remote:${song.type}:${accountId}:${stablePath}`;
  17557. }
  17558. if (song && isCueSplitItem(song)) {
  17559. return `memory_play_local_cue:${song.filePath}`;
  17560. }
  17561. return playbackUrl || '';
  17562. }
  17563. private getPlaybackMemoryKey(): string {
  17564. return this.buildPlaybackMemoryKey(this.currentSong, this.videoUrl);
  17565. }
  17566. private restoreRemotePlaybackPositionSafely(position: number, token: number, retryCount: number = 0): void {
  17567. if (token !== this.remoteRestoreSeekToken) {
  17568. return;
  17569. }
  17570. if (!this.mIjkMediaPlayer || position <= 0) {
  17571. if (this.waitInitialSeekBeforeStart) {
  17572. this.finishInitialSeekWait('invalid-memory-position', true);
  17573. }
  17574. return;
  17575. }
  17576. const duration = this.getActiveDuration();
  17577. const currentPos = this.mIjkMediaPlayer.getCurrentPosition();
  17578. let safePosition = position;
  17579. if (duration > 0) {
  17580. safePosition = Math.max(0, Math.min(position, duration - 500));
  17581. } else {
  17582. safePosition = Math.max(0, position);
  17583. }
  17584. if (safePosition <= 0) {
  17585. if (this.waitInitialSeekBeforeStart) {
  17586. this.finishInitialSeekWait('memory-position-too-small', true);
  17587. }
  17588. return;
  17589. }
  17590. if (retryCount === 0 && duration <= 0 && currentPos <= 0) {
  17591. Logger.info(TAG, `远程记忆seek提前尝试: pos=${safePosition}, duration=${duration}, current=${currentPos}`);
  17592. }
  17593. this.seekTo(safePosition + "", retryCount === 0 ? 'remote-memory-restore' : 'remote-memory-retry');
  17594. if (retryCount >= this.remoteMemorySeekMaxRetryCount) {
  17595. return;
  17596. }
  17597. setTimeout(() => {
  17598. if (token !== this.remoteRestoreSeekToken || !this.waitInitialSeekBeforeStart || !this.mIjkMediaPlayer) {
  17599. return;
  17600. }
  17601. const latestPos = this.mIjkMediaPlayer.getCurrentPosition();
  17602. if (Math.abs(latestPos - safePosition) <= 1500) {
  17603. return;
  17604. }
  17605. this.restoreRemotePlaybackPositionSafely(position, token, retryCount + 1);
  17606. }, this.remoteMemorySeekRetryIntervalMs);
  17607. }
  17608. //获取记忆播放功能
  17609. private restorePlaybackPosition() {
  17610. const position: number = this.pendingMemorySeekPosition > 0 ?
  17611. this.pendingMemorySeekPosition : PreferencesUtil.getNumberSync(this.getPlaybackMemoryKey(), 0);
  17612. if (!this.mIjkMediaPlayer || position <= 0) {
  17613. if (this.waitInitialSeekBeforeStart) {
  17614. this.finishInitialSeekWait('no-memory-position', true);
  17615. }
  17616. return;
  17617. }
  17618. const isRemoteSong = this.currentSong ? isRemoteCloudType(this.currentSong.type) : false;
  17619. if (isRemoteSong && this.videoUrl.includes('://')) {
  17620. const token = this.remoteRestoreSeekToken;
  17621. this.restoreRemotePlaybackPositionSafely(position, token);
  17622. return;
  17623. }
  17624. const duration = this.getActiveDuration();
  17625. let safePosition = position;
  17626. if (duration > 0) {
  17627. safePosition = Math.max(0, Math.min(position, duration - 500));
  17628. } else {
  17629. safePosition = Math.max(0, position);
  17630. }
  17631. if (safePosition <= 0) {
  17632. if (this.waitInitialSeekBeforeStart) {
  17633. this.finishInitialSeekWait('memory-position-too-small', true);
  17634. }
  17635. return;
  17636. }
  17637. this.seekTo(safePosition + "", isRemoteSong ? 'remote-memory-restore' : 'memory-restore');
  17638. }
  17639. private async seekTo(value: string, source: string = 'internal') {
  17640. // if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  17641. // ToastUtil.showToast('wma格式不支持拖动快进。')
  17642. // return
  17643. // }
  17644. // 如果是投播模式,使用 CastController 的 seek 方法
  17645. if (this.castControllerWrapper && this.isCastPlaying) {
  17646. try {
  17647. let seekPos = Number.parseInt(value);
  17648. const cueTrackItem = this.currentSong && isCueSplitItem(this.currentSong) ? this.currentSong : undefined;
  17649. const cueTrackStartOffset = cueTrackItem ? getCueTrackStartOffset(cueTrackItem) : 0;
  17650. const cueTrackEndOffset = cueTrackItem ? getCueTrackEndOffset(cueTrackItem) : 0;
  17651. const duration = this.getActiveDuration();
  17652. if (duration > 0) {
  17653. seekPos = Math.max(0, Math.min(seekPos, duration - 200));
  17654. }
  17655. if (cueTrackItem) {
  17656. seekPos += cueTrackStartOffset;
  17657. if (cueTrackEndOffset > cueTrackStartOffset) {
  17658. seekPos = Math.min(seekPos, cueTrackEndOffset - 200);
  17659. }
  17660. }
  17661. this.beginSeekTrace(source, seekPos);
  17662. this.isSeekTo = true;
  17663. Logger.info(
  17664. TAG,
  17665. `[seek] cast dispatch, source=${source}, target=${seekPos}, duration=${duration}, ` +
  17666. `uiDuration=${this.duration}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  17667. );
  17668. // 检查是否接近末尾
  17669. if (this.duration > 0 && seekPos >= this.duration - 500) {
  17670. Logger.warn('heanup seekTo', `快进位置接近末尾(${seekPos}ms >= ${this.duration}ms),可能触发播放完成`);
  17671. }
  17672. await this.castControllerWrapper.seek(seekPos);
  17673. Logger.info('heanup seekTo', `投播seek命令发送成功,位置: ${seekPos}ms`);
  17674. } catch (error) {
  17675. Logger.error('heanup seekTo', `投播seek失败: ${error}`);
  17676. }
  17677. } else {
  17678. // 本地播放器模式
  17679. let seekPos = Number.parseInt(value);
  17680. if (Number.isNaN(seekPos)) {
  17681. return;
  17682. }
  17683. const cueTrackItem = this.currentSong && isCueSplitItem(this.currentSong) ? this.currentSong : undefined;
  17684. const cueTrackStartOffset = cueTrackItem ? getCueTrackStartOffset(cueTrackItem) : 0;
  17685. const cueTrackEndOffset = cueTrackItem ? getCueTrackEndOffset(cueTrackItem) : 0;
  17686. const duration = this.getActiveDuration();
  17687. const isRemoteSong = this.currentSong ? isRemoteCloudType(this.currentSong.type) : false;
  17688. if (duration > 0) {
  17689. seekPos = Math.max(0, Math.min(seekPos, duration - 200));
  17690. } else if (seekPos < 0) {
  17691. seekPos = 0;
  17692. }
  17693. if (cueTrackItem) {
  17694. seekPos += cueTrackStartOffset;
  17695. if (cueTrackEndOffset > cueTrackStartOffset) {
  17696. seekPos = Math.min(seekPos, cueTrackEndOffset - 200);
  17697. }
  17698. }
  17699. if (isRemoteSong && duration <= 0 && seekPos > 0) {
  17700. Logger.warn(TAG, `seekTo 跳过未知时长远程seek: ${seekPos}ms`);
  17701. return;
  17702. }
  17703. if (isRemoteSong && duration <= 0) {
  17704. Logger.info(TAG, `seekTo 远程歌曲时长未知,仅允许起点seek: ${seekPos}ms`);
  17705. }
  17706. if (source !== 'internal') {
  17707. this.beginSeekTrace(source, seekPos);
  17708. }
  17709. if (this.handleBlockedSeek(seekPos, source)) {
  17710. return;
  17711. }
  17712. this.isSeekTo = true
  17713. try {
  17714. if (isRemoteSong || source !== 'internal' || this.isSeekTraceActive()) {
  17715. Logger.info(
  17716. TAG,
  17717. `[seek] player dispatch, source=${source}, target=${seekPos}, activeDuration=${duration}, ` +
  17718. `playerDuration=${this.mIjkMediaPlayer.getDuration()}, current=${this.mIjkMediaPlayer.getCurrentPosition()}, ` +
  17719. `isPlaying=${this.mIjkMediaPlayer.isPlaying()}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  17720. );
  17721. }
  17722. this.mIjkMediaPlayer.seekTo(seekPos + "");
  17723. this.logSeekTrace('seek-dispatched', this.mIjkMediaPlayer.getCurrentPosition(), this.mIjkMediaPlayer.getDuration(), true);
  17724. this.setProgress()
  17725. } catch (error) {
  17726. Logger.error(TAG, `本地播放器seek失败: ${error}`);
  17727. this.logSeekTrace('seek-dispatch-error', undefined, undefined, true);
  17728. } finally {
  17729. this.isSeekTo = false
  17730. }
  17731. }
  17732. }
  17733. // 添加到下一首播放
  17734. private addToNextPlay(song: VideoItem) {
  17735. if (!this.debounce()) {
  17736. return;
  17737. }
  17738. if (this.currentSong) {
  17739. if (this.currentSong === song) {
  17740. ToastUtil.showToast('当前已经在播放这首歌了!')
  17741. return
  17742. }
  17743. }
  17744. // 如果未开始播放或队列为空
  17745. if (this.curIndex === -1 || this.songList.length === 0) {
  17746. this.songList = [song];
  17747. this.curIndex = 0;
  17748. this.doPlay(song)
  17749. return;
  17750. }
  17751. // 插入到当前索引+1的位置
  17752. const insertPos = this.curIndex + 1;
  17753. this.songList.splice(insertPos, 0, song);
  17754. this.songList = [...this.songList]; // 触发状态更新
  17755. this.sonDataSource.pushArrayData(this.songList)
  17756. ToastUtil.showToast('已添加至下一首播放')
  17757. }
  17758. //后退10s,可再设置设置默认几秒
  17759. async backForward() {
  17760. // 如果是投播模式,从currentTime2获取当前位置
  17761. let pos: number;
  17762. if (this.castController && this.isCastPlaying) {
  17763. pos = this.currentTime2 * 1000; // 使用秒转毫秒
  17764. Logger.info('heanup backForward', `投播模式当前位置: ${pos}ms`);
  17765. } else if (this.mIjkMediaPlayer) {
  17766. pos = this.mIjkMediaPlayer.getCurrentPosition();
  17767. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17768. pos = Math.max(0, pos - getCueTrackStartOffset(this.currentSong));
  17769. }
  17770. } else {
  17771. return;
  17772. }
  17773. let value = pos - Number(this.fastForwardSeconds) * 1000;
  17774. if (value < 0) {
  17775. value = 0;
  17776. }
  17777. await this.seekTo(value + "", 'rewind-button');
  17778. }
  17779. //快进10s,可再设置设置默认几秒
  17780. async fastForward() {
  17781. // 如果是投播模式,从currentTime2获取当前位置
  17782. let pos: number;
  17783. if (this.castController && this.isCastPlaying) {
  17784. pos = this.currentTime2 * 1000; // 使用秒转毫秒
  17785. Logger.info('heanup fastForward', `投播模式当前位置: ${pos}ms`);
  17786. } else if (this.mIjkMediaPlayer) {
  17787. pos = this.mIjkMediaPlayer.getCurrentPosition();
  17788. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17789. pos = Math.max(0, pos - getCueTrackStartOffset(this.currentSong));
  17790. }
  17791. } else {
  17792. return;
  17793. }
  17794. let value = pos + Number(this.fastForwardSeconds) * 1000;
  17795. // 限制不超过总时长
  17796. if (this.duration > 0 && value > this.duration) {
  17797. value = this.duration;
  17798. }
  17799. await this.seekTo(value + "", 'fast-forward-button');
  17800. }
  17801. //下一个
  17802. private async playNext() {
  17803. this.lyricController.setLyric(null)
  17804. this.lyricControllerXF.setLyric(null)
  17805. this.lyricControllerSingle.setLyric(null)
  17806. Logger.info('heanup playNext', '========== playNext 开始 ==========');
  17807. Logger.info('heanup playNext', `isCastPlaying=${this.isCastPlaying}, castControllerWrapper存在=${!!this.castControllerWrapper}`);
  17808. if (!this.debounce()) {
  17809. Logger.warn('heanup playNext', 'debounce() 返回 false,退出');
  17810. return;
  17811. }
  17812. Logger.info('heanup playNext', `playType=${this.playType}`);
  17813. if (this.playType == 3) { //3:随机播放
  17814. Logger.info('heanup playNext', '随机播放模式');
  17815. await this.randomPlay()
  17816. return;
  17817. }
  17818. if (ArrayUtil.isNotEmpty(this.songList)) {
  17819. if (this.curIndex >= this.songList.length - 1) {
  17820. // playType=0 或 3: 尝试加载更多或循环
  17821. // playType=4: 不循环,检查是否是最后一首
  17822. if (this.playType == 4) {
  17823. // 连续播放不循环模式:到达最后一首时停止播放
  17824. Logger.info('heanup playNext', '连续播放不循环模式:已到达最后一首,停止播放');
  17825. ToastUtil.showToast('已经是最后一首了');
  17826. this.showRePlay();
  17827. this.currentTime = this.stringForTime(this.getActiveDuration());
  17828. this.progressValue = this.PROGRESS_MAX_VALUE;
  17829. this.slideEnable = false;
  17830. this.stop();
  17831. return;
  17832. }
  17833. await this.tryLoadNextPageForPlayback();
  17834. }
  17835. if (this.curIndex >= this.songList.length - 1) {
  17836. // playType=4 不应该执行到这里,因为上面已经return了
  17837. this.curIndex = 0;
  17838. } else {
  17839. this.curIndex++;
  17840. }
  17841. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  17842. this.currentSong = this.songList[this.curIndex];
  17843. console.info('heanup playNext', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  17844. const nextLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  17845. const nextUrl = await this.resolvePlaybackUrlForCurrentSong('playNext');
  17846. if (!nextUrl) {
  17847. if (nextLoading) {
  17848. this.hideLoadIng();
  17849. }
  17850. return;
  17851. }
  17852. this.videoUrl = nextUrl;
  17853. this.artist = this.songList[this.curIndex].artist
  17854. this.name = this.songList[this.curIndex].name
  17855. //this.cover = this.songList[this.curIndex].pixelMapPath
  17856. console.info('heanup playNext 1 ', `this.isCastPlaying: ${ this.isCastPlaying}`)
  17857. console.info('heanup playNext 2 ', `this.castControllerWrapper: ${this.castControllerWrapper}`)
  17858. // 如果是投播模式,使用 CastController 播放下一首
  17859. if (this.castControllerWrapper) {
  17860. console.info('heanup playNext', '使用 CastController 播放下一首');
  17861. try {
  17862. const nextDuration = this.getSongDurationMs(this.currentSong);
  17863. if (nextDuration > 0) {
  17864. this.duration = nextDuration;
  17865. this.durationTime = Math.floor(nextDuration / 1000);
  17866. this.durationStringTime = secondToTime(this.durationTime);
  17867. this.totalTime = this.stringForTime(nextDuration);
  17868. this.avSessionController.setAVMetadataMusic(this.currentSong, nextDuration, this.lyricContent);
  17869. }
  17870. this.updateCastProgress(0);
  17871. await this.castControllerWrapper.playNext(this.songList, this.curIndex, this.videoUrl, nextDuration);
  17872. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  17873. if (nextLoading) {
  17874. this.hideLoadIng();
  17875. }
  17876. console.info('heanup playNext', 'CastController 播放下一首成功');
  17877. return;
  17878. } catch (error) {
  17879. console.error('heanup playNext', `CastController 播放下一首失败: ${error}`);
  17880. // 如果投播失败,回退到本地播放
  17881. this.isCastPlaying = false;
  17882. }
  17883. }
  17884. // 本地播放器模式,需要先stop
  17885. this.CONTROL_PlayStatus = PlayStatus.INIT;
  17886. this.stop();
  17887. if (nextLoading) {
  17888. this.showLoadIng();
  17889. }
  17890. this.changeImageAnimation()
  17891. }
  17892. }
  17893. changeImageAnimation() {
  17894. if(this.openSkipSongAnimate){
  17895. // 第一步:淡出动画
  17896. this.getUIContext()?.animateTo({
  17897. duration: 500,
  17898. curve: Curve.EaseOut,
  17899. }, () => {
  17900. this.opacityValueImage = 0.1;
  17901. if(this.isCoverRectangle){
  17902. this.scaleValueImage = 0.88
  17903. }
  17904. });
  17905. // 第二步:切换图片后淡入
  17906. setTimeout(() => {
  17907. this.cover = this.songList[this.curIndex].pixelMapPath
  17908. this.getUIContext()?.animateTo({
  17909. duration: 500,
  17910. curve: Curve.EaseIn,
  17911. }, () => {
  17912. this.opacityValueImage = 1;
  17913. this.scaleValueImage = 1 // 图标恢复到原始大小
  17914. this.startPlayOrResumePlay()
  17915. });
  17916. }, 500);
  17917. }else{
  17918. this.cover = this.songList[this.curIndex].pixelMapPath
  17919. this.startPlayOrResumePlay()
  17920. }
  17921. }
  17922. // 内部方法:提前缓存下一首
  17923. private async preloadNextSongInternal(): Promise<void> {
  17924. // 随机模式下传递已播放索引集合
  17925. if (this.playType === 3) {
  17926. this.preloadNextRandomIndex = await preloadNextSongIfNeeded(
  17927. this.songList,
  17928. this.curIndex,
  17929. this.playType,
  17930. this.playedIndices
  17931. );
  17932. } else {
  17933. this.preloadNextRandomIndex = await preloadNextSongIfNeeded(
  17934. this.songList,
  17935. this.curIndex,
  17936. this.playType
  17937. );
  17938. }
  17939. }
  17940. // 存储已播放的歌曲索引
  17941. private playedIndices: Set<number> = new Set();
  17942. // 存储已播放的本地歌曲路径(随机播放去重用)
  17943. private playedLocalFilePaths: Set<string> = new Set();
  17944. // 随机播放模式下的播放历史栈(记录实际播放顺序,用于"上一首"功能)
  17945. private randomPlayHistory: VideoItem[] = [];
  17946. //随机播放
  17947. private async randomPlay() {
  17948. // if (!this.debounce()) {
  17949. // return;
  17950. // }
  17951. // 网盘模式: 渐进式扩展播放库的随机播放
  17952. // 通过检查当前歌曲类型判断是否为网盘音乐(而非modeType,因为不同网盘类型modeType不同)
  17953. const isCloudSong = this.currentSong && isRemoteCloudType(this.currentSong.type);
  17954. if (isCloudSong) {
  17955. const findRemoteQueue = getFindVideoItems();
  17956. const isSameFindQueue = this.songList.length === findRemoteQueue.length &&
  17957. this.songList.every((item: VideoItem, index: number) => item.filePath === findRemoteQueue[index]?.filePath);
  17958. const useFindRemoteQueue = this.playQueueScope === 'playlist' &&
  17959. findRemoteQueue.length > 0 &&
  17960. isSameFindQueue &&
  17961. findRemoteQueue.every((item: VideoItem) => isRemoteCloudType(item.type)) &&
  17962. findRemoteQueue.some((item: VideoItem) => item.filePath === this.currentSong?.filePath);
  17963. // 阈值常量
  17964. const UNPLAYED_THRESHOLD = 10; // 剩余未播放歌曲阈值
  17965. const LOAD_MORE_PAGES = 3; // 每次加载页数
  17966. // 获取网盘播放列表
  17967. const navidromeList = useFindRemoteQueue ? [] : getNavidromeVideoItems();
  17968. const webdavList = useFindRemoteQueue ? [] : getWebdavVideoItems();
  17969. const isNavidrome = !useFindRemoteQueue && navidromeList.length > 0;
  17970. const remoteList = useFindRemoteQueue ? findRemoteQueue : (isNavidrome ? navidromeList : webdavList);
  17971. if (remoteList.length > 0) {
  17972. // 将当前歌加入历史栈
  17973. if (this.currentSong) {
  17974. this.randomPlayHistory.unshift(this.currentSong);
  17975. if (this.randomPlayHistory.length > 50) {
  17976. this.randomPlayHistory = this.randomPlayHistory.slice(0, 50);
  17977. }
  17978. // 标记当前歌曲为已播放
  17979. markAsPlayed(this.currentSong.filePath);
  17980. Logger.info(TAG, `randomPlay(网盘模式): 将当前歌加入历史栈, 栈大小: ${this.randomPlayHistory.length}`);
  17981. }
  17982. // 检查未播放歌曲数量(仅Navidrome支持渐进式加载)
  17983. let unplayedCount = isNavidrome ? getUnplayedCount() : remoteList.length;
  17984. const totalCount = remoteList.length;
  17985. const playedCount = isNavidrome ? getPlayedCount() : 0;
  17986. Logger.info(TAG,
  17987. `randomPlay(网盘模式): source=${useFindRemoteQueue ? 'find-playlist' : (isNavidrome ? 'navidrome' : 'webdav')}, ` +
  17988. `总数${totalCount}, 已播放${playedCount}, 未播放${unplayedCount}`);
  17989. // 如果未播放数量不足阈值,且还有更多数据,触发加载更多页
  17990. if (isNavidrome && unplayedCount < UNPLAYED_THRESHOLD && hasMoreData()) {
  17991. Logger.info(TAG, `randomPlay(网盘模式): 未播放(${unplayedCount})不足阈值(${UNPLAYED_THRESHOLD}),触发加载更多`);
  17992. const loadSuccess = await triggerLoadMoreSongs(LOAD_MORE_PAGES);
  17993. if (loadSuccess) {
  17994. // 重新获取未播放数量
  17995. unplayedCount = getUnplayedCount();
  17996. Logger.info(TAG, `randomPlay(网盘模式): 加载完成,未播放数量更新为${unplayedCount}`);
  17997. }
  17998. }
  17999. // 从未播放歌曲中随机选择
  18000. let candidates: VideoItem[];
  18001. if (isNavidrome) {
  18002. candidates = getUnplayedSongs();
  18003. // 如果全部播放完,重置已播放记录
  18004. if (candidates.length === 0) {
  18005. Logger.info(TAG, 'randomPlay(网盘模式): 全部播放完毕,重置已播放记录');
  18006. clearPlayedHistory();
  18007. // 排除当前歌曲
  18008. const currentFilePath = this.currentSong?.filePath;
  18009. candidates = currentFilePath
  18010. ? getNavidromeVideoItems().filter(v => v.filePath !== currentFilePath)
  18011. : getNavidromeVideoItems();
  18012. }
  18013. } else {
  18014. // WebDAV模式:简单排除当前歌曲
  18015. const currentFilePath = this.currentSong?.filePath;
  18016. candidates = currentFilePath
  18017. ? remoteList.filter(v => v.filePath !== currentFilePath)
  18018. : remoteList;
  18019. }
  18020. if (candidates.length > 0) {
  18021. const randomIndex = Math.floor(Math.random() * candidates.length);
  18022. const randomSong = candidates[randomIndex];
  18023. // 标记为已播放
  18024. if (isNavidrome) {
  18025. markAsPlayed(randomSong.filePath);
  18026. }
  18027. Logger.info(TAG, `randomPlay(网盘模式): 从${candidates.length}首候选中随机选择: ${randomSong.name}`);
  18028. // 将选中的歌曲加入播放列表(如果不存在)
  18029. let nextIndex = this.songList.findIndex(song => song.filePath === randomSong.filePath);
  18030. if (nextIndex < 0) {
  18031. this.songList = [...this.songList, randomSong];
  18032. this.sonDataSource.pushArrayData(this.songList);
  18033. nextIndex = this.songList.length - 1;
  18034. }
  18035. this.curIndex = nextIndex;
  18036. this.playedIndices.add(this.curIndex);
  18037. this.CONTROL_PlayStatus = PlayStatus.INIT;
  18038. this.stop();
  18039. this.currentSong = randomSong;
  18040. const randomRemoteListLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  18041. const randomRemoteListUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-remote-list');
  18042. if (!randomRemoteListUrl) {
  18043. if (randomRemoteListLoading) {
  18044. this.hideLoadIng();
  18045. }
  18046. return;
  18047. }
  18048. this.videoUrl = randomRemoteListUrl;
  18049. this.name = this.currentSong.name;
  18050. this.artist = this.currentSong.artist;
  18051. this.changeImageAnimation();
  18052. return;
  18053. }
  18054. Logger.warn(TAG, 'randomPlay(网盘模式): 无可用候选歌曲,回退到默认随机逻辑');
  18055. }
  18056. }
  18057. if (this.currentSong) {
  18058. // 将当前歌加入到随机播放历史栈(在切换到新歌之前)
  18059. this.randomPlayHistory.unshift(this.currentSong);
  18060. // 限制历史栈大小,避免无限增长
  18061. if (this.randomPlayHistory.length > 50) {
  18062. this.randomPlayHistory = this.randomPlayHistory.slice(0, 50);
  18063. }
  18064. Logger.info(TAG, `randomPlay: 将当前歌加入历史栈, 栈大小: ${this.randomPlayHistory.length}`);
  18065. const isCurrentRemote = isRemoteCloudType(this.currentSong.type);
  18066. const currentFilePath = this.currentSong.filePath;
  18067. if (isCurrentRemote) {
  18068. const remoteOptions: RandomSongQueryOptions = {
  18069. type: this.currentSong.type,
  18070. excludeFilePaths: currentFilePath ? [currentFilePath] : []
  18071. };
  18072. const randomRemoteSong = await this.table.queryRandomSong(remoteOptions);
  18073. if (randomRemoteSong) {
  18074. // 验证并修正webdav_account_id
  18075. if (randomRemoteSong.webdav_account_id) {
  18076. const manager = RemoteDriveManager.getInstance();
  18077. const account = await manager.getWebDavAccountById(randomRemoteSong.webdav_account_id);
  18078. if (!account) {
  18079. Logger.warn(TAG, `随机播放的歌曲账号ID无效: ${randomRemoteSong.webdav_account_id}, 尝试查找同类型账号`);
  18080. // 获取所有账号,查找相同类型的账号
  18081. const allAccounts = manager.getAllWebDavAccounts();
  18082. let foundAccount: WebDavAccount | null = null;
  18083. for (let i = 0; i < allAccounts.length; i++) {
  18084. if (allAccounts[i].webType === randomRemoteSong.type) {
  18085. foundAccount = allAccounts[i];
  18086. break;
  18087. }
  18088. }
  18089. if (foundAccount && foundAccount.id) {
  18090. Logger.info(TAG, `找到同类型账号,更新webdav_account_id: ${randomRemoteSong.webdav_account_id} -> ${foundAccount.id}`);
  18091. randomRemoteSong.webdav_account_id = foundAccount.id.toString();
  18092. // 更新数据库记录
  18093. await this.table.updateWebDavAccountId(randomRemoteSong.filePath, foundAccount.id.toString());
  18094. } else {
  18095. Logger.error(TAG, `无法找到类型为${randomRemoteSong.type}的账号,跳过此歌曲`);
  18096. return;
  18097. }
  18098. }
  18099. }
  18100. let nextIndex = this.songList.findIndex(song => song.filePath === randomRemoteSong.filePath);
  18101. if (nextIndex < 0) {
  18102. this.songList = [...this.songList, randomRemoteSong];
  18103. this.sonDataSource.pushArrayData(this.songList);
  18104. nextIndex = this.songList.length - 1;
  18105. }
  18106. this.curIndex = nextIndex;
  18107. this.playedIndices.add(this.curIndex);
  18108. this.CONTROL_PlayStatus = PlayStatus.INIT;
  18109. this.stop();
  18110. this.currentSong = randomRemoteSong;
  18111. const randomRemoteDbLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  18112. const randomRemoteUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-remote-db');
  18113. if (!randomRemoteUrl) {
  18114. if (randomRemoteDbLoading) {
  18115. this.hideLoadIng();
  18116. }
  18117. return;
  18118. }
  18119. this.videoUrl = randomRemoteUrl;
  18120. this.name = this.currentSong.name;
  18121. this.artist = this.currentSong.artist;
  18122. this.changeImageAnimation();
  18123. return;
  18124. }
  18125. Logger.warn(TAG, '随机播放未获取到网盘歌曲,回退到列表随机');
  18126. } else {
  18127. if (currentFilePath) {
  18128. this.playedLocalFilePaths.add(currentFilePath);
  18129. }
  18130. // 根据modeType构建不同的查询选项
  18131. const localOptions: RandomSongQueryOptions = {
  18132. type: CommonConstants.TYPE_LOCAL,
  18133. excludeFilePaths: Array.from(this.playedLocalFilePaths)
  18134. };
  18135. Logger.info(TAG, `randomPlay: 本地播放模式, modeType=${this.modeType}, currentPlaylistSongFilePaths.length=${this.currentPlaylistSongFilePaths.length}, currentPath=${this.currentPath}`);
  18136. // modeType==0: 文件夹模式,添加parentPath过滤
  18137. if (this.modeType === 0 && this.currentPath) {
  18138. localOptions.parentPath = this.currentPath;
  18139. Logger.info(TAG, `randomPlay: 文件夹模式, parentPath=${this.currentPath}`);
  18140. }
  18141. // modeType==4: 歌单模式,添加playlistSongFilePaths
  18142. else if (this.modeType === 4 && this.currentPlaylistSongFilePaths.length > 0) {
  18143. localOptions.playlistSongFilePaths = this.currentPlaylistSongFilePaths;
  18144. Logger.info(TAG, `randomPlay: 歌单模式,歌曲数量=${this.currentPlaylistSongFilePaths.length}, 前3首=${this.currentPlaylistSongFilePaths.slice(0, 3).join(', ')}`);
  18145. } else if (this.modeType === 4) {
  18146. Logger.warn(TAG, `randomPlay: 歌单模式但没有歌曲路径列表! currentPlaylistSongFilePaths.length=${this.currentPlaylistSongFilePaths.length}`);
  18147. }
  18148. let randomLocalSong = await this.table.queryRandomSong(localOptions);
  18149. if (!randomLocalSong) {
  18150. this.playedLocalFilePaths.clear();
  18151. if (currentFilePath) {
  18152. this.playedLocalFilePaths.add(currentFilePath);
  18153. }
  18154. const fallbackLocalOptions: RandomSongQueryOptions = {
  18155. type: CommonConstants.TYPE_LOCAL,
  18156. excludeFilePaths: currentFilePath ? [currentFilePath] : []
  18157. };
  18158. // fallback时也要保持modeType的过滤条件
  18159. if (this.modeType === 0 && this.currentPath) {
  18160. fallbackLocalOptions.parentPath = this.currentPath;
  18161. } else if (this.modeType === 4 && this.currentPlaylistSongFilePaths.length > 0) {
  18162. fallbackLocalOptions.playlistSongFilePaths = this.currentPlaylistSongFilePaths;
  18163. }
  18164. randomLocalSong = await this.table.queryRandomSong(fallbackLocalOptions);
  18165. }
  18166. if (randomLocalSong !== null) {
  18167. const selectedLocalSong = randomLocalSong;
  18168. let nextIndex = this.songList.findIndex(song => song.filePath === selectedLocalSong.filePath);
  18169. if (nextIndex < 0) {
  18170. this.songList = [...this.songList, selectedLocalSong];
  18171. this.sonDataSource.pushArrayData(this.songList);
  18172. nextIndex = this.songList.length - 1;
  18173. }
  18174. this.curIndex = nextIndex;
  18175. this.playedIndices.add(this.curIndex);
  18176. this.CONTROL_PlayStatus = PlayStatus.INIT;
  18177. this.stop();
  18178. this.currentSong = selectedLocalSong;
  18179. const randomLocalUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-local-db');
  18180. if (!randomLocalUrl) {
  18181. return;
  18182. }
  18183. this.videoUrl = randomLocalUrl;
  18184. this.name = this.currentSong.name;
  18185. this.artist = this.currentSong.artist;
  18186. this.changeImageAnimation();
  18187. return;
  18188. }
  18189. Logger.warn(TAG, '随机播放未获取到本地歌曲,回退到列表随机');
  18190. }
  18191. }
  18192. if (ArrayUtil.isNotEmpty(this.songList)) {
  18193. if (this.curIndex >= 0 && this.curIndex < this.songList.length) {
  18194. this.playedIndices.add(this.curIndex);
  18195. }
  18196. if (this.songList.length > 3) {
  18197. // 优先使用预缓存的随机索引(仅网盘播放时)
  18198. const nextSong = this.songList[this.preloadNextRandomIndex >= 0 ? this.preloadNextRandomIndex : 0];
  18199. const isNextRemote = nextSong && isRemoteCloudType(nextSong.type);
  18200. const isCurrentRemote = this.currentSong && isRemoteCloudType(this.currentSong.type);
  18201. if (this.preloadNextRandomIndex >= 0 && this.preloadNextRandomIndex < this.songList.length && isNextRemote && isCurrentRemote) {
  18202. Logger.info('heanup randomPlay', `使用预缓存的随机索引: ${this.preloadNextRandomIndex} (网盘播放)`);
  18203. this.curIndex = this.preloadNextRandomIndex;
  18204. this.playedIndices.add(this.curIndex);
  18205. this.preloadNextRandomIndex = -1; // 重置预缓存索引
  18206. // 立即预缓存下一首,避免下次点击时没有预缓存
  18207. void this.preloadNextSongInternal();
  18208. } else {
  18209. // 如果没有预缓存索引,则正常随机选择
  18210. // 如果所有歌曲都播放过一次,清空已播放索引集合
  18211. if (this.playedIndices.size === this.songList.length) {
  18212. this.playedIndices.clear();
  18213. }
  18214. // 随机选择一个未播放的歌曲索引
  18215. let newIndex: number;
  18216. // 添加超时机制防止无限循环
  18217. let attempt = 0;
  18218. const maxAttempts = 100; // 根据需求调整
  18219. do {
  18220. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  18221. attempt++;
  18222. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  18223. if (attempt >= maxAttempts) {
  18224. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  18225. newIndex = Math.floor(Math.random() * this.songList.length);
  18226. }
  18227. this.curIndex = newIndex;
  18228. this.playedIndices.add(newIndex);
  18229. }
  18230. } else {
  18231. // 当歌曲数量小于或等于3时,直接播放下一首
  18232. if (this.curIndex == this.songList.length - 1) {
  18233. this.curIndex = 0;
  18234. } else {
  18235. this.curIndex++;
  18236. }
  18237. }
  18238. this.CONTROL_PlayStatus = PlayStatus.INIT;
  18239. this.stop();
  18240. this.currentSong = this.songList[this.curIndex];
  18241. const randomFallbackLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  18242. const randomFallbackUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-fallback');
  18243. if (!randomFallbackUrl) {
  18244. if (randomFallbackLoading) {
  18245. this.hideLoadIng();
  18246. }
  18247. return;
  18248. }
  18249. this.videoUrl = randomFallbackUrl;
  18250. this.name = this.songList[this.curIndex].name;
  18251. this.artist = this.songList[this.curIndex].artist
  18252. // this.cover = this.songList[this.curIndex].pixelMapPath
  18253. this.changeImageAnimation()
  18254. // 预缓存下一首(包括网盘和本地)
  18255. void this.preloadNextSongInternal();
  18256. }
  18257. }
  18258. private async playIndex(index: number) {
  18259. if (!this.debounce()) {
  18260. return;
  18261. }
  18262. if (ArrayUtil.isNotEmpty(this.songList)) {
  18263. this.curIndex = index;
  18264. this.currentSong = this.songList[index];
  18265. const playIndexLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  18266. const playIndexUrl = await this.resolvePlaybackUrlForCurrentSong('playIndex');
  18267. if (!playIndexUrl) {
  18268. if (playIndexLoading) {
  18269. this.hideLoadIng();
  18270. }
  18271. return;
  18272. }
  18273. this.videoUrl = playIndexUrl;
  18274. this.name = this.currentSong.name
  18275. this.artist = this.currentSong.artist
  18276. // 如果是投播模式,需要为投播设备准备当前歌曲
  18277. if (this.castController && this.isCastPlaying) {
  18278. Logger.info('heanup playIndex', '投播模式播放指定歌曲,不调用本地stop()');
  18279. this.initQueueItem();
  18280. await this.prepare();
  18281. if (playIndexLoading) {
  18282. this.hideLoadIng();
  18283. }
  18284. this.cover = this.currentSong.pixelMapPath;
  18285. return;
  18286. }
  18287. // 本地播放器模式,需要先stop
  18288. this.CONTROL_PlayStatus = PlayStatus.INIT;
  18289. this.stop();
  18290. if (playIndexLoading) {
  18291. this.showLoadIng();
  18292. }
  18293. this.changeImageAnimation()
  18294. }
  18295. }
  18296. //上一个
  18297. private async playPrevious() {
  18298. if (!this.debounce()) {
  18299. return;
  18300. }
  18301. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  18302. this.randomModePlayFromHistory()
  18303. return;
  18304. }
  18305. if (this.curIndex == 0) {
  18306. this.curIndex = this.songList.length - 1;
  18307. } else {
  18308. this.curIndex--;
  18309. }
  18310. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  18311. this.currentSong = this.songList[this.curIndex];
  18312. Logger.info('heanup playPrevious', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  18313. // 验证并修正webdav_account_id(针对远程类型歌曲)
  18314. if (isRemoteCloudType(this.currentSong.type) && this.currentSong.webdav_account_id) {
  18315. const manager = RemoteDriveManager.getInstance();
  18316. const account = await manager.getWebDavAccountById(this.currentSong.webdav_account_id);
  18317. if (!account) {
  18318. Logger.warn(TAG, `playPrevious: 歌曲账号ID无效: ${this.currentSong.webdav_account_id}, 尝试查找同类型账号`);
  18319. // 获取所有账号,查找相同类型的账号
  18320. const allAccounts = manager.getAllWebDavAccounts();
  18321. let foundAccount: WebDavAccount | null = null;
  18322. for (let i = 0; i < allAccounts.length; i++) {
  18323. if (allAccounts[i].webType === this.currentSong.type) {
  18324. foundAccount = allAccounts[i];
  18325. break;
  18326. }
  18327. }
  18328. if (foundAccount && foundAccount.id) {
  18329. Logger.info(TAG, `playPrevious: 找到同类型账号,更新webdav_account_id: ${this.currentSong.webdav_account_id} -> ${foundAccount.id}`);
  18330. this.currentSong.webdav_account_id = foundAccount.id.toString();
  18331. // 更新数据库记录
  18332. await this.table.updateWebDavAccountId(this.currentSong.filePath, foundAccount.id.toString());
  18333. } else {
  18334. Logger.error(TAG, `playPrevious: 无法找到类型为${this.currentSong.type}的账号,跳过此歌曲`);
  18335. // 跳过无效账号的歌曲,继续查找上一首
  18336. if (this.curIndex == 0) {
  18337. this.curIndex = this.songList.length - 1;
  18338. } else {
  18339. this.curIndex--;
  18340. }
  18341. this.currentSong = this.songList[this.curIndex];
  18342. }
  18343. }
  18344. }
  18345. const previousLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  18346. const previousUrl = await this.resolvePlaybackUrlForCurrentSong('playPrevious');
  18347. if (!previousUrl) {
  18348. if (previousLoading) {
  18349. this.hideLoadIng();
  18350. }
  18351. return;
  18352. }
  18353. this.videoUrl = previousUrl;
  18354. this.name = this.songList[this.curIndex].name
  18355. this.artist = this.songList[this.curIndex].artist
  18356. // 如果是投播模式,使用 CastController 切换上一首
  18357. if (this.castControllerWrapper) {
  18358. Logger.info('heanup playPrevious', '投播模式播放上一首,不调用本地stop()');
  18359. try {
  18360. const prevDuration = this.getSongDurationMs(this.currentSong);
  18361. if (prevDuration > 0) {
  18362. this.duration = prevDuration;
  18363. this.durationTime = Math.floor(prevDuration / 1000);
  18364. this.durationStringTime = secondToTime(this.durationTime);
  18365. this.totalTime = this.stringForTime(prevDuration);
  18366. this.avSessionController.setAVMetadataMusic(this.currentSong, prevDuration, this.lyricContent);
  18367. }
  18368. this.updateCastProgress(0);
  18369. await this.castControllerWrapper.playPrevious(this.songList, this.curIndex, this.videoUrl, prevDuration);
  18370. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  18371. if (previousLoading) {
  18372. this.hideLoadIng();
  18373. }
  18374. } catch (error) {
  18375. Logger.error('heanup playPrevious', `CastController 播放上一首失败: ${error}`);
  18376. this.isCastPlaying = false;
  18377. }
  18378. this.cover = this.songList[this.curIndex].pixelMapPath;
  18379. return;
  18380. }
  18381. // 本地播放器模式,需要先stop
  18382. this.CONTROL_PlayStatus = PlayStatus.INIT;
  18383. this.stop();
  18384. if (previousLoading) {
  18385. this.showLoadIng();
  18386. }
  18387. this.changeImageAnimation()
  18388. }
  18389. //随机播放模式下点击上一首: 播放刚刚播放过的那一首
  18390. private async randomModePlayFromHistory() {
  18391. if (this.randomPlayHistory.length >= 1) {
  18392. // 播放历史栈的第一首(刚刚播放过的)
  18393. const prevSong = this.randomPlayHistory[0];
  18394. Logger.info('heanup randomModePlayFromHistory', `从随机播放历史栈获取歌曲: ${prevSong.name}, type: ${prevSong.type}, 栈大小: ${this.randomPlayHistory.length}`);
  18395. // 从栈中移除这首歌(因为即将播放它,它应该成为当前歌,而不是历史)
  18396. this.randomPlayHistory.shift();
  18397. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  18398. this.CONTROL_PlayStatus = PlayStatus.INIT;
  18399. this.stop();
  18400. // 验证并修正webdav_account_id(针对远程类型歌曲)
  18401. if (isRemoteCloudType(prevSong.type) && prevSong.webdav_account_id) {
  18402. const manager = RemoteDriveManager.getInstance();
  18403. const account = await manager.getWebDavAccountById(prevSong.webdav_account_id);
  18404. if (!account) {
  18405. Logger.warn(TAG, `randomModePlayFromHistory: 歌曲账号ID无效: ${prevSong.webdav_account_id}, 尝试查找同类型账号`);
  18406. const allAccounts = manager.getAllWebDavAccounts();
  18407. let foundAccount: WebDavAccount | null = null;
  18408. for (let i = 0; i < allAccounts.length; i++) {
  18409. if (allAccounts[i].webType === prevSong.type) {
  18410. foundAccount = allAccounts[i];
  18411. break;
  18412. }
  18413. }
  18414. if (foundAccount && foundAccount.id) {
  18415. Logger.info(TAG, `randomModePlayFromHistory: 找到同类型账号,更新webdav_account_id: ${prevSong.webdav_account_id} -> ${foundAccount.id}`);
  18416. prevSong.webdav_account_id = foundAccount.id.toString();
  18417. await this.table.updateWebDavAccountId(prevSong.filePath, foundAccount.id.toString());
  18418. } else {
  18419. Logger.error(TAG, `randomModePlayFromHistory: 无法找到类型为${prevSong.type}的账号`);
  18420. // 无法播放这首歌,继续尝试下一首历史记录
  18421. if (this.randomPlayHistory.length >= 1) {
  18422. this.randomModePlayFromHistory();
  18423. return;
  18424. } else {
  18425. // 历史记录为空,无法继续
  18426. ToastUtil.showToast('没有更多历史记录');
  18427. return;
  18428. }
  18429. }
  18430. }
  18431. }
  18432. this.currentSong = prevSong;
  18433. const historyLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  18434. const historyUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-history');
  18435. if (!historyUrl) {
  18436. if (historyLoading) {
  18437. this.hideLoadIng();
  18438. }
  18439. return;
  18440. }
  18441. this.videoUrl = historyUrl;
  18442. this.cover = this.currentSong.pixelMapPath
  18443. this.artist = this.currentSong.artist
  18444. this.name = this.currentSong.name;
  18445. console.info('onecold startPlayOrResumePlay randomModePlayFromHistory')
  18446. this.startPlayOrResumePlay();
  18447. } else {
  18448. ToastUtil.showToast('随机播放模式暂无历史记录');
  18449. }
  18450. }
  18451. debounce() {
  18452. const delay = 600;
  18453. let cur = new Date().getTime();
  18454. if (cur - this.last > delay) {
  18455. this.last = cur;
  18456. return true;
  18457. }
  18458. return false;
  18459. }
  18460. /**
  18461. * Sets whether the screen is a constant based on the playback status.
  18462. */
  18463. watchStatus() {
  18464. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  18465. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  18466. this.windowClass.setWindowKeepScreenOn(true);
  18467. } else {
  18468. this.windowClass.setWindowKeepScreenOn(false);
  18469. }
  18470. }
  18471. /**
  18472. * Volume gesture method onActionStart.
  18473. *
  18474. * @param event Gesture event.
  18475. */
  18476. private customDialogComponentIdMM: number = 0
  18477. @Builder
  18478. customDialogComponentMM() {
  18479. Column() {
  18480. Row() {
  18481. Blank()
  18482. Text('验证密码')
  18483. .fontSize(22)
  18484. .fontColor($r('app.color.pri_bg'))
  18485. .margin({ top: 18 })
  18486. Blank()
  18487. Image($r('app.media.close'))
  18488. .fillColor(Color.White)
  18489. .margin({ top: 18, right: 18 })
  18490. .width(20)
  18491. .onClick(() => {
  18492. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  18493. })
  18494. }
  18495. .width('100%') // 使Row占据整个宽度
  18496. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  18497. Verify({
  18498. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  18499. });
  18500. }.height('60%')
  18501. .backgroundColor($r('app.color.index_background'))
  18502. .justifyContent(FlexAlign.SpaceBetween)
  18503. }
  18504. private handleVerifyCompleted(isSuccess: boolean) {
  18505. if (isSuccess) {
  18506. console.log('验证成功');
  18507. // 在这里处理验证成功后的逻辑
  18508. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  18509. this.currentPath = this.lockPath
  18510. this.getSortedFiles(this.currentPath)
  18511. } else {
  18512. // console.log('验证失败');
  18513. ToastUtil.showToast('验证失败')
  18514. }
  18515. }
  18516. private showVerifyDialog() {
  18517. promptAction.openCustomDialog({
  18518. transition: TransitionEffect.asymmetric(
  18519. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  18520. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  18521. ,
  18522. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  18523. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  18524. ),
  18525. builder: () => {
  18526. this.customDialogComponentMM()
  18527. },
  18528. isModal: true,
  18529. autoCancel: true,
  18530. maskColor: Color.Transparent,
  18531. alignment: DialogAlignment.Bottom,
  18532. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  18533. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  18534. console.log("dialog onWillDismiss")
  18535. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  18536. dismissDialogAction.dismiss()
  18537. }
  18538. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  18539. dismissDialogAction.dismiss()
  18540. }
  18541. }
  18542. }).then((dialogId: number) => {
  18543. this.customDialogComponentIdMM = dialogId
  18544. })
  18545. }
  18546. //左滑操作 移动文件 重命名 删除等操作
  18547. @Builder
  18548. DeleteButton(item: VideoItem, index: number, filePath: string) {
  18549. Row() {
  18550. //加入收藏
  18551. // Button() {
  18552. // Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  18553. // .fillColor(Color.White)
  18554. // .width(20)
  18555. // }
  18556. // .width(40)
  18557. // .height(40)
  18558. // .type(ButtonType.Circle)
  18559. // .backgroundColor(this.themeColor)
  18560. // .margin(5)
  18561. // .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  18562. // .onClick(() => {
  18563. // if (item) {
  18564. // this.doFav(item)
  18565. // }
  18566. // })
  18567. //加入下一首播放
  18568. Button() {
  18569. Image($r('app.media.next_to_play'))
  18570. .fillColor(Color.White)
  18571. .width(20)
  18572. }
  18573. .width(40)
  18574. .height(40)
  18575. .type(ButtonType.Circle)
  18576. .backgroundColor(this.themeColor)
  18577. .margin(5)
  18578. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  18579. .onClick(() => {
  18580. this.addToNextPlay(item);
  18581. })
  18582. //复制文件
  18583. Button() {
  18584. Image($r('app.media.copy'))
  18585. .fillColor(Color.White)
  18586. .width(20)
  18587. }
  18588. .width(40)
  18589. .height(40)
  18590. .type(ButtonType.Circle)
  18591. .backgroundColor(this.themeColor)
  18592. .margin(5)
  18593. .id(filePath + 'copy')
  18594. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  18595. .onClick(() => {
  18596. this.showCopyDialog(false, item, index, filePath + 'copy');
  18597. })
  18598. //移动文件
  18599. Button() {
  18600. Image($r('app.media.cut'))
  18601. .fillColor(Color.White)
  18602. .width(20)
  18603. }
  18604. .width(40)
  18605. .height(40)
  18606. .type(ButtonType.Circle)
  18607. .backgroundColor(this.themeColor)
  18608. .margin(5)
  18609. .id(filePath)
  18610. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  18611. .onClick(() => {
  18612. this.showCutDialog(false, item, index, filePath);
  18613. })
  18614. Button() {
  18615. Image($r('app.media.cut_current'))
  18616. .fillColor(Color.White)
  18617. .width(20)
  18618. }
  18619. .width(40)
  18620. .height(40)
  18621. .type(ButtonType.Circle)
  18622. .backgroundColor(this.themeColor)
  18623. .margin(5)
  18624. .id(filePath + 'current')
  18625. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  18626. (this.isHasDir ? Visibility.Visible : Visibility.None))
  18627. .onClick(() => {
  18628. this.showCutDialog(true, item, index, filePath + 'current');
  18629. })
  18630. //重命名
  18631. // Button() {
  18632. // Image($r('app.media.rename2'))
  18633. // .fillColor(Color.White)
  18634. // .width(20)
  18635. // }
  18636. // .width(40)
  18637. // .height(40)
  18638. // .type(ButtonType.Circle)
  18639. // .backgroundColor(this.themeColor)
  18640. // .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  18641. // (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  18642. // item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  18643. // .margin(5)
  18644. // .onClick(() => {
  18645. // this.showReNameDialog(item, index + '', filePath)
  18646. //
  18647. // })
  18648. Button() {
  18649. Image($r('app.media.delete2'))
  18650. .fillColor(Color.White)
  18651. .width(20)
  18652. }
  18653. .width(40)
  18654. .height(40)
  18655. .type(ButtonType.Circle)
  18656. .backgroundColor(this.themeColor)
  18657. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  18658. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  18659. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  18660. .margin({ left:5,top:5,bottom:5,right:20} )
  18661. .onClick(() => {
  18662. this.selectSingleItemForDelete(item)
  18663. this.showWarnIsDelete()
  18664. // this.showWarnIsDeleteFile(item, index + '', filePath)
  18665. })
  18666. // Button() {
  18667. // Image($r('app.media.share2'))
  18668. // .fillColor(Color.White)
  18669. // .width(20)
  18670. // }
  18671. // .width(40)
  18672. // .height(40)
  18673. // .type(ButtonType.Circle)
  18674. // .backgroundColor(this.themeColor)
  18675. // .margin(5)
  18676. // .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  18677. // .onClick(() => {
  18678. // Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  18679. // })
  18680. }
  18681. }
  18682. /**
  18683. * 穿山甲banner广告
  18684. */
  18685. // private declare bannerAd: CSJNativeExpressAd;
  18686. // @State private status: string = "未加载"
  18687. // @State private isShowAd: boolean = false
  18688. // private declare mAdSlot: AdSlot;
  18689. // private mBiddingAdm = '' //服务端bidding才需要设置
  18690. // private expressLoadAdListener: NativeExpressAdListener = {
  18691. // /**
  18692. // * 加载失败的回调
  18693. // *
  18694. // * @param code
  18695. // * @param message
  18696. // */
  18697. // onError: (code: number, message: string) => {
  18698. // console.error("加载广告失败,code=" + code + ",message=" + message);
  18699. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  18700. // },
  18701. //
  18702. // /**
  18703. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  18704. // *
  18705. // * @param ads 返回的广告列表
  18706. // */
  18707. //
  18708. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  18709. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  18710. // if (ads && ads.length > 0) {
  18711. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  18712. // ad.setExpressInteractionListener({
  18713. // /**
  18714. // *广告的点击回调
  18715. // * @param type 广告的交互类型
  18716. // */
  18717. // onAdClicked: (type: number) => {
  18718. // console.log("BannerExpressAdPage==onAdClicked......");
  18719. // },
  18720. //
  18721. // /**
  18722. // * 广告的展示回调 每个广告仅回调一次
  18723. // * @param type 广告的交互类型
  18724. // */
  18725. // onAdShow: (type: number) => {
  18726. // console.log("BannerExpressAdPage==onAdShow......");
  18727. // },
  18728. //
  18729. // /**
  18730. // * 模板渲染失败
  18731. // */
  18732. // onRenderFail: (code: number, msg: string) => {
  18733. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  18734. // },
  18735. //
  18736. // /**
  18737. // * 模板渲染成功
  18738. // * @param width 返回view的宽 单位 vp
  18739. // * @param height 返回view的高 单位 vp
  18740. // */
  18741. // onRenderSuccess: (width: number, height: number) => {
  18742. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  18743. // this.bannerAd = ad;
  18744. // this.status = "广告加载完成待展示";
  18745. //
  18746. // this.showBannerAd()
  18747. // }
  18748. // })
  18749. // //渲染广告
  18750. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  18751. // this.setDislikeCallback(ad); //设置dislike
  18752. // ad.render(this.getUIContext())
  18753. // this.status = "广告加载中...";
  18754. // });
  18755. // }
  18756. // }
  18757. // }
  18758. //
  18759. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  18760. // ad.setDislikeCallback({
  18761. // /**
  18762. // * dislike show
  18763. // */
  18764. // onShow: () => {
  18765. // console.log("BannerExpressAdPage==dislike......show");
  18766. // },
  18767. //
  18768. // /**
  18769. // * @param position 选择的位置
  18770. // * @param value 选择的内容
  18771. // * @param enforceRemove 是否强制关闭广告
  18772. // */
  18773. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  18774. // this.isShowAd = false;
  18775. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  18776. // ",enforce=" + enforceRemove);
  18777. // },
  18778. //
  18779. // /**
  18780. // * 点击取消
  18781. // */
  18782. // onCancel: () => {
  18783. // console.log("BannerExpressAdPage==dislike......onCancel");
  18784. // }
  18785. //
  18786. // })
  18787. // }
  18788. /**
  18789. * 加载Banner广告
  18790. */
  18791. loadBannerAd(rit: string) {
  18792. // if (Utility.isNoble()) {
  18793. // return
  18794. // }
  18795. // if (!Utility.isPassInstallTime(2)) {
  18796. // return
  18797. // }
  18798. // this.isShowAd = false;
  18799. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  18800. // this.mAdSlot = new AdSlotBuilder()
  18801. // .setCodeId(rit)
  18802. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  18803. // .setAdCount(1)
  18804. // .setBidAdm(this.mBiddingAdm)
  18805. // .build()
  18806. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  18807. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  18808. // this.status = "广告加载中..."
  18809. }
  18810. /**
  18811. * 展示Banner广告
  18812. */
  18813. // showBannerAd() {
  18814. // if (!this.bannerAd) {
  18815. // return
  18816. // }
  18817. // this.isShowAd = true
  18818. // this.status = "已展示"
  18819. // }
  18820. /**
  18821. * 穿山甲广告代码结束
  18822. */
  18823. /**
  18824. * 处理歌单播放请求
  18825. */
  18826. private syncWebdavQueueWithoutRestart(): void {
  18827. try {
  18828. if (!this.currentSong || !isWebDavType(this.currentSong.type)) {
  18829. return;
  18830. }
  18831. const webdavList = getWebdavVideoItems();
  18832. if (!ArrayUtil.isNotEmpty(webdavList)) {
  18833. return;
  18834. }
  18835. const currentPath = this.currentSong.filePath;
  18836. let targetIndex = webdavList.findIndex((item: VideoItem) => item.filePath === currentPath);
  18837. if (targetIndex < 0) {
  18838. const memoryIndex = getWebdavCurrentPlayIndex();
  18839. if (memoryIndex >= 0 && memoryIndex < webdavList.length) {
  18840. targetIndex = memoryIndex;
  18841. }
  18842. }
  18843. if (targetIndex < 0) {
  18844. targetIndex = 0;
  18845. }
  18846. this.songList = [...webdavList];
  18847. this.currentSongList = [...webdavList];
  18848. this.sonDataSource.pushArrayData(this.songList);
  18849. this.currentPlaylistSongFilePaths = this.songList.map(song => song.filePath);
  18850. this.curIndex = targetIndex;
  18851. PreferencesUtil.putSync('LastMusicList', this.songList);
  18852. Logger.info(TAG, `WebDAV播放队列已刷新,当前索引=${this.curIndex}, 队列长度=${this.songList.length}`);
  18853. } catch (error) {
  18854. Logger.error(TAG, `刷新WebDAV播放队列失败: ${(error as Error).message}`);
  18855. }
  18856. }
  18857. private async handlePlaylistPlayRequest(playlistId: string, playlistName:
  18858. string, songFilePaths: string[], startIndex: number, isJump: boolean, songCount?: number) {
  18859. try {
  18860. const totalCount = songCount ?? songFilePaths.length;
  18861. Logger.info(`heanup 处理歌单播放请求: ${playlistName}, 已加载: ${songFilePaths.length}, 服务端总数: ${totalCount}, 开始索引: ${startIndex}`)
  18862. // 检查是否为WebDAV播放请求
  18863. if (playlistId === 'webdav-playlist') {
  18864. Logger.info(`heanup 检测到WebDAV播放请求,从内存读取videoItems`)
  18865. // 从全局内存读取videoItems数据
  18866. const videoItems = getWebdavVideoItems();
  18867. const currentPlayIndex = getWebdavCurrentPlayIndex();
  18868. Logger.info(`heanup 从内存读取到WebDAV歌曲列表,长度:${videoItems.length},索引:${currentPlayIndex}`)
  18869. if (videoItems && videoItems.length > 0) {
  18870. // 验证webdav_account_id设置情况
  18871. const accountIds = videoItems.map(item => item.webdav_account_id).filter(id => id);
  18872. Logger.info(`heanup 有 ${accountIds.length}/${videoItems.length} 首歌曲设置了webdav_account_id`)
  18873. if(isJump){
  18874. this.setShowPlayTrue()//显示播放页
  18875. }
  18876. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName, totalCount)
  18877. return
  18878. } else {
  18879. return
  18880. }
  18881. }
  18882. if (playlistId === 'navidrome-playlist') {
  18883. Logger.info(`heanup 检测到Navidrome播放请求,从内存读取videoItems`);
  18884. const videoItems = getNavidromeVideoItems();
  18885. const currentPlayIndex = getNavidromeCurrentPlayIndex();
  18886. Logger.info(`heanup Navidrome歌曲列表长度: ${videoItems.length}, 服务端总数: ${totalCount}`);
  18887. if (videoItems && videoItems.length > 0) {
  18888. if(isJump){
  18889. this.setShowPlayTrue()//显示播放页
  18890. }
  18891. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName, totalCount);
  18892. return;
  18893. } else {
  18894. Logger.warn('heanup Navidrome播放请求缺少歌曲数据');
  18895. return;
  18896. }
  18897. }
  18898. if (playlistId === 'find-album-playlist' || playlistId.indexOf('find-') === 0) {
  18899. Logger.info(`heanup 检测到发现页播放请求,从内存读取videoItems`)
  18900. const videoItems = getFindVideoItems();
  18901. const currentPlayIndex = getFindCurrentPlayIndex();
  18902. Logger.info(`heanup 发现页歌曲列表长度: ${videoItems.length}, 索引: ${currentPlayIndex}`)
  18903. Logger.info(
  18904. TAG,
  18905. `[remote-debug] handlePlaylistPlayRequest find-memory playlist=${playlistId}, loaded=${videoItems.length}, ` +
  18906. `declaredTotal=${totalCount}, sample=${this.buildSongListDebugLog(videoItems)}`
  18907. )
  18908. if (videoItems && videoItems.length > 0) {
  18909. if (isJump) {
  18910. this.setShowPlayTrue()
  18911. }
  18912. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName, totalCount)
  18913. return
  18914. } else {
  18915. Logger.warn('heanup 发现页播放请求缺少歌曲数据')
  18916. return
  18917. }
  18918. }
  18919. // 从数据库重新加载这些歌曲,使用索引记录位置以保持顺序
  18920. const songMap: Map<number, VideoItem> = new Map()
  18921. let completedQueries = 0
  18922. Logger.info(`heanup 开始从数据库查询 ${songFilePaths.length} 首歌曲`)
  18923. // 遍历所有文件路径,使用索引记录位置
  18924. for (let i = 0; i < songFilePaths.length; i++) {
  18925. const filePath = songFilePaths[i]
  18926. const index = i
  18927. // Logger.info(`heanup 正在查询歌曲[${index}]: ${filePath}`)
  18928. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  18929. const queryPromise = this.table.queryVideoByFilePath(filePath)
  18930. // Logger.info(`heanup 创建了查询Promise,开始等待结果[${index}]: ${filePath}`)
  18931. queryPromise.then((videoItem) => {
  18932. completedQueries++
  18933. // Logger.info(`heanup 查询Promise返回结果[${index}]: ${filePath}, 找到歌曲: ${videoItem ? videoItem.name : 'null'}`)
  18934. if (videoItem) {
  18935. // 使用索引作为key保存到Map中,保持原始顺序
  18936. songMap.set(index, videoItem)
  18937. // Logger.info(`heanup 从数据库找到歌曲[${index}]: ${videoItem.name} (${completedQueries}/${songFilePaths.length})`)
  18938. } else {
  18939. Logger.warn(`heanup 数据库中未找到歌曲[${index}]: ${filePath} (${completedQueries}/${songFilePaths.length})`)
  18940. }
  18941. // 检查是否所有歌曲都已加载完成
  18942. if (completedQueries === songFilePaths.length) {
  18943. // Logger.info(`heanup 所有数据库查询完成,共找到 ${songMap.size} 首歌曲`)
  18944. // 按照索引顺序重建歌曲数组
  18945. const songs: VideoItem[] = []
  18946. for (let j = 0; j < songFilePaths.length; j++) {
  18947. const song = songMap.get(j)
  18948. if (song) {
  18949. songs.push(song)
  18950. // Logger.info(`heanup 按顺序添加歌曲[${j}]: ${song.name}`)
  18951. }
  18952. }
  18953. Logger.info(`heanup 最终歌曲列表顺序: ${songs.map((s, idx) => `[${idx}]${s.name}`).join(', ')}`)
  18954. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  18955. }
  18956. }).catch((error: Error) => {
  18957. completedQueries++
  18958. Logger.error(`heanup 查询歌曲失败[${index}]: ${filePath}, 错误: ${error.message} (${completedQueries}/${songFilePaths.length})`)
  18959. // 即使出错也要检查是否完成所有查询
  18960. if (completedQueries === songFilePaths.length) {
  18961. Logger.info(`heanup 所有数据库查询完成(包含错误),共找到 ${songMap.size} 首歌曲`)
  18962. // 按照索引顺序重建歌曲数组
  18963. const songs: VideoItem[] = []
  18964. for (let j = 0; j < songFilePaths.length; j++) {
  18965. const song = songMap.get(j)
  18966. if (song) {
  18967. songs.push(song)
  18968. }
  18969. }
  18970. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  18971. }
  18972. })
  18973. }
  18974. } catch (error) {
  18975. Logger.error('heanup 处理简化歌单播放请求失败: ' + error)
  18976. ToastUtil.showToast('播放失败')
  18977. }
  18978. }
  18979. /**
  18980. * 完成歌单加载并开始播放
  18981. */
  18982. private finishLoadingPlaylist(songs: VideoItem[], startIndex: number, playlistName: string, totalCount?: number) {
  18983. if (songs.length === 0) {
  18984. Logger.error('heanup 没有找到任何可播放的歌曲')
  18985. ToastUtil.showToast('没有找到可播放的歌曲')
  18986. return
  18987. }
  18988. this.songList = songs
  18989. this.currentSongList = songs // 同步更新 currentSongList
  18990. this.sonDataSource.pushArrayData(songs)
  18991. this.sonDataSource.notifyDataReload()
  18992. this.curIndex = startIndex
  18993. // 保存歌单的歌曲路径列表,用于随机播放
  18994. this.currentPlaylistSongFilePaths = songs.map(song => song.filePath);
  18995. const actualTotal = totalCount ?? songs.length;
  18996. // 如果是网盘播放,保存服务端总数到全局存储
  18997. if (totalCount && totalCount > 0 && songs.length > 0) {
  18998. const firstSong = songs[0];
  18999. if (firstSong && (isNavidromeType(firstSong.type) ||
  19000. isJellyfinType(firstSong.type) ||
  19001. isEmbyType(firstSong.type) ||
  19002. isAudioStationType(firstSong.type) ||
  19003. isPlexType(firstSong.type) ||
  19004. isDaoLiYuType(firstSong.type))) {
  19005. setNavidromeTotalCount(totalCount);
  19006. Logger.info('heanup finishLoadingPlaylist', `已保存服务端总数到全局存储: ${totalCount}`);
  19007. }
  19008. }
  19009. Logger.info('heanup finishLoadingPlaylist', `保存歌单歌曲路径列表,已加载=${this.currentPlaylistSongFilePaths.length}, 服务端总数=${actualTotal}`);
  19010. Logger.info(
  19011. TAG,
  19012. `[remote-debug] finishLoadingPlaylist playlist=${playlistName}, loaded=${songs.length}, actualTotal=${actualTotal}, ` +
  19013. `startIndex=${startIndex}, sample=${this.buildSongListDebugLog(songs)}`
  19014. );
  19015. if (songs[startIndex]) {
  19016. // 确保当前播放的歌曲也更新到存储
  19017. AppStorage.setOrCreate('currentSong', songs[startIndex])
  19018. // 设置isFromSonPlayList=true,避免doPlay方法重新从全局列表构建播放列表
  19019. this.doPlay(songs[startIndex], startIndex, true)
  19020. }
  19021. PreferencesUtil.putSync('LastMusicList', this.songList)
  19022. // ToastUtil.showToast(`开始播放歌单: ${playlistName}`)
  19023. }
  19024. }
  19025. //视频气泡窗口的布局
  19026. @Builder
  19027. function customPopupBuilder(dataBu: BubbleBean) {
  19028. List() {
  19029. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  19030. ListItem() {
  19031. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  19032. Row() {
  19033. Column() {
  19034. Image(dataBu.imageRes[index])
  19035. .height(28)
  19036. .fillColor(dataBu.color)
  19037. .alignSelf(ItemAlign.Center)
  19038. }
  19039. .width(32)
  19040. Text(item)
  19041. .padding({
  19042. top: 10,
  19043. bottom: 10,
  19044. right: 10,
  19045. left: 10
  19046. })
  19047. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  19048. .textAlign(TextAlign.Start)
  19049. .width("100%")
  19050. }
  19051. }
  19052. .backgroundColor($r('app.color.settings_background_main'))
  19053. .margin({ top: 6, bottom: 6 })
  19054. }
  19055. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  19056. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  19057. TransitionEffect.scale({ x: 0, y: 0 })))
  19058. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  19059. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  19060. .onClick(() => {
  19061. dataBu.onItemClick?.(index)
  19062. })
  19063. })
  19064. }
  19065. .scrollBar(BarState.Off)
  19066. .width(120)
  19067. .divider({
  19068. strokeWidth: 1,
  19069. color: "#22FFFFFF"
  19070. })
  19071. }
  19072. // Function to calculate a hash for the file list
  19073. function simpleHash(fileList: string[]): string {
  19074. let hash = 0;
  19075. const str = fileList.join(',');
  19076. for (let i = 0; i < str.length; i++) {
  19077. const char = str.charCodeAt(i);
  19078. hash = (hash << 5) - hash + char;
  19079. hash |= 0; // Convert to 32bit integer
  19080. }
  19081. return hash.toString();
  19082. }
  19083. interface MoreItem {
  19084. id: number;
  19085. image: Resource;
  19086. title: string;
  19087. }
  19088. //视频气泡窗口的布局
  19089. @Builder
  19090. function cutPopupBuilder(dataBu: BubbleBean) {
  19091. Column() {
  19092. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  19093. .padding({
  19094. top: 10,
  19095. bottom: 10,
  19096. right: 10,
  19097. left: 10
  19098. })
  19099. .textAlign(TextAlign.Start)
  19100. .width(160)
  19101. .fontWeight(666)
  19102. .fontSize(16)
  19103. List() {
  19104. ForEach(dataBu.data, (item: string, index: number) => {
  19105. ListItem() {
  19106. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  19107. Row() {
  19108. Column() {
  19109. Image($r('app.media.music_group'))
  19110. .height(28)
  19111. .fillColor(dataBu.color)
  19112. .alignSelf(ItemAlign.Center)
  19113. }
  19114. .width(32)
  19115. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  19116. .padding({
  19117. top: 10,
  19118. bottom: 10,
  19119. right: 10,
  19120. left: 10
  19121. })
  19122. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  19123. .fontSize(15)
  19124. }
  19125. }
  19126. .backgroundColor(Color.Transparent)
  19127. .margin({ top: 7, bottom: 7 })
  19128. }
  19129. .onClick(() => {
  19130. dataBu.onItemClick?.(index)
  19131. })
  19132. })
  19133. }
  19134. .scrollBar(BarState.Off)
  19135. .width(150)
  19136. .divider({
  19137. strokeWidth: 1,
  19138. color: "#22FFFFFF"
  19139. })
  19140. }
  19141. .height(300)
  19142. .padding({
  19143. bottom: 30
  19144. })
  19145. }
  19146. @Concurrent
  19147. function buildAlphabetIndexTask(items: Array<AlphaTaskItem>, sortType: number, isShowFileName: boolean): Array<string> {
  19148. const alphabetSet = new Set<string>()
  19149. for (const item of items) {
  19150. let text = isShowFileName ? (item.fileName || '') :
  19151. (item.type != CommonConstants.TYPE_IS_DIR && item.pyStr) ? item.pyStr : (item.name || '')
  19152. if (sortType === 0 || sortType == 1) {
  19153. text = item.artist || ''
  19154. } else if (sortType === 2 || sortType == 3) {
  19155. text = item.album || ''
  19156. }
  19157. if (text && text.length > 0) {
  19158. const first = getFirstLetter(text)
  19159. if (!alphabetSet.has(first)) {
  19160. alphabetSet.add(first)
  19161. }
  19162. }
  19163. }
  19164. const sorted = Array.from(alphabetSet).sort((a, b) => {
  19165. if (sortType === 4 || sortType == 0 || sortType == 2 || sortType == 6) {
  19166. return a.localeCompare(b)
  19167. }
  19168. return b.localeCompare(a)
  19169. })
  19170. return sorted
  19171. }
  19172. function getFileDirName(filePath: string,rootPath:string): string{
  19173. if(filePath===rootPath){
  19174. return '首页'
  19175. }
  19176. let result = FileUtil.getFileName(filePath)
  19177. if(StrUtil.isEmpty(result))
  19178. return ''
  19179. if(result.startsWith('.'))
  19180. result = result.replace(/\./g, '')
  19181. return result
  19182. }
  19183. //只扫描当前目录下文件(不扫描子文件夹)的方法
  19184. @Concurrent
  19185. async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
  19186. const table: MediaTable = new MediaTable(context);
  19187. try {
  19188. // 直接获取当前目录下的文件列表
  19189. const files = FileUtil.listFileSync(dirPath);
  19190. await Promise.all(files.map(async (file) => {
  19191. const fPath = `${dirPath}/${file}`;
  19192. // 跳过目录,只处理文件
  19193. if (FileUtil.isDirectory(fPath)) {
  19194. return;
  19195. }
  19196. // 跳过特定格式文件
  19197. if (fPath.endsWith('.lrc') || fPath.endsWith('.srt')) {
  19198. return;
  19199. }
  19200. // 检查是否为媒体文件
  19201. if (Utility.isMeidaByExtension(fPath)) {
  19202. let mType = CommonConstants.TYPE_LOCAL;
  19203. if (fPath.includes(lockPath)) {
  19204. mType = CommonConstants.TYPE_LOCK;
  19205. }
  19206. const mediaItem = await Utility.uriGetMusicAssetsFromFile(
  19207. context, fPath, mType, true
  19208. );
  19209. table.insert(mediaItem, (id: number) => {
  19210. // 插入回调函数
  19211. }, cover_api);
  19212. }
  19213. }));
  19214. } catch (error) {
  19215. console.error(' 扫描当前目录失败:', error);
  19216. }
  19217. }
  19218. //内嵌标签后更新库
  19219. @Concurrent
  19220. async function updateInfoDb(
  19221. context: Context,
  19222. filePath: string,
  19223. titleStr: string,
  19224. artistStr: string,
  19225. albumStr: string,
  19226. lyricConStr: string,
  19227. yearStr: string,
  19228. genreStr: string,
  19229. trackStr: string,
  19230. albumArtistStr: string,
  19231. composerStr: string,
  19232. lyricistStr: string,
  19233. commentStr: string,
  19234. discStr: string,
  19235. ): Promise<boolean> {
  19236. const table: MediaTable = new MediaTable(context);
  19237. await new Promise<void>((resolve, reject) => {
  19238. table.getRdbStore(context, (err:Error) => {
  19239. err ? reject(err) : resolve();
  19240. });
  19241. });
  19242. return await new Promise<boolean>((resolve) => {
  19243. table.updateMediaInfo(filePath, titleStr, artistStr, albumStr, lyricConStr,
  19244. yearStr, genreStr, trackStr, albumArtistStr, composerStr, lyricistStr, commentStr, discStr,
  19245. (success: boolean, error?: string) => {
  19246. if (success) {
  19247. console.log("onecold 编辑信息成功,数据库已同步");
  19248. } else {
  19249. console.error("onecold 编辑信息数据库失败原因: " + error);
  19250. }
  19251. resolve(success);
  19252. });
  19253. });
  19254. }
  19255. @Concurrent
  19256. async function replaceLocalMusicCoverTask(
  19257. context: Context,
  19258. filePath: string,
  19259. sandboxCoverPath: string
  19260. ): Promise<boolean> {
  19261. const coverResult: boolean = await changeMusicCover(context, filePath, sandboxCoverPath, true, '');
  19262. if (!coverResult) {
  19263. return false;
  19264. }
  19265. const table: MediaTable = new MediaTable(context);
  19266. await new Promise<void>((resolve, reject) => {
  19267. table.getRdbStore(context, (err: Error) => {
  19268. err ? reject(err) : resolve();
  19269. });
  19270. });
  19271. return await new Promise<boolean>((resolve) => {
  19272. table.updateCustomCoverPath(filePath, fileUri.getUriFromPath(sandboxCoverPath),
  19273. (success: boolean, _error?: string) => {
  19274. resolve(success);
  19275. });
  19276. });
  19277. }