LocalMusic.ets 732 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523
  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 { triggerLoadMoreSongs, hasMoreData } from '../common/util/NavidromeRandomLoader';
  18. import {
  19. ImplOnBufferingUpdateListener,
  20. ImplOnCompletionListener,
  21. ImplOnErrorListener,
  22. ImplOnInfoListener,
  23. ImplOnPreparedListener,
  24. ImplOnSeekCompleteListener,
  25. ImplOnTimedTextListener,
  26. ImplOnVideoSizeChangedListener
  27. } from '../common/IjkPlayerListenerImpls';
  28. import {
  29. ButtonFancyModifier,
  30. ImageFancyModifier,
  31. ShadowModifier,
  32. SymbolGlyphFancyModifier } from '../common/util/AttributeModifierUtil'
  33. import {
  34. AppUtil,
  35. ArrayUtil,
  36. Base64Util,
  37. DateUtil,
  38. DeviceUtil,
  39. FileUtil,
  40. GlobalContext,
  41. LogUtil,
  42. MD5,
  43. PreferencesUtil,
  44. RandomUtil,
  45. StrUtil,
  46. ToastUtil
  47. } from '@pura/harmony-utils';
  48. import { imagePathToPixelMap } from '../common/util/CommUtils';
  49. import LyricUtil from '../common/util/LyricUtil';
  50. import { unifiedDataChannel, uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData';
  51. import { CommonConstants } from '../common/constants/CommonConstants';
  52. import { BaiduConstants } from '../common/constants/BaiduConstants';
  53. import { EventConstants } from '../common/constants/EventConstants';
  54. import Logger from '../common/util/Logger';
  55. import { http } from '@kit.NetworkKit';
  56. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  57. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  58. import { BubbleBean } from '../viewmodel/BubbleBean';
  59. import { PopupPosition, XPopup } from '@chinalike/popup';
  60. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  61. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  62. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  63. import { MessageEvents, util, worker, ErrorEvent, JSON } from '@kit.ArkTS';
  64. import { Verify } from './Verify';
  65. import { taskpool } from '@kit.ArkTS';
  66. import { RotatingCover } from './RotatingCover';
  67. import { SpectrumView } from './spectrum/SpectrumView';
  68. import { PlayingIndicator } from './PlayingIndicator';
  69. import { PointLightButton } from './PointLight/PointLightButton';
  70. import { PlayConstants } from '../common/constants/PlayConstants';
  71. import { effectKit } from '@kit.ArkGraphics2D';
  72. import { ColorConversion } from '../common/util/ColorConversion';
  73. import { Lyric, LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  74. import { AvSessionController } from '../controller/AvSessionController';
  75. import { EqualizerManager } from '../common/util/EqualizerManager';
  76. import { EqualizerViewWithCallback } from './EqualizerView';
  77. import { CastController, CastControllerCallbacks } from '../controller/CastController';
  78. import { repairAudioMetadata, convertDsfToWav, getApiLyric,changeMusicCover} from '../common/util/MusicTagUtils';
  79. import { extractHwMediaMetadata, FFMpegTags,Utility } from '../common/util/Utility';
  80. import { TagsContentCover } from '../view/TagsContentCover';
  81. import {
  82. DeviceChangeReason,
  83. IjkMediaPlayer,
  84. InterruptEvent,
  85. InterruptHintType,
  86. LogUtils,
  87. OnBufferingUpdateListener,
  88. OnCompletionListener,
  89. OnErrorListener,
  90. OnInfoListener,
  91. OnPreparedListener,
  92. OnSeekCompleteListener,
  93. OnTimedTextListener,
  94. OnVideoSizeChangedListener
  95. } from '@ohos/ijkplayer';
  96. import { PlayStatus } from '../common/PlayStatus';
  97. import fs from '@ohos.file.fs';
  98. import { image } from '@kit.ImageKit';
  99. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  100. import { media } from '@kit.MediaKit';
  101. import { UniversalDetector } from '@ohos/juniversalchardet';
  102. import { SettingPage } from '../pages/SettingPage';
  103. import { secondToTime,getTransverterText } from '../common/util/CommUtils';
  104. import { CommonConstants2 } from '../common/util/CommonConstants2';
  105. import { hilog } from '@kit.PerformanceAnalysisKit';
  106. import { LazyDataSource } from '../common/util/LazyDataSource';
  107. import MediaTable, { PageQueryOptions, PageQueryResult, RandomSongQueryOptions } from '../common/util/MediaTable';
  108. import FileDeletionWatcher from '../common/util/FileDeletionWatcher';
  109. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  110. import { ringtone } from '@kit.RingtoneKit';
  111. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  112. import { resourceManager } from '@kit.LocalizationKit';
  113. import { deviceInfo } from '@kit.BasicServicesKit';
  114. import '../common/network/RemoteCacheRegistry';
  115. import { ServerLogUtil } from '../common/util/ServerLogUtil';
  116. import { lyricService, SongData } from '../common/service/LyricService';
  117. import { shouldResolveRemoteLyricOnPlay, tryResolveRemotePlaybackLyric } from '../common/util/RemotePlaybackLyricUtil';
  118. import {
  119. cloneVideoItem,
  120. preloadNextSongIfNeeded,
  121. setVideoUrlForSong,
  122. getTypeOrder,
  123. isWebDavType,
  124. isSmbType,
  125. isNavidromeType,
  126. isFtpType,
  127. isBaiduType,
  128. isJellyfinType,
  129. isEmbyType,
  130. isAudioStationType,
  131. isPlexType,
  132. isRemoteCloudType,
  133. mergeCoverWithPriority,
  134. WorkerEditMusicResult,
  135. WebDavMetadataUpdatePayload,
  136. isDaoLiYuType
  137. } from '../common/util/RemotePlayerUtil';
  138. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  139. import app from '@system.app';
  140. import { TextNodeController } from './PipLyricTextBuilder';
  141. import { IndexerView } from './IndexerView';
  142. import { KeyCode } from '@kit.InputKit';
  143. import { KnockController } from '../controller/KnockController';
  144. import { DeleteComptent } from '../view/DeleteComptent';
  145. import { ABLoopComptent } from '../view/ABLoopComptent';
  146. import { FixMessyView } from '../view/FixMessyView';
  147. import {
  148. parseCueFile,
  149. CueTrack,
  150. CueInfo,
  151. getCueTrackDuration,
  152. getCueTrackEndOffset,
  153. getCueTrackStartOffset,
  154. importCueTracks,
  155. isCueSplitItem
  156. } from '../common/util/CueUtils';
  157. import { CueComptent } from '../view/CueComptent';
  158. import { SearchHistoryUtil } from '../common/util/SearchHistoryUtil';
  159. import { IsoExtractComptent } from '../view/IsoExtractComptent';
  160. import PlaylistTable from '../common/util/PlaylistTable';
  161. import { showAddToPlaylistDialog } from '../dialog/AddToPlaylistDialog';
  162. import { showCreatePlaylistDialog } from '../dialog/PlaylistDialog';
  163. import { convertPlaylistSongsToVideoItems, emptyView,updateAllSongsSortOrder } from '../pages/PlaylistDetailPage';
  164. import { Playlist, PlaylistSong } from '../viewmodel/Playlist';
  165. import { Song } from '../viewmodel/Song';
  166. import { WebDavAccount } from '../viewmodel/WebDavAccount';
  167. import { SongType } from '../common/enums/SongType';
  168. import { RemoteDriveManager, WebDavAuthInfo as WebDavManagerAuthInfo,
  169. buildHttpHeadersWithWebDav,
  170. WebDavAuthItem} from '../common/util/RemoteDriveManager';
  171. import PermissionUtil from '../common/util/PermissionUtil'
  172. import { EditAudio, setRingTone } from './EditAudio';
  173. import { ExtractAccompaniment } from './ExtractAccompaniment';
  174. import { ExtractAudioFromVideo } from './ExtractAudioFromVideo';
  175. import { AudioFormatConverter } from './AudioFormatConverter';
  176. import { MergeAudio } from './MergeAudio';
  177. import { AIVoiceSeparation } from './AIVoiceSeparation';
  178. import { WebDavUrlUtil } from '../common/util/WebDavUrlUtil';
  179. import { ChangeTone } from './ChangeTone';
  180. import {
  181. hdsEffect,
  182. HdsVisualComponent,
  183. HdsSceneController,
  184. HdsSceneType,
  185. HdsVisualComponentAttribute,
  186. } from '@kit.UIDesignKit';
  187. import { GlobalAlphabetIndexerModifier } from '../Styels/GlobalStyles'
  188. import { getFirstLetter } from '../Constants';
  189. import { audio } from '@kit.AudioKit';
  190. import { PointLightDefaultButton } from './PointLight/PointLightDeFaultButton';
  191. import { CoverThumbCache } from '../common/util/CoverThumbCache';
  192. import { LyricCopySheet } from './LyricCopySheet';
  193. import {
  194. IsoArchiveAudioEntry,
  195. IsoExtractFailureDetail,
  196. IsoExtractProgressMessage,
  197. IsoExtractTaskResult,
  198. listIsoAudioEntriesTask,
  199. extractIsoAudioEntriesTask
  200. } from '../common/util/IsoArchiveUtil';
  201. const TAG = 'LocalMusic';
  202. const HICAR_LOG_TAG = 'HiCarWindow';
  203. const PREF_PLAY_COVER_SCALE_GUIDE_SHOWN = 'play_cover_scale_guide_show';
  204. function logHiCarWindow(message: string): void {
  205. void ServerLogUtil.info(HICAR_LOG_TAG, message);
  206. }
  207. export interface WorkerMetadataPayload {
  208. originFilePath: string;
  209. originId?: string;
  210. bit_rate?: string;
  211. duration?: string;
  212. sampleRate?: string;
  213. mimeType?: string;
  214. md5Str?: string;
  215. videoSize?: number;
  216. size?: string;
  217. pixelMapPath?: string;
  218. artist?: string;
  219. album?: string;
  220. name?: string;
  221. lyricContent?: string;
  222. bits_per_raw_sample?: string;
  223. channels?: string;
  224. channel_layout?: string;
  225. start_time?: string;
  226. genre?: string;
  227. year?: string;
  228. probe_score?: number;
  229. track?: string;
  230. disc?: string;
  231. ALBUMARTIST?: string;
  232. COMPOSER?: string;
  233. COMMENT?: string;
  234. LYRICIST?: string;
  235. nb_streams?: number;
  236. nb_programs?: number;
  237. error?: string;
  238. }
  239. interface WorkerMessageScanDone {
  240. code: 101;
  241. data: Record<string, never>;
  242. }
  243. interface WorkerMessageMediaList {
  244. code: 102;
  245. data: Array<VideoItem>;
  246. totalCount: number;
  247. }
  248. interface WorkerMessageArtistList {
  249. code: 103;
  250. data1: Map<string, Array<VideoItem>>;
  251. data2: Array<VideoItem>;
  252. totalCount: number;
  253. }
  254. interface WorkerMessageAlbumList {
  255. code: 104;
  256. data1: Map<string, Array<VideoItem>>;
  257. data2: Array<VideoItem>;
  258. totalCount: number;
  259. }
  260. interface WorkerMessageMetadata {
  261. code: 105;
  262. data: WorkerMetadataPayload;
  263. }
  264. interface WorkerMessageEditResult {
  265. code: 106;
  266. data: WorkerEditMusicResult;
  267. }
  268. interface AlphaTaskItem {
  269. type: number;
  270. name?: string;
  271. pyStr?: string;
  272. fileName?: string;
  273. artist?: string;
  274. album?: string;
  275. }
  276. type LocalMusicWorkerMessage =
  277. WorkerMessageScanDone
  278. | WorkerMessageMediaList
  279. | WorkerMessageArtistList
  280. | WorkerMessageAlbumList
  281. | WorkerMessageMetadata
  282. | WorkerMessageEditResult;
  283. /**
  284. * 歌单播放事件数据
  285. */
  286. interface PlaylistEventData {
  287. playlistId: string;
  288. playlistName: string;
  289. songCount: number;
  290. startIndex: number;
  291. songFilePaths: string[];
  292. isJump: boolean;
  293. webDavAuthInfo?: WebDavAuthItem; // 新增WebDAV认证信息
  294. }
  295. const DEFAULT_INDEX =
  296. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  297. 'X', 'Y', 'Z']
  298. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  299. // 元数据提取状态追踪
  300. const metadataExtractionInFlight: Map<string, Promise<void>> = new Map();
  301. // setVideoUrlForSong 函数已移至 MusicPlayerUtil.ets
  302. // 定义接口
  303. interface HiCarAspectRatio {
  304. ratio: number;
  305. name: string;
  306. }
  307. interface GeneratedObjectLiteralInterface_1 {
  308. assetId: string;
  309. title: string;
  310. artist: string;
  311. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  312. mediaUri: string;
  313. // 该字段大写,音频'AUDIO',视频'VIDEO'
  314. mediaType: string;
  315. mediaSize: number;
  316. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  317. startPosition: number;
  318. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  319. duration: number;
  320. albumCoverUri: string;
  321. albumTitle: string;
  322. appName: string;
  323. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  324. drmScheme: string;
  325. }
  326. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  327. const ITEM_HEIGHT: number = 65; // 列表项中高度
  328. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  329. /**
  330. * 排序模式枚举
  331. * 定义各种排序方式的升序基准值
  332. */
  333. export enum SortMode {
  334. ByArtist = 0, // 按艺术家升序
  335. ByAlbum = 2, // 按专辑升序
  336. ByName = 4, // 按名称升序
  337. ByTime = 6, // 按时间升序
  338. ByAddTime = 7, // 按添加时间(只有降序)
  339. ByCount = 8, // 按数量升序
  340. ByDiscTrack = 10 // 按碟片编号-音轨号升序
  341. }
  342. //功能强大的音乐播放器
  343. @Preview
  344. @Component
  345. export struct LocalMusic {
  346. @State default_layout:number = 0
  347. @State isGeKongPlayNext: boolean = true//是否开启隔空手势播放下一首
  348. @State bluetoothDisconnectPause: boolean = false // 蓝牙设备断开暂停
  349. @State isBluetoothConnected: boolean = false // 蓝牙连接状态
  350. @State bluetoothLyricEnabled: boolean = false // 蓝牙歌词开关
  351. @State bluetoothLyricMode: number = 0 // 蓝牙歌词显示模式
  352. private lastBluetoothLyricLine: string = '' // 上一次发送的歌词行
  353. @State showFindLocation: boolean = true
  354. @StorageProp("EnablePointLight") enablePointLight: boolean = true
  355. @State showSimple: boolean = true//开启沉浸模式
  356. @State isPaging: boolean = true;//是否分页加载机制
  357. @State isCoverRectangle: boolean = true;
  358. @State showZMIndex: boolean = false //是否右侧显示字母索引
  359. private prevOffsetY: number = 0; // 记录上一次的Y轴偏移量
  360. @State autoHideTitle: boolean = true //滚动自动隐藏标题栏
  361. // 字母表
  362. @State alphaBet: string[] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
  363. 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  364. @State alphaBetStyle: GlobalAlphabetIndexerModifier = new GlobalAlphabetIndexerModifier()
  365. @State selectAlphaBetIndex: number = 0
  366. @State isShowAlphaBet: boolean = false
  367. @State isScrolling: boolean = false
  368. @State isTouchingAlphaBet: boolean = false
  369. @State alphabetHeight: number = 0
  370. public enableShowAlphabet: boolean = true // 是否显示字母表
  371. private alphaBetHideTimer: number = 0
  372. private alphaBetRebuildTimer: number = 0
  373. private alphaBetDirty: boolean = false
  374. private alphaBetCacheKey: string = ''
  375. private alphaBetBuildVersion: number = 0
  376. @State isShowPrecious: boolean = false //播控条显示上一首按钮
  377. //背景两侧流光控制器
  378. @State sceneBgController: HdsSceneController|undefined = deviceInfo.sdkApiVersion>=20
  379. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  380. new HdsSceneController()
  381. .setSceneParams({
  382. backgroundMaskColors: [Color.Green, Color.Red],
  383. firstEdgeFlowLight: {
  384. startPos: 0,
  385. endPos: 0.5,
  386. color: Color.Red
  387. },
  388. secondEdgeFlowLight: {
  389. startPos: 0,
  390. endPos: -0.5,
  391. color: Color.Green
  392. }
  393. }) : undefined;
  394. //背景流光控制器
  395. @State bgController: hdsEffect.ShaderEffectController|undefined = deviceInfo.sdkApiVersion>=20
  396. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  397. new hdsEffect.ShaderEffectController():undefined;
  398. @State showAddSheet:boolean = false
  399. private loadingDialogId: string = ''
  400. private loadingProgressDialogId: string = ''
  401. @State isoAudioEntries: IsoArchiveAudioEntry[] = []
  402. @State selectedIsoAudioPaths: string[] = []
  403. @State isoSourceFileName: string = ''
  404. @State isIsoExtracting: boolean = false
  405. @State isoExtractProgress: number = 0
  406. @State isoExtractProgressText: string = ''
  407. @State isoExtractCurrentEntryName: string = ''
  408. private isoSourceFilePath: string = ''
  409. private isoExtractDestinationDir: string = ''
  410. private isoComponentId: number = 0
  411. private isoExtractProgressTimer: number = 0
  412. private isoExtractExpectedOutputPaths: Array<string> = []
  413. private isoExtractTotalBytes: number = 0
  414. private isoExtractDisplayedProgress: number = 0
  415. private isoExtractReceivedTaskProgress: boolean = false
  416. private isoExtractTask: taskpool.Task | undefined = undefined
  417. private isoExtractLastActivityTime: number = 0
  418. private readonly isoExtractStallTimeoutMs: number = 15000
  419. private isoExtractCanceled: boolean = false
  420. private isoExtractCancelMessage: string = ''
  421. searchController: SearchController = new SearchController()
  422. @State rightTopImage:Resource = $r('sys.symbol.sort')
  423. @State isEditAudio:boolean = false
  424. @State isExtractAcc:boolean = false
  425. @State isConverter:boolean = false
  426. @State isAIVoiceSeparation:boolean = false
  427. @State isExtractAudio:boolean = false
  428. @State isMergeAudio:boolean = false
  429. @State isCopyFileToDownLoad: boolean = false
  430. @State isChangeTone:boolean = false
  431. @State offHeight: number = 75
  432. @State currentSongList: Array<VideoItem> = []//当前歌单
  433. @Consume currentSongListName:string //当前歌单名称
  434. @Consume @Watch('onIDChange') currentSongListID:string //当前歌单ID
  435. @State currentPlaylistSongFilePaths: string[] = [] //当前歌单的歌曲路径列表(用于随机播放)
  436. @State isRefreshing: boolean = false;
  437. @State maxRefreshingHeight: number = 100.0;
  438. @State isPlayerLoading: boolean = false; // 播放器加载状态
  439. private contentNode?: ComponentContent<Object> = undefined;
  440. // WebDAV相关实例变量(现在改为从内存读取,不再需要存储)
  441. @State ratioL: number = 1;
  442. @State mediaKuCount: number = 0;
  443. @State albumCount: number = 0;
  444. @State artistCount: number = 0;
  445. @State fastForwardSeconds: string = '10'
  446. @State isShowBackFast: boolean = true//快进快退按钮
  447. @State isCanAuto:boolean = true
  448. @State opacityValueImage: number = 1;
  449. @State tipPopup:boolean = false
  450. @State preloadNextSong: boolean = PreferencesUtil.getBooleanSync('preload_next_song', true) // 是否提前缓存下一首
  451. @Consume mType: number;
  452. @StorageProp('themeColor') themeColor: string =
  453. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  454. themeMode: number = 0;
  455. @State titleName: string = '首页'
  456. @State textStr: string = ''
  457. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  458. // private download_path: string = '';
  459. @Consume rootPath: string //音频根目录
  460. @Consume currentPath: string
  461. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  462. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  463. @State lockPath: string = ''
  464. @State favPath: string = ''
  465. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  466. @State historyPath: string = ''
  467. @State historyList: Array<VideoItem> = []
  468. @Consume isHistory: boolean
  469. static readonly HISTORY_MUSIC: string = 'music_historyList';
  470. private table: MediaTable = new MediaTable(getContext(this))
  471. private playlistTable: PlaylistTable | null = null
  472. private deletionWatcher: FileDeletionWatcher | null = null
  473. @State allPlaylists: Playlist[] = []
  474. @State isZero: boolean = false
  475. @State fileList: Array<string> = []
  476. @State dirList: Array<VideoItem> = []
  477. @Consume videoLocalList:VideoItem[]
  478. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  479. @State listRefreshKey: number = 0
  480. @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  481. @State artistList: Array<VideoItem> = []; //艺术家文件
  482. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  483. @State artistSongCountMap: Map<string, number> = new Map();
  484. @State albumList: Array<VideoItem> = []; //专辑文件
  485. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  486. @State albumSongCountMap: Map<string, number> = new Map();
  487. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  488. @State imageOpacities: number[] = [];
  489. @Consume isCanBack: boolean
  490. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  491. @State showSingleLyric: boolean = false
  492. @State sortType: number = 4 //默认排序方式
  493. @State isShowSimi: boolean = false //是否显示私密音频
  494. @State isShowFAV: boolean = true //是否显示我的收藏
  495. @State isShowTitleBar: boolean = true //是否显示分类导航条
  496. @State isShowAllBar: boolean = true //是否显示播放全部条
  497. @State isShowSingleLineLyric: boolean = false //是否显示单行歌词
  498. @State isEnableWordByWordLyric: boolean = true //是否开启逐字歌词
  499. @State isShowHistory: boolean = true //是否显示最近播放
  500. @State @Watch('onColorModeChange') isCustomizeBg: boolean = false //自定义背景界面
  501. @State isGridMusic: boolean = false //是否网格布局
  502. @State isCircleBtn: boolean = false //是否圆形播放按钮
  503. @State twoFingerType: number = 3 //双支放大缩小的类型
  504. @State isScrollHide: boolean = false //是否滚动隐藏
  505. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  506. @State isStartAutoPlay: boolean = false //启动后自动播放
  507. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  508. @State isShowHeader: boolean = true
  509. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  510. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  511. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  512. @State rectangleCoverScale: number = 1
  513. @State rectangleCoverPinchValue: number = 1
  514. @State isSwipe: boolean = false //listItem的左滑开关
  515. @State openSkipSongAnimate: boolean = true//切歌动画效果
  516. @State isPlayPageSwipeNext: boolean = true // 播放页上滑切歌
  517. @State isLightText: boolean = true //是否开启歌词发光
  518. @State customizeBgPath: string | undefined = '';
  519. @State isDarkMode: boolean = false
  520. @State lyricTextWeight: number = 400
  521. @State lyricTextWeightPip: number = 400
  522. @State currentSwiperIndex: number = 0
  523. @State blurValue: number = 0 //背景模糊
  524. @State bgBrightness: number = 0 //背景亮度
  525. private listScroller: ListScroller = new ListScroller()
  526. private playListScroller: Scroller = new Scroller()
  527. @State isOneKeyTags:boolean = false
  528. @State isFixMessy:boolean = false
  529. // 分页相关状态
  530. @State private currentPage: number = 0 // 当前页码
  531. @State private pageSize: number = 53 // 每页数量
  532. @State private totalCount: number = 0 // 总记录数
  533. @State private hasMoreData: boolean = true // 是否还有更多数据
  534. @State private isLoadingPage: boolean = false // 是否正在加载分页数据
  535. private pageCache: Map<number, VideoItem[]> = new Map() // 页面缓存(最多保留3页)
  536. private pageHasMoreCache: Map<number, boolean> = new Map()
  537. private pageTotalCountCache: Map<number, number> = new Map()
  538. private prefetchingPages: Set<number> = new Set()
  539. private preloadStartRatio: number = 0.18
  540. private appendStartRatio: number = 0.30
  541. private earlyAppendReserveCount: number = 28
  542. private lastScrollTriggerPage: number = -1
  543. private lastVisibleEndIndex: number = -1
  544. private isPagingTransition: boolean = false
  545. private pagingScheduleTimer: number = 0
  546. private listScrollAlphaCheckAt: number = 0
  547. private listScrollPagingCheckAt: number = 0
  548. private listScrollLastAlphaStart: number = -1
  549. private listScrollLastPagingEnd: number = -1
  550. private gridScrollPagingCheckAt: number = 0
  551. private gridScrollLastPagingEnd: number = -1
  552. private waterScrollPagingCheckAt: number = 0
  553. private waterScrollLastPagingEnd: number = -1
  554. private gridWaterScrollIdleTimer: number = 0
  555. private gridWaterLastActiveTs: number = 0
  556. private listUpdateTimer: number = 0
  557. private listUpdateVersion: number = 0
  558. private detailBackTransitioning: boolean = false
  559. private mediaLibraryEnterTs: number = 0
  560. private mediaLibraryWarmupPrefetchTimer: number = 0
  561. private listVisibleStart: number = -1
  562. private listVisibleEnd: number = -1
  563. private listThumbWarmupCheckAt: number = 0
  564. private listThumbWarmupStart: number = -1
  565. private listThumbWarmupEnd: number = -1
  566. private gridThumbWarmupCheckAt: number = 0
  567. private gridThumbWarmupStart: number = -1
  568. private gridThumbWarmupEnd: number = -1
  569. private waterThumbWarmupCheckAt: number = 0
  570. private waterThumbWarmupStart: number = -1
  571. private waterThumbWarmupEnd: number = -1
  572. private gridVisibleStart: number = -1
  573. private gridVisibleEnd: number = -1
  574. private waterVisibleStart: number = -1
  575. private waterVisibleEnd: number = -1
  576. private titleBarToggleMinDelta: number = 12
  577. private titleBarLastCheckTs: number = 0
  578. @State private coverThumbVersion: number = 0
  579. private coverThumbCache: CoverThumbCache = new CoverThumbCache(1, 960)
  580. private coverThumbCacheReady: boolean = false
  581. private pendingCoverThumbRefresh: boolean = false
  582. private playQueueScope: 'view' | 'history' | 'fav' | 'playlist' | 'single' = 'view'
  583. private isHydratingPlayList: boolean = false
  584. @StorageProp('isLandscape') @Watch('onIsLandscapeChange') isLandscape: boolean = false;
  585. @StorageProp('topSafeHeight') topSafeHeight: number = 0;
  586. @StorageProp('bottomSafeHeight') bottomSafeHeight: number = 0;
  587. @StorageProp('windowWidth') windowWidth: number = 0;
  588. @StorageProp('windowHeight') windowHeight: number = 0;
  589. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  590. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  591. private UNKONWN:string = '';
  592. private listArea: Area = {
  593. width: 0,
  594. height: 0,
  595. position: {},
  596. globalPosition: {}
  597. }
  598. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  599. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  600. // WebDAV认证信息缓存(作为实例变量,比全局上下文更可靠)
  601. private currentWebDavAuthInfo: WebDavAuthItem | null = null;
  602. // 当前实际播放中的记忆key,避免切歌时 currentSong 已切换导致串写
  603. private activePlaybackMemoryKey: string = '';
  604. // 网盘流地址记忆恢复token,切歌后用于取消旧的延迟seek任务
  605. private remoteRestoreSeekToken: number = 0;
  606. // 本次是否需要先seek到记忆点再开始播放
  607. private waitInitialSeekBeforeStart: boolean = false;
  608. // 本次播放记忆点(毫秒)
  609. private pendingMemorySeekPosition: number = 0;
  610. // 记忆播放seek兜底,避免一直转圈
  611. private initialSeekGuardTimer: number = 0;
  612. private readonly initialSeekGuardTimeoutMs: number = 2000;
  613. private readonly remoteMemorySeekInitialDelayMs: number = 120;
  614. private readonly remoteMemorySeekRetryIntervalMs: number = 80;
  615. private readonly remoteMemorySeekMaxRetryCount: number = 6;
  616. private lastSeekRequestMs: number = -1;
  617. private lastSeekSource: string = '';
  618. private seekTraceUntilTs: number = 0;
  619. private lastSeekTraceLogTs: number = 0;
  620. private readonly seekTraceLogWindowMs: number = 4000;
  621. private readonly seekTraceLogIntervalMs: number = 400;
  622. //瀑布流的列数横竖屏动态切换
  623. onIsLandscapeChange() {
  624. if(this.isLandscape){
  625. this.columns = 4
  626. }else{
  627. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  628. }
  629. }
  630. onColorModeChange() {
  631. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  632. }
  633. //点击某个歌单id发生变化的时候回调
  634. onIDChange(){
  635. console.log('onecold 歌单id发生变化this.currentSongListID='+this.currentSongListID)
  636. console.log('onecold 歌单id发生变化this.currentSongListName='+this.currentSongListName)
  637. if(this.modeType==4){
  638. this.titleName = this.currentSongListName
  639. this.rightTopImage = $r('sys.symbol.sort')
  640. //获取缓存
  641. const cacheSongs:string =PreferencesUtil.getStringSync(this.currentSongListID+'currentSongList', '')
  642. console.log('onecold 歌单id发生变化获取缓存2 cacheSongs = '+cacheSongs)
  643. if(StrUtil.isNotEmpty(cacheSongs)){
  644. this.currentSongList = JSON.parse(cacheSongs) as VideoItem[]
  645. this.updateListData(this.currentSongList, true)
  646. }
  647. this.doSongListTask()//获取歌单信息
  648. }
  649. }
  650. async doSongListTask() {
  651. // 初始化歌单数据库
  652. const playlistTable = new PlaylistTable(this.context);
  653. // 查询歌单中的所有歌曲
  654. const playlistSongs: PlaylistSong[] = await playlistTable.queryPlaylistSongs(this.currentSongListID);
  655. console.log('onecold 歌单id发生变化获取缓存7 playlistSongs='+playlistSongs.length)
  656. if (ArrayUtil.isEmpty(playlistSongs)) {
  657. this.updateListData([], true)
  658. // 清空歌单路径列表
  659. this.currentPlaylistSongFilePaths = [];
  660. } else {
  661. this.currentSongList = await convertPlaylistSongsToVideoItems(this.context, playlistSongs);
  662. console.log('onecold 从数据库读取的歌曲为 playlistSongs='+this.currentSongList.length)
  663. this.updateListData(this.currentSongList, true)
  664. // 保存歌单的歌曲路径列表,用于随机播放
  665. this.currentPlaylistSongFilePaths = playlistSongs.map(song => song.songFilePath);
  666. Logger.info('heanup doSongListTask', `保存歌单歌曲路径列表,歌单ID=${this.currentSongListID}, 数量=${this.currentPlaylistSongFilePaths.length}`);
  667. if (ArrayUtil.isNotEmpty(this.currentSongList)&&this.currentSongList.length > 100) {
  668. // 只保存前100条记录到缓存中
  669. let canceList = this.currentSongList.slice(0, 100);
  670. PreferencesUtil.putSync(this.currentSongListID+'currentSongList',
  671. JSON.stringify(canceList))
  672. } else {
  673. PreferencesUtil.putSync(this.currentSongListID+'currentSongList', JSON.stringify(this.currentSongList));
  674. }
  675. }
  676. this.isRefreshing = false
  677. }
  678. async onModeChange(preserveList: boolean = false): Promise<void> {
  679. this.isFavMusic = false
  680. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  681. this.refreshDirVisibilitySettings()
  682. if (this.mediaLibraryWarmupPrefetchTimer) {
  683. clearTimeout(this.mediaLibraryWarmupPrefetchTimer)
  684. this.mediaLibraryWarmupPrefetchTimer = 0
  685. }
  686. Logger.info('heanup LocalMusic', `onModeChange: 切换模式 modeType=${this.modeType}`);
  687. switch (this.modeType) {
  688. case 0:
  689. // 首页模式已在 resetAndLoadFirstPage 中处理
  690. // 切换模式时加载对应的排序类型
  691. this.titleName = Utility.resourceToString(this.context,$r('app.string.home'))
  692. this.sortType = this.loadSortTypeForCurrentMode()
  693. this.mediaLibraryEnterTs = 0
  694. break
  695. case 1:
  696. this.rightTopImage = $r('sys.symbol.sort')
  697. this.titleName = Utility.resourceToString(this.context,$r('app.string.media_ku'))
  698. // 切换模式时加载对应的排序类型
  699. this.sortType = this.loadSortTypeForCurrentMode()
  700. this.mediaLibraryEnterTs = Date.now()
  701. break
  702. case 2:
  703. this.rightTopImage = $r('sys.symbol.sort')
  704. this.titleName = Utility.resourceToString(this.context,$r('app.string.artist'))
  705. // 切换到艺术家模式时,加载艺术家模式的排序类型(默认按数量降序)
  706. this.sortType = this.loadSortTypeForCurrentMode()
  707. this.mediaLibraryEnterTs = 0
  708. break
  709. case 3:
  710. this.rightTopImage = $r('sys.symbol.sort')
  711. this.titleName = Utility.resourceToString(this.context,$r('app.string.album'))
  712. // 切换到专辑模式时,加载专辑模式的排序类型(默认按数量降序)
  713. this.sortType = this.loadSortTypeForCurrentMode()
  714. this.mediaLibraryEnterTs = 0
  715. break
  716. }
  717. // 模式切换时重置分页状态并加载第一页
  718. await this.resetAndLoadFirstPage(!preserveList);
  719. Logger.info('heanup onModeChange', `doSortType: 切换排序方式 sortType=${this.sortType}, mode=${this.modeType}`);
  720. }
  721. // @Consume currentSong: VideoItem | undefined;
  722. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  723. // @StorageLink('isPlay') isPlay: boolean = false;
  724. @Consume isShowPlay: boolean ;
  725. @State isShowCoverScaleGuide: boolean = false
  726. @StorageLink('songList') songList: Array<VideoItem> = [];
  727. @State translateY: number = 0;
  728. @State isShowSheet: boolean = false;
  729. @State isShowSheetView: boolean = false;
  730. @State isShowLyricCopySheet: boolean = false;
  731. @State lyricCopyLines: string[] = [];
  732. @State lyricSelectedIndexes: number[] = [];
  733. @State isShowTimeCloseView: boolean = false;
  734. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  735. @StorageLink('currIndex') curIndex: number = 0;
  736. @Consume isShowDrawer: boolean;
  737. @Consume offsetX: number;
  738. @State isFac: boolean = false;
  739. @State favList: Array<VideoItem> = []
  740. @Consume isFavMusic: boolean
  741. @State isClickedPLayAll: boolean = false;
  742. private scrollerForlist: ListScroller = new ListScroller();
  743. private knockController: KnockController | undefined = undefined;
  744. @StorageProp('animationState') animationState: AnimationStatus = AnimationStatus.Initial
  745. // 缓存机制
  746. private cache: Map<string, Array<VideoItem>> = new Map();
  747. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  748. // 持久化缓存
  749. private async saveCacheToStorage() {
  750. const cacheArray = Array.from(this.cache.entries());
  751. const stringCacheArray = Array.from(this.stringCache.entries());
  752. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  753. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  754. }
  755. // 载入缓存
  756. private async loadCacheFromStorage() {
  757. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  758. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  759. if (cacheString) {
  760. const parsedCache: Object | null = JSON.parse(cacheString);
  761. if (parsedCache && Array.isArray(parsedCache)) {
  762. const cacheArray: [string, Array<VideoItem>][] = parsedCache;
  763. this.cache = new Map(cacheArray);
  764. }
  765. }
  766. if (stringCacheString) {
  767. const parsedStringCache: Object | null = JSON.parse(stringCacheString);
  768. if (parsedStringCache && Array.isArray(parsedStringCache)) {
  769. const stringCacheArray: [string, string][] = parsedStringCache;
  770. this.stringCache = new Map(stringCacheArray);
  771. }
  772. }
  773. }
  774. // 查找缓存
  775. private findCache(key: string): Array<VideoItem> | undefined {
  776. return this.cache.get(key);
  777. }
  778. // 查找字符串缓存
  779. private findStringCache(key: string): string | undefined {
  780. return this.stringCache.get(key);
  781. }
  782. // 添加缓存
  783. private addCache(key: string, value: Array<VideoItem>) {
  784. this.cache.set(key, value);
  785. }
  786. // 添加字符串缓存
  787. private addStringCache(key: string, value: string) {
  788. this.stringCache.set(key, value);
  789. }
  790. // 删除缓存
  791. private deleteCache(key: string) {
  792. this.cache.delete(key);
  793. this.saveCacheToStorage()
  794. }
  795. // 删除字符串缓存
  796. private deleteStringCache(key: string) {
  797. this.stringCache.delete(key);
  798. }
  799. // 多选机制
  800. @State selectedFiles: Array<VideoItem> = [];
  801. @Consume isMultiSelect: boolean;
  802. @State isAllSelected: boolean = false;
  803. @State appName: string = ''
  804. @State isHasDir: boolean = false
  805. @State packName: string = ''
  806. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  807. doSwipBack() {
  808. if(this.isSearchMode){
  809. console.info('onecold doSwipBack = ' +this.isSearchMode)
  810. this.isSearchMode = false
  811. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  812. this.searchText = ''
  813. this.getSortedFiles(this.currentPath)
  814. return
  815. }
  816. this.onSearchInput('')
  817. return
  818. }
  819. this.isZero = false
  820. if (this.modeType !== 0 && this.isCanBack) {
  821. if (this.detailBackTransitioning) {
  822. return
  823. }
  824. this.detailBackTransitioning = true
  825. // 先设置 isCanBack=false,确保 onModeChange 读取的是列表页的排序设置
  826. this.isCanBack = false
  827. this.rightTopImage = $r('sys.symbol.sort')
  828. if (this.modeType == 2) {
  829. this.titleName = Utility.resourceToString(this.context,$r('app.string.artist'))
  830. if (ArrayUtil.isNotEmpty(this.artistList)) {
  831. this.updateListData(this.artistList, true, true)
  832. }
  833. } else if (this.modeType == 3) {
  834. this.titleName = Utility.resourceToString(this.context,$r('app.string.album'))
  835. if (ArrayUtil.isNotEmpty(this.albumList)) {
  836. this.updateListData(this.albumList, true, true)
  837. }
  838. }
  839. // 返回列表页时保留当前列表,避免先清空导致闪现
  840. void this.onModeChange(true).then(() => {
  841. if (this.modeType == 2) {
  842. if (this.isGridMusic||this.twoFingerType==4) {
  843. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  844. let lastWaterOffset = this.mScrollMap.get('lastWaterArtistScrollOffset') ?? 0
  845. if(this.twoFingerType==4){
  846. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  847. }else{
  848. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  849. }
  850. } else {
  851. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  852. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  853. }
  854. } else if (this.modeType == 3) {
  855. if (this.isGridMusic||this.twoFingerType==4) {
  856. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  857. let lastWaterOffset = this.mScrollMap.get('lastWaterAlBumScrollOffset') ?? 0
  858. if(this.twoFingerType==4){
  859. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  860. }else{
  861. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  862. }
  863. } else {
  864. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  865. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  866. }
  867. }
  868. this.detailBackTransitioning = false
  869. }).catch((error: Error) => {
  870. Logger.error('heanup LocalMusic', `doSwipBack onModeChange error: ${error.message}`)
  871. this.detailBackTransitioning = false
  872. })
  873. return
  874. }
  875. this.mediaLibraryEnterTs = 0
  876. if (this.isHistory || this.isFavMusic) {
  877. this.isHistory = false
  878. this.getSortedFiles(this.currentPath)
  879. return
  880. }
  881. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  882. animateTo({ duration: 555 }, () => {
  883. // 动画闭包内控制Image组件的出现和消失
  884. this.isShowDrawer = !this.isShowDrawer
  885. this.offsetX = 0
  886. })
  887. return
  888. }
  889. //返回上一级歌单的滚动位置
  890. setTimeout(() => {
  891. if (this.modeType == 0) {
  892. if (this.isGridMusic||this.twoFingerType==4) {
  893. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  894. let lastWaterOffset = this.mScrollMap.get('lastWaterDirScrollOffset') ?? 0
  895. if(this.twoFingerType==4){
  896. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  897. }else{
  898. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  899. }
  900. } else {
  901. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  902. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  903. }
  904. }
  905. }, 100)
  906. this.currentPath = Utility.getParentDirectory(this.currentPath)
  907. Logger.info('this.currentPath2 = ' + this.currentPath)
  908. this.getSortedFiles(this.currentPath, false, undefined, undefined, undefined, true)
  909. }
  910. private triggerSwipeBackWithAnimation(): void {
  911. animateTo({ duration: 555 }, () => {
  912. this.doSwipBack()
  913. })
  914. }
  915. // 组件生命周期
  916. aboutToAppear() {
  917. console.info('onecold aboutToAppear sdkApiVersion = '+deviceInfo.sdkApiVersion)
  918. if(ArrayUtil.isNotEmpty(this.videoLocalList)&&this.modeType==0){
  919. this.updateListData(this.videoLocalList)
  920. }
  921. // 初始化 PlaylistTable
  922. this.playlistTable = new PlaylistTable(getContext(this))
  923. this.sonTwoFingerType = PreferencesUtil.getNumberSync('sonTwoFingerType', 3);
  924. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  925. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  926. this.tipPopup = !this.tipPopup
  927. PreferencesUtil.putSync('isFirstTiped',false)
  928. }
  929. this.loadSearchHistory()
  930. this.initSetting()
  931. this.syncEqualizerUi();
  932. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  933. Utility.getAppName(getContext(this)).then((appName: string) => {
  934. this.appName = appName
  935. })
  936. this.packName = AppUtil.getBundleName()
  937. this.tabSelectedIndexes[0] = this.modeType//SegmentButton的索引
  938. this.loadCacheFromStorage(); // 加载文件夹缓存
  939. // 在首页初始化时读取媒体库,艺术家,专辑等缓存数据
  940. this.initLoadCache()
  941. this.mkDownLoadDir()
  942. let eventMusic: emitter.InnerEvent = { eventId: EventConstants.EVENT_AUDIO_OPEN }
  943. // 监听广播事件(打开其他应用处理)
  944. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  945. this.saveVideoDatas([eventData.data?.message], true)
  946. });
  947. //侧滑广播接收时间
  948. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_UPDATE }
  949. // 监听广播事件(手势返回处理)
  950. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  951. this.triggerSwipeBackWithAnimation()
  952. });
  953. //ScanFilePage广播接收时间
  954. let eventScanUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_SCAN_UPDATE }
  955. // 监听ScanFilePage广播事件(更新数据库)
  956. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  957. this.doUpdateData()
  958. });
  959. let eventEqualizerChanged: emitter.InnerEvent = { eventId: EventConstants.EVENT_EQUALIZER_CHANGED }
  960. emitter.on(eventEqualizerChanged, () => {
  961. this.syncEqualizerUi();
  962. if (this.mIjkMediaPlayer) {
  963. const equalizerManager = EqualizerManager.getInstance();
  964. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  965. this.markEqualizerApplied();
  966. }
  967. });
  968. // 监听歌单播放请求事件
  969. let eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY }
  970. emitter.on(eventPlaylistPlay, async (eventData: emitter.EventData) => {
  971. const data = eventData.data as Record<string, Object>
  972. if (!data) {
  973. Logger.error('heanup eventPlaylistPlay: eventData.data is undefined or null')
  974. return
  975. }
  976. // 检查歌单播放数据结构
  977. if (data.playlistId && data.songFilePaths && data.startIndex !== undefined) {
  978. const playlistData: PlaylistEventData = {
  979. playlistId: data.playlistId as string,
  980. playlistName: data.playlistName as string,
  981. songCount: data.songCount as number,
  982. startIndex: data.startIndex as number,
  983. isJump: data.isJump as boolean,
  984. songFilePaths: data.songFilePaths as string[]
  985. }
  986. await this.handlePlaylistPlayRequest(
  987. playlistData.playlistId,
  988. playlistData.playlistName,
  989. playlistData.songFilePaths,
  990. playlistData.startIndex,
  991. playlistData.isJump,
  992. playlistData.songCount
  993. )
  994. return
  995. }
  996. Logger.error('heanup eventPlaylistPlay: 接收到无效的数据结构')
  997. });
  998. let eventRefreshSort: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_REFRESH_SORT }
  999. // 监听广播事件(通用设置配置更新)
  1000. emitter.on(eventRefreshSort, (eventData: emitter.EventData) => {
  1001. if(this.modeType ==4){
  1002. this.doSongListTask()//获取歌单信息
  1003. }
  1004. });
  1005. let eventQueueRefresh: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAY_QUEUE_REFRESH }
  1006. emitter.on(eventQueueRefresh, () => {
  1007. this.syncWebdavQueueWithoutRestart();
  1008. });
  1009. let eventSetting: emitter.InnerEvent = { eventId: EventConstants.EVENT_SETTING_UPDATE }
  1010. // 监听广播事件(通用设置配置更新)
  1011. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  1012. this.initSetting()
  1013. });
  1014. // 监听 WebDAV 元数据更新事件
  1015. let eventWebDavMetadata: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED }
  1016. emitter.on(eventWebDavMetadata, (eventData: emitter.EventData) => {
  1017. const payloads = eventData?.data as WebDavMetadataUpdatePayload[] | undefined;
  1018. if (!payloads || payloads.length === 0) {
  1019. Logger.info(TAG, 'LocalMusic: WebDav metadata event received but payload empty');
  1020. return;
  1021. }
  1022. Logger.info(TAG, `LocalMusic: WebDav metadata event payload count: ${payloads.length}`);
  1023. // 处理每个元数据更新
  1024. for (let i = 0; i < payloads.length; i++) {
  1025. const payload = payloads[i];
  1026. if (!payload || !payload.filePath) {
  1027. continue;
  1028. }
  1029. // 重要:只更新当前正在播放的歌曲
  1030. // 如果 filePath 不匹配,说明是其他歌曲的元数据更新,忽略不做处理
  1031. if (this.currentSong && this.currentSong.filePath === payload.filePath) {
  1032. Logger.info(TAG, `LocalMusic: 更新当前播放歌曲的元数据: ${payload.filePath}`);
  1033. if (payload.name && payload.name.length > 0) {
  1034. this.name = payload.name;
  1035. if (this.currentSong) {
  1036. this.currentSong.name = payload.name;
  1037. }
  1038. }
  1039. if (payload.artist && payload.artist.length > 0) {
  1040. this.artist = payload.artist;
  1041. if (this.currentSong) {
  1042. this.currentSong.artist = payload.artist;
  1043. }
  1044. }
  1045. if (this.currentSong) {
  1046. const coverMutated = mergeCoverWithPriority(this.currentSong, payload.pixelMapPath,
  1047. payload.isCustomCover ?? 0);
  1048. if (coverMutated && this.currentSong.pixelMapPath) {
  1049. this.cover = this.currentSong.pixelMapPath;
  1050. Logger.info(TAG, `LocalMusic: 封面已更新: ${this.currentSong.pixelMapPath}`);
  1051. }
  1052. if (payload.md5Str && payload.md5Str.length > 0) {
  1053. this.currentSong.md5Str = payload.md5Str;
  1054. }
  1055. }
  1056. // 同步更新 AppStorage
  1057. AppStorage.setOrCreate('currentSong', this.currentSong);
  1058. } else {
  1059. Logger.info(TAG, `LocalMusic: 跳过非当前播放歌曲的元数据更新: ${payload.filePath}, 当前: ${this.currentSong?.filePath}`);
  1060. }
  1061. }
  1062. });
  1063. // 监听广播事件(通用设置配置更新)
  1064. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  1065. this.doChangeSetting()
  1066. });
  1067. let event: Callback<InterruptEvent> = (event) => {
  1068. // LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  1069. console.info(`heanup onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`)
  1070. this.savePlaybackPosition()
  1071. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  1072. this.pause();
  1073. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  1074. console.info(`heanup onecold audioInterrupt startPlayOrResumePlay: ${JSON.stringify(event)}`)
  1075. this.startPlayOrResumePlay();
  1076. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  1077. console.info(`heanup onecold 与其他应用音频冲突 被截断点 INTERRUPT_HINT_STOP`)
  1078. if(!this.isSameTimePlay){
  1079. this.stop();
  1080. }
  1081. }
  1082. }
  1083. this.mIjkMediaPlayer.on('audioInterrupt', event);
  1084. // 音频设备断连回调处理比如蓝牙耳机断开
  1085. let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  1086. console.info(`onecold Heanup deviceChange event: ${JSON.stringify(event)}`);
  1087. if (event.reason === DeviceChangeReason.REASON_NEW_DEVICE_AVAILABLE) { // 音频设备连接
  1088. } else if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  1089. console.info('heanup onecold 音频设备断开连接, 暂停播放')
  1090. this.pause();
  1091. }
  1092. }
  1093. // 订阅音频设备断开和连接事件
  1094. this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  1095. const eventPause: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAY_PAUSE }
  1096. // 监听广播事件(hicar断开暂停播放)
  1097. emitter.on(eventPause, (eventData: emitter.EventData) => {
  1098. console.info('heanup onecold hicar断开暂停播放, 暂停播放')
  1099. this.pause();
  1100. });
  1101. let audioManager = audio.getAudioManager(); // 需要先创建AudioManager实例。
  1102. let audioRoutingManager = audioManager.getRoutingManager(); // 再调用AudioManager的方法创建AudioRoutingManager实例。
  1103. // 监听蓝牙音响断开音频设备状态变化。
  1104. audioRoutingManager.on('deviceChange', audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (deviceChanged: audio.DeviceChangeAction) => {
  1105. console.info(`onecold device change type : ${deviceChanged.type}`); // 设备连接状态变化,0为连接,1为断开连接。
  1106. console.info(`onecold device descriptor size : ${deviceChanged.deviceDescriptors.length}`);
  1107. console.info(`onecold device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceRole}`); // 设备角色。
  1108. console.info(`onecold device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceType}`);
  1109. // 蓝牙设备类型为8
  1110. const isBluetooth = deviceChanged.deviceDescriptors[0].deviceType === 8;
  1111. if (isBluetooth) {
  1112. if (deviceChanged.type === 0) {
  1113. // 蓝牙连接
  1114. this.isBluetoothConnected = true;
  1115. console.info('onecold 蓝牙设备已连接');
  1116. } else if (deviceChanged.type === 1) {
  1117. // 蓝牙断开
  1118. this.isBluetoothConnected = false;
  1119. this.lastBluetoothLyricLine = '';
  1120. console.info('onecold 蓝牙设备已断开');
  1121. // 恢复原始元数据
  1122. if (this.currentSong) {
  1123. this.avSessionController.restoreOriginalMetadata(
  1124. this.currentSong.name || '',
  1125. this.currentSong.artist || ''
  1126. );
  1127. }
  1128. // 蓝牙断开暂停
  1129. if (this.bluetoothDisconnectPause && deviceChanged.deviceDescriptors[0].deviceRole === 2) {
  1130. console.info('heanup onecold 蓝牙音响断开, 暂停播放');
  1131. this.pause();
  1132. }
  1133. }
  1134. }
  1135. });
  1136. // 有线耳机断开和连接的监听。监听音频设备状态变化。
  1137. audioRoutingManager.on('deviceChange', audio.DeviceFlag.INPUT_DEVICES_FLAG, (deviceChanged: audio.DeviceChangeAction) => {
  1138. console.info('onecold device change type : ' + deviceChanged.type); // 设备连接状态变化,0为连接,1为断开连接。
  1139. // 设备类型 22是USB耳机,带麦克风,3是有线耳机。
  1140. if(deviceChanged.type==1&&
  1141. (deviceChanged.deviceDescriptors[0].deviceType== 22||
  1142. deviceChanged.deviceDescriptors[0].deviceType==3)){
  1143. console.info('heanup onecold 有线耳机断开, 暂停播放')
  1144. this.pause();
  1145. }
  1146. });
  1147. this.makeWorker()
  1148. //折叠屏的屏幕显示模式变化
  1149. display.on('foldDisplayModeChange', (data) => {
  1150. this.doChangeBarHeight()
  1151. });
  1152. display.on('foldStatusChange', (data) => {
  1153. Logger.info('onecold foldStatusChange ')
  1154. });
  1155. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  1156. this.rectangleCoverScale = PreferencesUtil.getNumberSync(SettingPage.RECTANGLE_COVER_SCALE, 1)
  1157. if (this.rectangleCoverScale < 0.7 || this.rectangleCoverScale > 1.4) {
  1158. this.rectangleCoverScale = 1
  1159. }
  1160. // 读取 themeMode 并同步 currentColorMode
  1161. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  1162. this.applyThemeMode(this.themeMode)
  1163. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  1164. AppStorage.setOrCreate('themeColor', themeColor);
  1165. this.themeColor = themeColor;
  1166. this.doChangeSetting()
  1167. this.windowClass.on('windowSizeChange', (size: window.Size) => {
  1168. LogUtil.info('onecold windowSizeChange')
  1169. this.doChangeBarHeight()
  1170. let viewWidth = px2vp(size.width);
  1171. let viewHeight = px2vp(size.height);
  1172. if(this.isPhoneLan()){
  1173. this.is_auto_hide_progress = false
  1174. if(this.isHiCar()){
  1175. return
  1176. }
  1177. setTimeout(() => {
  1178. this.is_auto_hide_progress = true
  1179. }, 6000)
  1180. }else{
  1181. this.startAutoHide()
  1182. }
  1183. });
  1184. this.eventHub.on('onStateChange', (fg: boolean) => {
  1185. this.isAppForeground = fg;
  1186. if (fg && this.curState === 'STARTED') {
  1187. this.stopPip();
  1188. this.syncLyricPositionNow();
  1189. }
  1190. });
  1191. //NewIndex的博空调收到eventHub消息控制播放
  1192. this.getUIContext().getHostContext()!.eventHub.on('playOrPause', () => {
  1193. if (ArrayUtil.isNotEmpty(this.songList)) {
  1194. this.playOrPause();
  1195. } else {
  1196. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1197. }
  1198. });
  1199. this.getUIContext().getHostContext()!.eventHub.on('playPrevious', () => {
  1200. if (ArrayUtil.isNotEmpty(this.songList)) {
  1201. this.playPrevious();
  1202. } else {
  1203. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1204. }
  1205. });
  1206. this.getUIContext().getHostContext()!.eventHub.on('playNext', () => {
  1207. if (ArrayUtil.isNotEmpty(this.songList)) {
  1208. this.playNext();
  1209. } else {
  1210. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1211. }
  1212. });
  1213. this.getUIContext().getHostContext()!.eventHub.on('showPlayerView', () => {
  1214. this.showPlayerView();
  1215. });
  1216. this.getUIContext().getHostContext()!.eventHub.on('openPlayList', () => {
  1217. this.openPlayList();
  1218. });
  1219. }
  1220. //载入媒体库,艺术家,专辑等缓存
  1221. initLoadCache(){
  1222. this.mediaKuCount = PreferencesUtil.getNumberSync('mediaKuCount', 0)
  1223. this.artistCount = PreferencesUtil.getNumberSync('artistCount', 0)
  1224. this.albumCount = PreferencesUtil.getNumberSync('albumCount', 0)
  1225. let cachedListStr:string = PreferencesUtil.getStringSync('mediaKuList', '[]');
  1226. let cachedList = JSON.parse(cachedListStr) as Array<VideoItem>;
  1227. if(ArrayUtil.isNotEmpty(cachedList)){
  1228. this.mediaKuList = cachedList
  1229. if(this.modeType==1){
  1230. this.updateListData(this.mediaKuList)
  1231. }
  1232. }
  1233. let artistListStr:string = PreferencesUtil.getStringSync('artistList', '[]');
  1234. let artistCachedList = JSON.parse(artistListStr) as Array<VideoItem>;
  1235. if(ArrayUtil.isNotEmpty(artistCachedList)){
  1236. this.artistList = artistCachedList
  1237. let artistMapStr:string = PreferencesUtil.getStringSync('artistMap', '[]');
  1238. const parsedArray = JSON.parse(artistMapStr) as [string, VideoItem[]][];
  1239. this.artistMap = new Map(parsedArray);
  1240. // this.artistMap = JSON.parse(artistMapStr) as Map<string, VideoItem[]>;
  1241. if(this.modeType==2){
  1242. this.updateListData(this.artistList)
  1243. }
  1244. }
  1245. let albumListStr:string = PreferencesUtil.getStringSync('albumList', '[]');
  1246. let albumCachedList = JSON.parse(albumListStr) as Array<VideoItem>;
  1247. if(ArrayUtil.isNotEmpty(albumCachedList)){
  1248. this.albumList = albumCachedList
  1249. let albumMapStr:string = PreferencesUtil.getStringSync('albumMap', '[]');
  1250. const parsedArray = JSON.parse(albumMapStr) as [string, VideoItem[]][];
  1251. this.albumMap = new Map(parsedArray);
  1252. if(this.modeType==3){
  1253. this.updateListData(this.albumList)
  1254. }
  1255. }
  1256. }
  1257. startAutoHide() {
  1258. if(this.isHiCar()){
  1259. return
  1260. }
  1261. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  1262. console.info('onecold startAutoHide')
  1263. this.is_auto_hide_progress = false
  1264. setTimeout(() => {
  1265. this.is_auto_hide_progress = true
  1266. }, 6000)
  1267. }
  1268. }
  1269. applyThemeMode(mode: number) {
  1270. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  1271. if (mode === 1) {
  1272. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  1273. } else if (mode === 2) {
  1274. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1275. }
  1276. AppStorage.setOrCreate('currentColorMode', colorMode)
  1277. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  1278. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  1279. AppStorage.setOrCreate('themeMode', mode)
  1280. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1281. // 只有强制浅色/深色时才主动设置
  1282. const context = getContext(this) as common.UIAbilityContext
  1283. context.getApplicationContext().setColorMode(colorMode)
  1284. }
  1285. initSetting() {
  1286. this.default_layout = PreferencesUtil.getNumberSync('default_layout', 0)
  1287. this.isGeKongPlayNext = PreferencesUtil.getBooleanSync('isGeKongPlayNext', false)
  1288. this.bluetoothDisconnectPause = PreferencesUtil.getBooleanSync(SettingPage.BLUETOOTH_DISCONNECT_PAUSE, false)
  1289. this.bluetoothLyricEnabled = PreferencesUtil.getBooleanSync(SettingPage.BLUETOOTH_LYRIC_ENABLED, false)
  1290. this.bluetoothLyricMode = PreferencesUtil.getNumberSync(SettingPage.BLUETOOTH_LYRIC_MODE, 0)
  1291. this.isShowSpectrum = PreferencesUtil.getBooleanSync('isShowSpectrum', true)
  1292. this.spectrumModeIndex = PreferencesUtil.getNumberSync('spectrumModeIndex', 0)
  1293. this.enablePointLight = PreferencesUtil.getBooleanSync('enablePointLight', true)
  1294. AppStorage.setOrCreate('EnablePointLight', this.enablePointLight);
  1295. this.showSimple = PreferencesUtil.getBooleanSync('showSimple', true)
  1296. this.showFindLocation = PreferencesUtil.getBooleanSync('showFindLocation', true)
  1297. this.showZMIndex = PreferencesUtil.getBooleanSync('showZMIndex', false)
  1298. this.autoHideTitle = PreferencesUtil.getBooleanSync('autoHideTitle', true)
  1299. this.isShowPrecious = PreferencesUtil.getBooleanSync('isShowPrecious', false)
  1300. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1301. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  1302. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  1303. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, false)
  1304. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  1305. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  1306. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  1307. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  1308. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  1309. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  1310. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  1311. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  1312. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  1313. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 3)
  1314. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  1315. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  1316. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  1317. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  1318. this.isEnableWordByWordLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_ENABLE_WORD_BY_WORD_LYRIC, true)
  1319. this.isLightText = PreferencesUtil.getBooleanSync(SettingPage.IS_LIGHT_TEXT, true)
  1320. this.syncWordByWordLyricMode()
  1321. this.syncLyricLightTextMode()
  1322. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  1323. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  1324. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  1325. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  1326. const volumeBoostPercent = PreferencesUtil.getNumberSync(this.volumeBoostPreferenceKey, 0)
  1327. this.volumeBoostPercent = Math.max(0, Math.min(volumeBoostPercent, this.volumeBoostMaxPercent))
  1328. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  1329. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  1330. this.isPlayPageSwipeNext = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYPAGE_SWIPE_NEXT, true)
  1331. this.volumeSmall = PreferencesUtil.getBooleanSync('volumeSmall', false)
  1332. this.autoParseMusicName = PreferencesUtil.getBooleanSync('autoParseMusicName', true)
  1333. this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
  1334. this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
  1335. this.refreshDirVisibilitySettings()
  1336. this.fastForwardSeconds = PreferencesUtil.getStringSync('fastForwardSeconds', '10')
  1337. this.isShowBackFast = PreferencesUtil.getBooleanSync('isShowBackFast', false)
  1338. this.isCopyFileToDownLoad = PreferencesUtil.getBooleanSync(SettingPage.IS_COPYFILE_TO_DOWNLOAD, false)
  1339. let audioManager = audio.getAudioManager();
  1340. let audioSessionManager: audio.AudioSessionManager = audioManager.getSessionManager();
  1341. if(this.isSameTimePlay){
  1342. //与其他应用同时播放,关键代码
  1343. let strategy: audio.AudioSessionStrategy = {
  1344. concurrencyMode: audio.AudioConcurrencyMode.CONCURRENCY_MIX_WITH_OTHERS
  1345. };
  1346. audioSessionManager.activateAudioSession(strategy).then(() => {
  1347. console.info('onecold Succeeded in doing activateAudioSession.');
  1348. }).catch((err: BusinessError) => {
  1349. console.error(`Failed to activateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1350. });
  1351. }else{
  1352. let isActivated = audioSessionManager.isAudioSessionActivated();
  1353. if(isActivated){
  1354. audioSessionManager.deactivateAudioSession().then(() => {
  1355. console.info('Succeeded in doing deactivateAudioSession.');
  1356. }).catch((err: BusinessError) => {
  1357. console.error(`Failed to deactivateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1358. });
  1359. }
  1360. }
  1361. //如果是hicar连接状态,这些都是false
  1362. if(this.isHiCar()){
  1363. this.autoHideTitle = false
  1364. this.isCoverRectangle= true
  1365. this.columns=4
  1366. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  1367. {
  1368. this.isGridMusic= false//用list不用网格
  1369. this.isCoverTopBig = false
  1370. }
  1371. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  1372. }
  1373. if (this.isSavePlayMode) {
  1374. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  1375. }
  1376. }
  1377. doChangeSetting() {
  1378. this.initSetting()
  1379. this.deleteCache(this.currentPath)
  1380. if (this.modeType === 0) {
  1381. this.getSortedFiles(this.currentPath)
  1382. }
  1383. }
  1384. doChangeBarHeight() {
  1385. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  1386. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  1387. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  1388. this.setBarHeightNormal()
  1389. }
  1390. }
  1391. onPageShow() {
  1392. this.knockController?.immersiveListening();
  1393. app.setImageCacheCount(100);
  1394. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  1395. app.setImageRawDataCacheSize(104857600);
  1396. this.refreshDirVisibilitySettings();
  1397. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  1398. }
  1399. //开启线程查看各个数据库
  1400. makeWorker() {
  1401. setTimeout(() => {
  1402. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  1403. // ToastUtil.showToast('请到文件扫描页面导入音乐!')
  1404. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  1405. workerInstance.postMessage({
  1406. code: 1,
  1407. data1: this.context,
  1408. data2: this.rootPath,
  1409. data3: this.lockPath,
  1410. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  1411. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  1412. });
  1413. PreferencesUtil.putSync('isFirstApp', false)
  1414. } else {
  1415. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1416. workerInstance.postMessage({ code: 3, data: this.context });
  1417. workerInstance.postMessage({ code: 4, data: this.context });
  1418. this.getHistoryList(false)
  1419. }
  1420. }, 1000)
  1421. workerInstance.onmessage = (e: MessageEvents): void => {
  1422. const message = e.data as LocalMusicWorkerMessage;
  1423. switch (message.code) {
  1424. case 101: //第一次扫描文件夹入库
  1425. ToastUtil.showToast('刷新同步数据库成功!')
  1426. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  1427. this.doAllUpdateData()
  1428. break;
  1429. case 102: //查询媒体库列表
  1430. this.isRefreshing = false
  1431. this.mediaKuList = message.data // 只包含前100条
  1432. const mediaTotalCount: number = message.totalCount ?? this.mediaKuList.length;
  1433. this.mediaKuCount = mediaTotalCount;
  1434. Logger.info(`heanup 查询媒体库列表 缓存数=${this.mediaKuList.length}, 总数=${mediaTotalCount}`)
  1435. Utility.doSortListAscending(this.mediaKuList)
  1436. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  1437. // 媒体库模式下重新加载第一页(分页查询)
  1438. if (this.modeType === 1) {
  1439. this.resetAndLoadFirstPage();
  1440. }
  1441. PreferencesUtil.putSync('mediaKuCount', mediaTotalCount)
  1442. // 只保存前100条记录到缓存中
  1443. PreferencesUtil.putSync('mediaKuList', JSON.stringify(this.mediaKuList));
  1444. break;
  1445. case 103: //收到查询艺术家列表
  1446. this.isRefreshing = false
  1447. this.artistMap = message.data1; // 只包含前60个艺术家的歌曲
  1448. this.artistList = message.data2; // 只包含前100个艺术家
  1449. const artistTotalCount: number = message.totalCount ?? this.artistList.length;
  1450. this.artistCount = artistTotalCount;
  1451. const nextArtistCountMap = new Map(this.artistSongCountMap);
  1452. this.artistMap.forEach((songs, artist) => {
  1453. nextArtistCountMap.set(artist, songs.length);
  1454. });
  1455. this.artistSongCountMap = nextArtistCountMap;
  1456. Logger.info(`heanup 查询艺术家列表 缓存数=${this.artistList.length}, 总数=${artistTotalCount}`)
  1457. PreferencesUtil.putSync('artistCount', artistTotalCount)
  1458. // 艺术家模式下重新加载第一页(分页查询)
  1459. if (this.modeType === 2) {
  1460. this.resetAndLoadFirstPage();
  1461. }
  1462. // 保存前100条艺术家列表
  1463. PreferencesUtil.putSync('artistList', JSON.stringify(this.artistList));
  1464. // 保存前60条艺术家的歌曲Map
  1465. const sortedEntries = Array.from(this.artistMap.entries());
  1466. PreferencesUtil.putSync('artistMap', JSON.stringify(sortedEntries));
  1467. break;
  1468. case 104: //收到查询专辑列表
  1469. this.isRefreshing = false
  1470. this.albumMap = message.data1;
  1471. this.albumList = message.data2
  1472. const albumTotalCount: number = message.totalCount ?? this.albumList.length;
  1473. this.albumCount = albumTotalCount;
  1474. const nextAlbumCountMap = new Map(this.albumSongCountMap);
  1475. this.albumMap.forEach((songs, album) => {
  1476. nextAlbumCountMap.set(album, songs.length);
  1477. });
  1478. this.albumSongCountMap = nextAlbumCountMap;
  1479. Logger.info(`heanup 查询专辑列表 缓存数=${this.albumList.length}, 总数=${albumTotalCount}`)
  1480. // 专辑模式下重新加载第一页(分页查询)
  1481. if (this.modeType === 3) {
  1482. this.resetAndLoadFirstPage();
  1483. }
  1484. //查询完毕在启动是否自动播放
  1485. if (this.isStartAutoPlay&&this.isCanAuto) {
  1486. this.isCanAuto = false
  1487. console.info('onecold startPlayOrResumePlay 757')
  1488. this.startPlayOrResumePlay()
  1489. }
  1490. PreferencesUtil.putSync('albumCount', albumTotalCount)
  1491. // 保存前100条专辑列表(Worker已经只发送了100条)
  1492. PreferencesUtil.putSync('albumList', JSON.stringify(this.albumList));
  1493. // 保存前60条专辑Map(Worker已经只发送了60条)
  1494. const mapArrayAlbum = Array.from(this.albumMap.entries());
  1495. PreferencesUtil.putSync('albumMap', JSON.stringify(mapArrayAlbum));
  1496. break;
  1497. case 105: // 缓存完成后返回的元数据
  1498. this.handleWorkerMetadataPayload(message.data);
  1499. break;
  1500. case 106: // 编辑音乐元数据和封面完成
  1501. this.handleEditMusicResult(message.data);
  1502. break;
  1503. }
  1504. };
  1505. // 在调用terminate后,执行onexit
  1506. workerInstance.onexit = (code) => {
  1507. metadataExtractionInFlight.clear();
  1508. Logger.info(TAG, 'workerInstance 线程已退出,code: ' + code);
  1509. }
  1510. workerInstance.onerror = (err: ErrorEvent) => {
  1511. metadataExtractionInFlight.clear();
  1512. console.error('workerInstance 线程执行发生异常: ' + err.message)
  1513. }
  1514. }
  1515. private handleWorkerMetadataPayload(payload: WorkerMetadataPayload | undefined): void {
  1516. if (!payload || !payload.originFilePath) {
  1517. return;
  1518. }
  1519. metadataExtractionInFlight.delete(payload.originFilePath);
  1520. if (payload.error) {
  1521. Logger.warn(TAG, `缓存文件元数据解析失败: ${payload.error}`);
  1522. return;
  1523. }
  1524. this.applyMetadataToCollections(payload.originFilePath, payload);
  1525. }
  1526. private applyMetadataToCollections(filePath: string, payload: WorkerMetadataPayload): void {
  1527. const targets: Array<VideoItem> = [];
  1528. let mainListUpdated = false;
  1529. let playlistUpdated = false;
  1530. if (this.currentSong && this.currentSong.filePath === filePath) {
  1531. targets.push(this.currentSong);
  1532. }
  1533. const collectFromList = (list?: Array<VideoItem>, markUpdated?: () => void) => {
  1534. if (!list || list.length === 0) {
  1535. return;
  1536. }
  1537. const found = Utility.getItemByFilePath(list, filePath);
  1538. if (found) {
  1539. markUpdated?.();
  1540. targets.push(found);
  1541. }
  1542. };
  1543. collectFromList(this.videoLocalList, () => {
  1544. mainListUpdated = true;
  1545. });
  1546. collectFromList(this.songList, () => {
  1547. playlistUpdated = true;
  1548. });
  1549. collectFromList(this.historyList);
  1550. collectFromList(this.favList);
  1551. const remoteManager = RemoteDriveManager.getInstance();
  1552. collectFromList(remoteManager.webDavSongs);
  1553. const updated = new Set<VideoItem>();
  1554. const remoteMetadataUpdates: Map<string, WebDavMetadataUpdatePayload> = new Map();
  1555. for (let i = 0; i < targets.length; i++) {
  1556. const target = targets[i];
  1557. if (!target || updated.has(target)) {
  1558. continue;
  1559. }
  1560. updated.add(target);
  1561. this.mergeVideoItemWithPayload(target, payload);
  1562. if (isRemoteCloudType(target.type) && StrUtil.isNotEmpty(target.filePath)) {
  1563. remoteMetadataUpdates.set(target.filePath, {
  1564. filePath: target.filePath,
  1565. pixelMapPath: target.pixelMapPath,
  1566. isCustomCover: target.isCustomCover,
  1567. md5Str: target.md5Str,
  1568. name: target.name,
  1569. artist: target.artist
  1570. });
  1571. }
  1572. }
  1573. if (this.currentSong && this.currentSong.filePath === filePath) {
  1574. this.mergeVideoItemWithPayload(this.currentSong, payload);
  1575. if (payload.name) {
  1576. this.name = payload.name;
  1577. }
  1578. if (payload.artist) {
  1579. this.artist = payload.artist;
  1580. }
  1581. if (payload.pixelMapPath && this.currentSong?.pixelMapPath) {
  1582. this.cover = this.currentSong.pixelMapPath;
  1583. }
  1584. if (payload.lyricContent) {
  1585. this.applyInlineLyricContent(payload.lyricContent);
  1586. }
  1587. let avSessionDurationMs: number = this.duration;
  1588. if (payload.duration) {
  1589. const durationSeconds = Number(payload.duration);
  1590. if (!Number.isNaN(durationSeconds) && durationSeconds > 0) {
  1591. avSessionDurationMs = durationSeconds * 1000;
  1592. this.duration = avSessionDurationMs;
  1593. this.durationTime = Math.floor(avSessionDurationMs / 1000);
  1594. this.durationStringTime = secondToTime(this.durationTime);
  1595. }
  1596. }
  1597. if (avSessionDurationMs > 0) {
  1598. this.avSessionController.setAVMetadataMusic(this.currentSong, avSessionDurationMs, this.lyricContent);
  1599. }
  1600. this.currentSong = cloneVideoItem(this.currentSong);
  1601. AppStorage.setOrCreate('currentSong', this.currentSong);
  1602. }
  1603. const primaryTarget = targets.length > 0 ? targets[0] : undefined;
  1604. if (primaryTarget) {
  1605. this.persistRemoteMetadataToDb(primaryTarget).catch((error: Error) => {
  1606. Logger.error(TAG, `缓存元数据持久化失败: ${error.message}`);
  1607. });
  1608. }
  1609. if (remoteMetadataUpdates.size > 0) {
  1610. const eventUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
  1611. emitter.emit(eventUpdate, { data: Array.from(remoteMetadataUpdates.values()) });
  1612. }
  1613. this.refreshLazyListViews(mainListUpdated, playlistUpdated);
  1614. }
  1615. private handleEditMusicResult(result: WorkerEditMusicResult): void {
  1616. // 关闭进度条
  1617. DialogHelper.closeDialog(this.loadingDialogId)
  1618. if (result.success) {
  1619. console.log("heanup 编辑信息成功,数据库已同步");
  1620. if (result.coverResult) {
  1621. ToastUtil.showToast('内嵌封面成功');
  1622. }
  1623. ToastUtil.showToast('内嵌音乐标签成功');
  1624. this.isShowMoreView = false;
  1625. this.name = this.titleStr;
  1626. // 同步当前播放的歌曲信息
  1627. if (this.editingItem && this.currentSong && this.editingItem.filePath == this.currentSong.filePath) {
  1628. this.currentSong.name = this.titleStr;
  1629. this.artist = this.artistStr;
  1630. this.currentSong.artist = this.artistStr;
  1631. this.currentSong.album = this.ablumStr;
  1632. this.currentSong.year = this.yearStr;
  1633. this.currentSong.genre = this.genreStr;
  1634. this.currentSong.track = this.trackStr;
  1635. this.currentSong.lyricContent = this.lyricConStr;
  1636. this.currentSong.ALBUMARTIST = this.albumArtistStr;
  1637. this.currentSong.COMPOSER = this.composerStr;
  1638. this.currentSong.LYRICIST = this.lyricistStr;
  1639. this.currentSong.COMMENT = this.commentStr;
  1640. }
  1641. // if (result.needRefreshList && this.modeType == 0) {
  1642. // this.deleteCache(this.currentPath);
  1643. // this.getSortedFiles(this.currentPath);
  1644. // }
  1645. // 同步编辑字段到本地列表
  1646. if (this.editingItem) {
  1647. this.syncEditedFields(this.editingItem);
  1648. this.syncListsAfterEdit(this.editingItem.filePath);
  1649. this.doUpateEditedFields(this.editingItem);
  1650. }
  1651. // 清理临时变量
  1652. this.longItemFilePath = '';
  1653. this.tempLyricContent = '';
  1654. this.isShowEdit = false;
  1655. this.imagePathStr = '';
  1656. } else {
  1657. console.error("heanup 编辑信息失败: " + result.error);
  1658. ToastUtil.showToast('编辑失败: ' + (result.error || '未知错误'));
  1659. // 清理临时变量
  1660. this.longItemFilePath = '';
  1661. this.tempLyricContent = '';
  1662. this.isShowEdit = false;
  1663. this.imagePathStr = '';
  1664. }
  1665. }
  1666. private assignStringMetadata(target: VideoItem, key: keyof VideoItem, value?: string | null, allowEmpty = false): void {
  1667. if (value === undefined || value === null) {
  1668. return;
  1669. }
  1670. const text = value.toString();
  1671. if (!allowEmpty && text.trim().length === 0) {
  1672. return;
  1673. }
  1674. Reflect.set(target, key as string, value);
  1675. }
  1676. private assignNumberMetadata(target: VideoItem, key: keyof VideoItem, value?: number | null): void {
  1677. if (value === undefined || value === null || Number.isNaN(value)) {
  1678. return;
  1679. }
  1680. Reflect.set(target, key as string, value);
  1681. }
  1682. private mergeVideoItemWithPayload(target: VideoItem, payload: WorkerMetadataPayload): void {
  1683. if (!target || !payload) {
  1684. return;
  1685. }
  1686. this.assignStringMetadata(target, 'name', payload.name);
  1687. this.assignStringMetadata(target, 'artist', payload.artist);
  1688. this.assignStringMetadata(target, 'album', payload.album);
  1689. this.assignStringMetadata(target, 'bit_rate', payload.bit_rate);
  1690. this.assignStringMetadata(target, 'duration', payload.duration);
  1691. this.assignStringMetadata(target, 'sampleRate', payload.sampleRate);
  1692. this.assignStringMetadata(target, 'mimeType', payload.mimeType);
  1693. this.assignStringMetadata(target, 'md5Str', payload.md5Str);
  1694. this.assignStringMetadata(target, 'size', payload.size);
  1695. mergeCoverWithPriority(target, payload.pixelMapPath);
  1696. this.assignStringMetadata(target, 'lyricContent', payload.lyricContent, true);
  1697. this.assignStringMetadata(target, 'genre', payload.genre);
  1698. this.assignStringMetadata(target, 'track', payload.track);
  1699. this.assignStringMetadata(target, 'bits_per_raw_sample', payload.bits_per_raw_sample);
  1700. this.assignStringMetadata(target, 'channels', payload.channels);
  1701. this.assignStringMetadata(target, 'channel_layout', payload.channel_layout);
  1702. this.assignStringMetadata(target, 'start_time', payload.start_time);
  1703. this.assignStringMetadata(target, 'year', payload.year);
  1704. this.assignStringMetadata(target, 'disc', payload.disc);
  1705. this.assignStringMetadata(target, 'ALBUMARTIST', payload.ALBUMARTIST);
  1706. this.assignStringMetadata(target, 'COMPOSER', payload.COMPOSER);
  1707. this.assignStringMetadata(target, 'LYRICIST', payload.LYRICIST);
  1708. this.assignStringMetadata(target, 'COMMENT', payload.COMMENT, true);
  1709. this.assignNumberMetadata(target, 'videoSize', payload.videoSize);
  1710. this.assignNumberMetadata(target, 'probe_score', payload.probe_score);
  1711. this.assignNumberMetadata(target, 'nb_streams', payload.nb_streams);
  1712. this.assignNumberMetadata(target, 'nb_programs', payload.nb_programs);
  1713. }
  1714. private mergeVideoItemFromSource(target: VideoItem, source: VideoItem): void {
  1715. if (!target || !source) {
  1716. return;
  1717. }
  1718. this.assignStringMetadata(target, 'name', source.name);
  1719. this.assignStringMetadata(target, 'artist', source.artist);
  1720. this.assignStringMetadata(target, 'album', source.album);
  1721. this.assignStringMetadata(target, 'bit_rate', source.bit_rate);
  1722. this.assignStringMetadata(target, 'duration', source.duration);
  1723. this.assignStringMetadata(target, 'sampleRate', source.sampleRate);
  1724. this.assignStringMetadata(target, 'md5Str', source.md5Str);
  1725. this.assignStringMetadata(target, 'trackCount', source.trackCount);
  1726. this.assignStringMetadata(target, 'mimeType', source.mimeType);
  1727. this.assignStringMetadata(target, 'size', source.size);
  1728. mergeCoverWithPriority(target, source.pixelMapPath, source.isCustomCover ?? 0);
  1729. this.assignStringMetadata(target, 'lyricContent', source.lyricContent, true);
  1730. this.assignStringMetadata(target, 'genre', source.genre);
  1731. this.assignStringMetadata(target, 'track', source.track);
  1732. this.assignStringMetadata(target, 'bits_per_raw_sample', source.bits_per_raw_sample);
  1733. this.assignStringMetadata(target, 'channels', source.channels);
  1734. this.assignStringMetadata(target, 'channel_layout', source.channel_layout);
  1735. this.assignStringMetadata(target, 'start_time', source.start_time);
  1736. this.assignStringMetadata(target, 'year', source.year);
  1737. this.assignStringMetadata(target, 'disc', source.disc);
  1738. this.assignStringMetadata(target, 'ALBUMARTIST', source.ALBUMARTIST);
  1739. this.assignStringMetadata(target, 'COMPOSER', source.COMPOSER);
  1740. this.assignStringMetadata(target, 'LYRICIST', source.LYRICIST);
  1741. this.assignStringMetadata(target, 'COMMENT', source.COMMENT, true);
  1742. this.assignNumberMetadata(target, 'videoSize', source.videoSize);
  1743. this.assignNumberMetadata(target, 'probe_score', source.probe_score);
  1744. this.assignNumberMetadata(target, 'nb_streams', source.nb_streams);
  1745. this.assignNumberMetadata(target, 'nb_programs', source.nb_programs);
  1746. if (source.remote_rel_path && StrUtil.isEmpty(target.remote_rel_path)) {
  1747. target.remote_rel_path = source.remote_rel_path;
  1748. }
  1749. }
  1750. private async hydrateRemoteSongFromDb(item: VideoItem | undefined): Promise<void> {
  1751. if (!item || !isRemoteCloudType(item.type)) {
  1752. return;
  1753. }
  1754. const storagePath = item.remote_rel_path || WebDavUrlUtil.toStoragePath(item.filePath);
  1755. if (!storagePath) {
  1756. return;
  1757. }
  1758. try {
  1759. const cached = await this.table.queryVideoByFilePath(storagePath);
  1760. if (!cached) {
  1761. return;
  1762. }
  1763. this.mergeVideoItemFromSource(item, cached);
  1764. if (StrUtil.isEmpty(item.remote_rel_path)) {
  1765. item.remote_rel_path = storagePath;
  1766. }
  1767. if (item === this.currentSong) {
  1768. if (StrUtil.isNotEmpty(item.name)) {
  1769. this.name = item.name;
  1770. }
  1771. if (StrUtil.isNotEmpty(item.artist)) {
  1772. this.artist = item.artist!;
  1773. }
  1774. if (StrUtil.isNotEmpty(item.pixelMapPath)) {
  1775. this.cover = item.pixelMapPath!;
  1776. }
  1777. if (StrUtil.isNotEmpty(item.lyricContent) && StrUtil.isEmpty(this.lyricContent)) {
  1778. this.applyInlineLyricContent(item.lyricContent as string);
  1779. }
  1780. }
  1781. } catch (error) {
  1782. Logger.error(TAG, `hydrateRemoteSongFromDb 失败: ${(error as Error).message}`);
  1783. }
  1784. }
  1785. private applyInlineLyricContent(content: string): void {
  1786. if (StrUtil.isEmpty(content)) {
  1787. return;
  1788. }
  1789. this.lyricContent = content;
  1790. const lines: string[] = content.split('\n').map((line: string) => line.trim());
  1791. const lyric: Lyric = this.parser.parse(lines);
  1792. this.lyricController.setLyric(lyric);
  1793. this.lyricControllerXF.setLyric(lyric);
  1794. this.lyricControllerSingle.setLyric(lyric);
  1795. }
  1796. private extractParentPathFromStoragePath(path: string): string {
  1797. if (!path) {
  1798. return '';
  1799. }
  1800. const lastSlash = path.lastIndexOf('/');
  1801. if (lastSlash <= 0) {
  1802. return '';
  1803. }
  1804. return path.substring(0, lastSlash);
  1805. }
  1806. private resolveRemoteStoragePath(target: VideoItem): string | null {
  1807. if (!target || !isRemoteCloudType(target.type)) {
  1808. return null;
  1809. }
  1810. if (isWebDavType(target.type)) {
  1811. const storagePath = target.remote_rel_path || WebDavUrlUtil.toStoragePath(target.filePath);
  1812. if (storagePath) {
  1813. target.remote_rel_path = storagePath;
  1814. return storagePath;
  1815. }
  1816. return null;
  1817. }
  1818. if (target.remote_rel_path && target.remote_rel_path.length > 0) {
  1819. return target.remote_rel_path;
  1820. }
  1821. return null;
  1822. }
  1823. private async persistRemoteMetadataToDb(target: VideoItem): Promise<void> {
  1824. if (!this.context || !target || !isRemoteCloudType(target.type)) {
  1825. return;
  1826. }
  1827. const storagePath = this.resolveRemoteStoragePath(target);
  1828. if (!storagePath) {
  1829. return;
  1830. }
  1831. const table = new MediaTable(this.context);
  1832. await new Promise<void>((resolve) => {
  1833. table.getRdbStore(this.context as Context, () => resolve());
  1834. });
  1835. const cloneItem = cloneVideoItem(target);
  1836. cloneItem.filePath = storagePath;
  1837. cloneItem.remote_rel_path = storagePath;
  1838. cloneItem.parentPath = this.extractParentPathFromStoragePath(storagePath);
  1839. await table.saveOrUpdateWebDavItem(cloneItem);
  1840. }
  1841. onPageHide() {
  1842. this.knockController?.immersiveDisableListening();
  1843. }
  1844. @State isFirstStartPlay: boolean = false
  1845. private async startFileDeletionWatcher(): Promise<void> {
  1846. if (!this.rootPath) {
  1847. return;
  1848. }
  1849. if (!this.deletionWatcher) {
  1850. this.deletionWatcher = new FileDeletionWatcher(this.context, this.table);
  1851. }
  1852. try {
  1853. await this.deletionWatcher.watchDirectories([
  1854. this.rootPath,
  1855. this.lockPath,
  1856. this.favPath,
  1857. this.historyPath
  1858. ]);
  1859. } catch (error) {
  1860. Logger.error(TAG, `初始化文件删除监听失败: ${(error as Error).message}`);
  1861. }
  1862. }
  1863. //获取download_path
  1864. async mkDownLoadDir() {
  1865. const documentViewPicker = new picker.DocumentViewPicker()
  1866. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  1867. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  1868. PreferencesUtil.putSync('download_path', this.rootPath+'/')
  1869. this.currentPath = this.rootPath
  1870. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  1871. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  1872. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  1873. Logger.info('onecold rootPath = ' + this.rootPath)
  1874. if (!FileUtil.accessSync(this.favPath)) {
  1875. FileUtil.mkdirSync(this.favPath)
  1876. }
  1877. if (!FileUtil.accessSync(this.historyPath)) {
  1878. FileUtil.mkdirSync(this.historyPath)
  1879. }
  1880. // await this.startFileDeletionWatcher();
  1881. this.getSortedFiles(this.rootPath).then(async () => {
  1882. this.isFavMusic = false
  1883. //穿山甲
  1884. // this.loadBannerAd(CSJUtil.getBannerID())
  1885. this.restoreLastPlayContext();
  1886. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  1887. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  1888. if (ArrayUtil.isEmpty(this.songList)) {
  1889. this.songList = this.videoLocalList.filter(item =>
  1890. item.type === CommonConstants.TYPE_LOCAL && !this.isIsoLocalFile(item))
  1891. } else {
  1892. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  1893. }
  1894. if (ArrayUtil.isNotEmpty(this.songList)) {
  1895. this.isFirstStartPlay = true
  1896. this.sonDataSource.pushArrayData(this.songList)
  1897. if (this.currentSong === undefined) {
  1898. this.isFirstStartPlay = false
  1899. this.currentSong = this.songList[0]
  1900. }
  1901. const restoredUrl = await this.resolvePlaybackUrlForCurrentSong('restore-last-song');
  1902. if (!restoredUrl) {
  1903. return;
  1904. }
  1905. this.videoUrl = restoredUrl;
  1906. Logger.info(TAG, `WebDAV URL同步构建完成: ${this.videoUrl}`);
  1907. this.name = this.currentSong.name
  1908. this.cover = this.currentSong.pixelMapPath
  1909. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  1910. } else {
  1911. this.name = '空空如也'
  1912. }
  1913. })
  1914. this.getFavList(false)
  1915. }
  1916. getFavList(isFavRefresh: boolean) {
  1917. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  1918. this.favList = result
  1919. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  1920. this.videoLocalList = this.favList
  1921. this.updateListData(this.videoLocalList, true)
  1922. }
  1923. })
  1924. }
  1925. getHistoryList(isRefresh: boolean) {
  1926. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  1927. this.historyList = result
  1928. // for (let i = 0; i < this.historyList.length; i++) {
  1929. //
  1930. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  1931. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  1932. // }
  1933. if (isRefresh) {
  1934. this.videoLocalList = this.historyList
  1935. this.updateListData(this.videoLocalList, true)
  1936. }
  1937. })
  1938. }
  1939. // 组件消失生命周期
  1940. aboutToDisappear() {
  1941. console.info('LifeCycleComponent aboutToDisappear');
  1942. if (this.alphaBetHideTimer) {
  1943. clearTimeout(this.alphaBetHideTimer);
  1944. this.alphaBetHideTimer = 0;
  1945. }
  1946. if (this.alphaBetRebuildTimer) {
  1947. clearTimeout(this.alphaBetRebuildTimer);
  1948. this.alphaBetRebuildTimer = 0;
  1949. }
  1950. if (this.pagingScheduleTimer) {
  1951. clearTimeout(this.pagingScheduleTimer);
  1952. this.pagingScheduleTimer = 0;
  1953. }
  1954. if (this.gridWaterScrollIdleTimer) {
  1955. clearTimeout(this.gridWaterScrollIdleTimer);
  1956. this.gridWaterScrollIdleTimer = 0;
  1957. }
  1958. if (this.listUpdateTimer) {
  1959. clearTimeout(this.listUpdateTimer);
  1960. this.listUpdateTimer = 0;
  1961. }
  1962. if (this.mediaLibraryWarmupPrefetchTimer) {
  1963. clearTimeout(this.mediaLibraryWarmupPrefetchTimer);
  1964. this.mediaLibraryWarmupPrefetchTimer = 0;
  1965. }
  1966. this.clearInitialSeekGuardTimer();
  1967. this.alphaBetBuildVersion++;
  1968. this.gridWaterLastActiveTs = 0;
  1969. this.coverThumbCache.dispose();
  1970. this.coverThumbCacheReady = false;
  1971. this.pendingCoverThumbRefresh = false;
  1972. this.deletionWatcher?.stop();
  1973. this.knockController?.immersiveDisableListening();
  1974. this.curIndex = 0
  1975. this.isAppForeground = false;
  1976. emitter.off(EventConstants.EVENT_AUDIO_OPEN);
  1977. emitter.off(EventConstants.EVENT_SCAN_UPDATE);
  1978. emitter.off(EventConstants.EVENT_SWIPE_BACK_UPDATE);
  1979. emitter.off(EventConstants.EVENT_SETTING_UPDATE);
  1980. emitter.off(EventConstants.EVENT_WEBDAV_METADATA_UPDATED);
  1981. emitter.off(EventConstants.EVENT_EQUALIZER_CHANGED);
  1982. emitter.off(EventConstants.EVENT_PLAY_QUEUE_REFRESH);
  1983. this.mDestroyPage = true;
  1984. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  1985. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  1986. this.stop();
  1987. }
  1988. this.mIjkMediaPlayer.off('audioInterrupt');
  1989. this.mIjkMediaPlayer.off('deviceChange');
  1990. if (workerInstance) {
  1991. workerInstance.terminate();
  1992. }
  1993. this.stopPip();
  1994. this.destroyPipController()
  1995. this.getUIContext().getHostContext()!.eventHub.off('playOrPause');
  1996. this.getUIContext().getHostContext()!.eventHub.off('playPrevious');
  1997. this.getUIContext().getHostContext()!.eventHub.off('playNext');
  1998. this.getUIContext().getHostContext()!.eventHub.off('showPlayerView');
  1999. this.getUIContext().getHostContext()!.eventHub.off('openPlayList');
  2000. this.eventHub.off('onStateChange');
  2001. }
  2002. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean,
  2003. openItem?: VideoItem, immediateListUpdate?: boolean, scrollTopAfterUpdate?: boolean) {
  2004. this.isFavMusic = false
  2005. console.info('onecold getSortedFiles 1 curPath '+curPath)
  2006. if (isWorkerPost) {
  2007. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  2008. }
  2009. if (this.modeType !== 0) {
  2010. // 第三方打开场景:非文件夹模式也需要继续执行自动播放
  2011. if (isOpen && destPath) {
  2012. this.openMusic(true, destPath, openItem)
  2013. }
  2014. return
  2015. }
  2016. console.info('onecold getSortedFiles 2')
  2017. this.isCanBack = false
  2018. this.currentPath = curPath
  2019. console.info('onecold getSortedFiles this.currentPath ='+this.currentPath)
  2020. this.titleName = getFileDirName(this.currentPath,this.rootPath)
  2021. if (curPath === this.rootPath) {
  2022. this.rightTopImage = $r('sys.symbol.sort')
  2023. } else {
  2024. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  2025. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  2026. this.rightTopImage = $r('sys.symbol.chevron_left')
  2027. }
  2028. }
  2029. // Get the current file list and calculate its hash
  2030. this.fileList = FileUtil.listFileSync(curPath);
  2031. const currentHash = simpleHash(this.fileList);
  2032. // Check cache
  2033. const cachedValue = this.findCache(curPath);
  2034. Logger.info('onecold cachedValue = ' + cachedValue)
  2035. const cachedHash = this.findStringCache(curPath + '_hash');
  2036. const cachedDirList = this.findCache(curPath + "_dirList");
  2037. if (cachedValue !== undefined&&!this.isRefreshing) {
  2038. // this.videoLocalList = cachedValue;
  2039. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  2040. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  2041. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  2042. }
  2043. this.isRefreshing = false
  2044. this.updateListData(cachedValue, undefined, immediateListUpdate)
  2045. if (scrollTopAfterUpdate) {
  2046. this.scrollToTopForCurrentLayout()
  2047. }
  2048. }
  2049. if (cachedDirList !== undefined) {
  2050. this.dirList = cachedDirList
  2051. }
  2052. //通过当前hash值和缓存hash判断list有没有变化
  2053. if (cachedValue && cachedHash === currentHash) {
  2054. return;
  2055. }
  2056. // this.fileList = FileUtil.listFileSync(curPath)
  2057. let directories: Array<VideoItem> = [];
  2058. let isoFiles: Array<VideoItem> = this.getLocalIsoItems(curPath, this.fileList);
  2059. let files: Array<VideoItem> = [];
  2060. for (let i = 0; i < this.fileList.length; i++) {
  2061. // console.info(`The name of file: ${this.fileList[i]}`);
  2062. let path = curPath + '/' + this.fileList[i]
  2063. if (FileUtil.isDirectory(path)) {
  2064. let item: VideoItem =
  2065. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  2066. '')
  2067. if (this.isShowDir(item.name)) {
  2068. directories.push(item);
  2069. }
  2070. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2071. // Utility.doSortListAscending(directories)
  2072. } else {
  2073. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  2074. let item: VideoItem =
  2075. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  2076. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  2077. files.push(item);
  2078. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2079. // this.doSortListAscending(files)
  2080. }
  2081. }
  2082. }
  2083. }
  2084. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  2085. if (this.currentPath !== this.lockPath) {
  2086. files = result.filter(item => !this.isIsoLocalFile(item));
  2087. }
  2088. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2089. Utility.doSortListAscending(files)
  2090. Utility.doSortListAscending(isoFiles)
  2091. if (this.currentPath === this.rootPath) {
  2092. this.dirList = directories
  2093. this.addCache(curPath + "_dirList", this.dirList);
  2094. }
  2095. //插入广告先注释掉
  2096. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  2097. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  2098. // directories.push(adItem)
  2099. // }
  2100. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  2101. this.videoLocalList = directories.concat(isoFiles).concat(files);
  2102. this.updateListData(this.videoLocalList, undefined, immediateListUpdate)
  2103. if (scrollTopAfterUpdate) {
  2104. this.scrollToTopForCurrentLayout()
  2105. }
  2106. if (ArrayUtil.isNotEmpty(files)) {
  2107. if (this.currentPath != this.rootPath) {
  2108. if (files) {
  2109. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  2110. }
  2111. }
  2112. }
  2113. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2114. this.addCache(curPath, this.videoLocalList);
  2115. await this.saveCacheToStorage();
  2116. this.addStringCache(curPath + '_hash', currentHash);
  2117. }
  2118. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  2119. for (let i = 0; i < this.videoLocalList.length; i++) {
  2120. console.info(`onecold gengxin 1: ${this.videoLocalList[i].name}`);
  2121. }
  2122. // this.setButtonStatus()
  2123. this.openMusic(isOpen, destPath,openItem)
  2124. this.isRefreshing = false
  2125. });
  2126. }
  2127. //第三方app打开天天静听导入音乐后播放
  2128. openMusic(isOpen?: boolean, destPath?: string,openItem?:VideoItem){
  2129. if (isOpen&&destPath) {
  2130. if (destPath === undefined) {
  2131. // 处理 destPath 为 undefined 的情况
  2132. return
  2133. }
  2134. if (destPath.endsWith('.lrc')) {
  2135. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  2136. if (StrUtil.isNotEmpty(this.videoUrl)) {
  2137. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  2138. this.initLyric(lyricPath);
  2139. }
  2140. return
  2141. }
  2142. if(openItem){
  2143. this.doPlay(openItem,0,false,true)
  2144. // this.isShowPlay = true
  2145. this.setShowPlayTrue()
  2146. }
  2147. }
  2148. }
  2149. //扫描文件夹入库
  2150. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  2151. const files = FileUtil.listFileSync(curPath);
  2152. let mediaItems: VideoItem[] = [];
  2153. Logger.info('onecold scanDirectory start ')
  2154. for (const file of files) {
  2155. const fPath = `${curPath}/${file}`;
  2156. if (fPath === this.lockPath) {
  2157. Logger.info(`Skipping locked path: ${fPath}`);
  2158. continue;
  2159. }
  2160. if (FileUtil.isDirectory(fPath)) {
  2161. // Recursively scan subdirectories
  2162. const subDirItems = await this.scanDirectory(fPath);
  2163. mediaItems = mediaItems.concat(subDirItems);
  2164. } else {
  2165. Logger.info('onecold scanDirectory filePath = ' + fPath)
  2166. // Process media files
  2167. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  2168. let mediaItem: VideoItem =
  2169. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2170. mediaItems.push(mediaItem);
  2171. this.table.insert(mediaItem, (id: number) => {
  2172. });
  2173. }
  2174. }
  2175. }
  2176. return mediaItems;
  2177. }
  2178. updateListData(mList: Array<VideoItem>, noSort?: boolean, immediate?: boolean) {
  2179. this.isShowTitleBar = true
  2180. const shouldAnimate = !immediate
  2181. if (this.listUpdateTimer) {
  2182. clearTimeout(this.listUpdateTimer)
  2183. this.listUpdateTimer = 0
  2184. }
  2185. const updateVersion = ++this.listUpdateVersion
  2186. if (shouldAnimate) {
  2187. this.getUIContext().animateTo({ duration: 666 }, () => {
  2188. this.opacityItem = 0.5;
  2189. });
  2190. }
  2191. const applyListData = () => {
  2192. if (updateVersion !== this.listUpdateVersion) {
  2193. return
  2194. }
  2195. this.videoLocalList = mList;
  2196. if (!noSort) {
  2197. if (this.modeType === 0 || this.modeType === 1) {
  2198. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  2199. this.doSortType(this.sortType)
  2200. }
  2201. }
  2202. this.dataSource.pushArrayData(this.videoLocalList)
  2203. if (shouldAnimate) {
  2204. this.getUIContext().animateTo({ duration: 666 }, () => {
  2205. this.opacityItem = 1;
  2206. });
  2207. } else {
  2208. this.opacityItem = 1;
  2209. }
  2210. this.setButtonStatus()
  2211. //添加到字母索引表
  2212. this.markAlphaBetDirty()
  2213. };
  2214. if (immediate) {
  2215. applyListData();
  2216. return;
  2217. }
  2218. this.listUpdateTimer = setTimeout(() => {
  2219. this.listUpdateTimer = 0
  2220. applyListData();
  2221. }, 200);
  2222. }
  2223. getCurFileList(): Array<VideoItem> {
  2224. const source = this.isSearchMode ? this.filteredList : this.videoLocalList
  2225. let files: Array<VideoItem> = [];
  2226. if (ArrayUtil.isNotEmpty(source)) {
  2227. for (let i = 0; i < source.length; i++) {
  2228. if (this.isSelectableLocalItem(source[i])) {
  2229. files.push(source[i]);
  2230. }
  2231. }
  2232. }
  2233. return files
  2234. }
  2235. private isProtectedLocalDirectory(item: VideoItem): boolean {
  2236. return item.type === CommonConstants.TYPE_IS_DIR &&
  2237. (item.name === LocalMusic.STR_LOCK_VIDEO ||
  2238. item.name === LocalMusic.STR_FAC_VIDEO ||
  2239. item.name === LocalMusic.STR_HISTORY_MUSIC)
  2240. }
  2241. private isIsoLocalFile(item?: VideoItem | null): boolean {
  2242. if (!item || item.type !== CommonConstants.TYPE_LOCAL) {
  2243. return false
  2244. }
  2245. return Utility.isIsoByExtension(item.filePath || item.fileName || item.name || '')
  2246. }
  2247. private supportsLocalAudioActions(item: VideoItem): boolean {
  2248. return !!item && item.type !== CommonConstants.TYPE_IS_DIR && !this.isIsoLocalFile(item)
  2249. }
  2250. private buildLocalIsoItem(filePath: string, fileName?: string): VideoItem {
  2251. const displayName = fileName || FileUtil.getFileName(filePath) || filePath
  2252. let fileSize = 0
  2253. try {
  2254. const stat = fs.statSync(filePath) as fs.Stat
  2255. if (typeof stat.size === 'number') {
  2256. fileSize = stat.size
  2257. }
  2258. } catch (_error) {
  2259. }
  2260. const item = new VideoItem(
  2261. displayName,
  2262. filePath,
  2263. filePath,
  2264. CommonConstants.TYPE_LOCAL,
  2265. fileSize,
  2266. Utility.getFormatDateStr(Date.now(), 'yyyy-MM-dd HH:mm'),
  2267. Utility.formatFSize(fileSize),
  2268. '',
  2269. 'ISO 镜像',
  2270. '可提取音频',
  2271. displayName
  2272. )
  2273. item.mimeType = 'application/x-iso9660-image'
  2274. item.duration = ''
  2275. return item
  2276. }
  2277. private getLocalIsoItems(curPath: string, fileNames?: Array<string>): Array<VideoItem> {
  2278. let sourceNames: Array<string> = []
  2279. if (fileNames !== undefined && fileNames.length > 0) {
  2280. sourceNames = fileNames
  2281. } else {
  2282. const listedNames = FileUtil.listFileSync(curPath)
  2283. sourceNames = listedNames ? listedNames : []
  2284. }
  2285. const isoItems: Array<VideoItem> = []
  2286. for (let i = 0; i < sourceNames.length; i++) {
  2287. const name = sourceNames[i]
  2288. const fullPath = `${curPath}/${name}`
  2289. if (FileUtil.isDirectory(fullPath) || !Utility.isIsoByExtension(fullPath)) {
  2290. continue
  2291. }
  2292. isoItems.push(this.buildLocalIsoItem(fullPath, name))
  2293. }
  2294. Utility.doSortListAscending(isoItems)
  2295. return isoItems
  2296. }
  2297. private filterOutLocalIsoItems(items: Array<VideoItem>): Array<VideoItem> {
  2298. return items.filter(item => !this.isIsoLocalFile(item))
  2299. }
  2300. private isSelectableLocalItem(item: VideoItem): boolean {
  2301. if (!item) {
  2302. return false
  2303. }
  2304. if (item.type === CommonConstants.TYPE_LOCAL) {
  2305. return true
  2306. }
  2307. if (item.type === CommonConstants.TYPE_IS_DIR) {
  2308. return !this.isProtectedLocalDirectory(item)
  2309. }
  2310. return false
  2311. }
  2312. private isLocalItemSelected(item: VideoItem): boolean {
  2313. return this.selectedFiles.some(x => x.filePath === item.filePath)
  2314. }
  2315. private hasSelectedDirectories(): boolean {
  2316. return this.selectedFiles.some(item => item.type === CommonConstants.TYPE_IS_DIR)
  2317. }
  2318. private getSelectedPlayableFiles(): Array<VideoItem> {
  2319. return this.selectedFiles.filter(item => item.type === CommonConstants.TYPE_LOCAL && !this.isIsoLocalFile(item))
  2320. }
  2321. private syncLocalSelectionState(): void {
  2322. const selectableItems = this.getCurFileList()
  2323. const selectableKeys: Set<string> = new Set(selectableItems.map(item => item.filePath))
  2324. const nextSelected = this.selectedFiles.filter(item => selectableKeys.has(item.filePath))
  2325. if (nextSelected.length !== this.selectedFiles.length) {
  2326. this.selectedFiles = [...nextSelected]
  2327. }
  2328. this.isAllSelected = nextSelected.length > 0 && nextSelected.length === selectableItems.length
  2329. }
  2330. private enterLocalMultiSelect(item: VideoItem): void {
  2331. if (!this.isSelectableLocalItem(item)) {
  2332. return
  2333. }
  2334. if (!this.isMultiSelect) {
  2335. this.isMultiSelect = true
  2336. }
  2337. if (!this.isLocalItemSelected(item)) {
  2338. this.selectedFiles = [...this.selectedFiles, item]
  2339. }
  2340. this.syncLocalSelectionState()
  2341. }
  2342. private selectSingleItemForDelete(item: VideoItem): void {
  2343. if (!this.isSelectableLocalItem(item)) {
  2344. return
  2345. }
  2346. this.selectedFiles = [item]
  2347. this.isAllSelected = false
  2348. }
  2349. setButtonStatus() {
  2350. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2351. this.isZero = false
  2352. } else {
  2353. this.isZero = true
  2354. }
  2355. if (this.currentPath !== this.rootPath &&
  2356. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  2357. this.isHasDir = true //不为空,说明有子文件夹
  2358. } else {
  2359. this.isHasDir = false
  2360. }
  2361. }
  2362. private getPlayListDisplayCount(): number {
  2363. if (this.playQueueScope === 'history') {
  2364. return this.historyList.length;
  2365. }
  2366. if (this.playQueueScope === 'fav') {
  2367. return this.favList.length;
  2368. }
  2369. if (this.playQueueScope === 'playlist') {
  2370. // 检测是否是流媒体播放(Navidrome/Jellyfin/Emby/AudioStation/Plex/道理鱼等)
  2371. // 如果是,优先返回服务端总数
  2372. const navidromeTotalCount = getNavidromeTotalCount();
  2373. Logger.info('heanup getPlayListDisplayCount', `playQueueScope=playlist, navidromeTotalCount=${navidromeTotalCount}, currentSong=${this.currentSong?.name}, type=${this.currentSong?.type}`);
  2374. if (navidromeTotalCount > 0 && this.currentSong && (
  2375. isNavidromeType(this.currentSong.type) ||
  2376. isJellyfinType(this.currentSong.type) ||
  2377. isEmbyType(this.currentSong.type) ||
  2378. isAudioStationType(this.currentSong.type) ||
  2379. isPlexType(this.currentSong.type) ||
  2380. isDaoLiYuType(this.currentSong.type)
  2381. )) {
  2382. Logger.info('heanup getPlayListDisplayCount', `返回服务端总数: ${navidromeTotalCount}`);
  2383. return navidromeTotalCount;
  2384. }
  2385. Logger.info('heanup getPlayListDisplayCount', `返回 currentSongList.length: ${this.currentSongList.length}`);
  2386. return this.currentSongList.length;
  2387. }
  2388. if (this.playQueueScope === 'view' && this.modeType === 1 && this.totalCount > 0) {
  2389. return this.totalCount;
  2390. }
  2391. Logger.info('heanup getPlayListDisplayCount', `返回 songList.length: ${this.songList.length}, playQueueScope=${this.playQueueScope}`);
  2392. return this.songList.length;
  2393. }
  2394. private restoreLastPlayContext(): void {
  2395. const scope = PreferencesUtil.getStringSync('LastPlayQueueScope', 'view') as string;
  2396. if (scope === 'history' || scope === 'fav' || scope === 'playlist' || scope === 'single') {
  2397. this.playQueueScope = scope;
  2398. } else {
  2399. this.playQueueScope = 'view';
  2400. }
  2401. const lastModeType = PreferencesUtil.getNumberSync('LastPlayModeType', this.modeType);
  2402. const lastTotalCount = PreferencesUtil.getNumberSync('LastPlayTotalCount', 0);
  2403. if (lastModeType === 1 && this.totalCount === 0 && lastTotalCount > 0) {
  2404. this.totalCount = lastTotalCount;
  2405. }
  2406. }
  2407. private async hydrateFullMediaPlayListIfNeeded(isSonList:boolean = true): Promise<void> {
  2408. if (this.isHydratingPlayList) {
  2409. return;
  2410. }
  2411. if (this.playQueueScope !== 'view' || this.modeType !== 1) {
  2412. return;
  2413. }
  2414. if (this.totalCount === 0 || this.songList.length >= this.totalCount) {
  2415. return;
  2416. }
  2417. this.isHydratingPlayList = true;
  2418. try {
  2419. const fullList: VideoItem[] = [];
  2420. let pageIndex = 0;
  2421. let hasMore = true;
  2422. while (hasMore) {
  2423. const result = await this.table.queryMediaLibraryPaged({
  2424. pageIndex,
  2425. pageSize: this.pageSize,
  2426. sortType: this.sortType,
  2427. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  2428. isShowFileName: this.isShowFileName
  2429. });
  2430. if (result.items.length === 0) {
  2431. break;
  2432. }
  2433. fullList.push(...result.items);
  2434. hasMore = result.hasMore;
  2435. pageIndex += 1;
  2436. if (fullList.length >= result.totalCount) {
  2437. hasMore = false;
  2438. }
  2439. }
  2440. if (fullList.length > 0) {
  2441. if(isSonList){
  2442. this.songList = fullList;
  2443. this.sonDataSource.pushArrayData(this.songList);
  2444. }else{
  2445. this.videoLocalList = fullList;
  2446. this.dataSource.pushArrayData(this.videoLocalList);
  2447. }
  2448. }
  2449. } finally {
  2450. this.isHydratingPlayList = false;
  2451. }
  2452. }
  2453. @Builder
  2454. SortMenuBuilder() {
  2455. Menu() {
  2456. MenuItem({
  2457. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.person')),
  2458. content: "按艺术家",
  2459. builder: this.SubSortBuilder(SortMode.ByArtist),
  2460. symbolEndIcon: this.isSortTypeInRange(SortMode.ByArtist) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2461. })
  2462. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByArtist)))
  2463. MenuItem({
  2464. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat_size_square')),
  2465. content: "按专辑",
  2466. builder: this.SubSortBuilder(SortMode.ByAlbum),
  2467. symbolEndIcon: this.isSortTypeInRange(SortMode.ByAlbum) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2468. })
  2469. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByAlbum)))
  2470. MenuItem({
  2471. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat')),
  2472. content: "按名称",
  2473. builder: this.SubSortBuilder(SortMode.ByName),
  2474. symbolEndIcon: this.isSortTypeInRange(SortMode.ByName) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2475. })
  2476. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByName)))
  2477. MenuItem({
  2478. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2479. content: $r('app.string.sort_by_time'),
  2480. builder: this.SubSortBuilder(SortMode.ByTime),
  2481. symbolEndIcon: this.isSortTypeInRange(SortMode.ByTime) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2482. })
  2483. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByTime)))
  2484. MenuItem({
  2485. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  2486. content: '按碟片音轨号',
  2487. builder: this.SubSortBuilder(SortMode.ByDiscTrack),
  2488. symbolEndIcon: this.isSortTypeInRange(SortMode.ByDiscTrack) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2489. })
  2490. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByDiscTrack)))
  2491. .visibility((this.modeType==0||(this.modeType==2&&this.isCanBack)||
  2492. (this.modeType==3&&this.isCanBack))?Visibility.Visible:Visibility.None)
  2493. }.attributeModifier(new MenuModifier())
  2494. }
  2495. @Builder
  2496. SortMenuForArtistAblumBuilder() {
  2497. Menu() {
  2498. MenuItem({
  2499. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat')),
  2500. content: "按名称",
  2501. builder: this.SubSortBuilder(SortMode.ByName),
  2502. symbolEndIcon: this.isSortTypeInRange(SortMode.ByName) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2503. })
  2504. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByName)))
  2505. MenuItem({
  2506. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2507. content: '按数量',
  2508. builder: this.SubSortBuilder(SortMode.ByCount),
  2509. symbolEndIcon: this.isSortTypeInRange(SortMode.ByCount) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2510. })
  2511. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByCount)))
  2512. }.attributeModifier(new MenuModifier())
  2513. }
  2514. @Builder SubSortBuilder(sortType: number){
  2515. Menu(){
  2516. MenuItem({
  2517. content: "升序",
  2518. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_up')),
  2519. symbolEndIcon: this.sortType === sortType ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2520. })
  2521. .backgroundColor(this.getSortOrderItemBackground(this.sortType === sortType, true))
  2522. .onClick(async () => {
  2523. await this.doSortType(sortType)
  2524. })
  2525. MenuItem({
  2526. content: "降序",
  2527. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_down')),
  2528. symbolEndIcon: this.sortType === sortType + 1 ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2529. })
  2530. .backgroundColor(this.getSortOrderItemBackground(this.sortType === sortType + 1, false))
  2531. .onClick(async () => {
  2532. await this.doSortType(sortType + 1) // 降序的sortType = 升序的sortType + 1
  2533. })
  2534. }
  2535. }
  2536. async doSortType(index: number): Promise<void> {
  2537. Logger.info('heanup LocalMusic', `doSortType: 切换排序方式 sortType=${index}, mode=${this.modeType}, isCanBack=${this.isCanBack}`);
  2538. this.sortType = index;
  2539. this.saveSortTypeForCurrentMode(index);
  2540. // 详情页模式(modeType=2/3 且 isCanBack=true): 重新查询当前项目的歌曲
  2541. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  2542. await this.reloadCurrentDetailSongs();
  2543. } else {
  2544. // 分页模式下,排序需要重新从数据库查询
  2545. await this.resetAndLoadFirstPage();
  2546. }
  2547. }
  2548. /**
  2549. * 重新加载当前详情页(专辑/艺术家)的歌曲数据
  2550. * 用于详情页切换排序方式时重新查询并排序
  2551. */
  2552. private async reloadCurrentDetailSongs(): Promise<void> {
  2553. Logger.info('heanup LocalMusic', `reloadCurrentDetailSongs: modeType=${this.modeType}, titleName=${this.titleName}, sortType=${this.sortType}`);
  2554. try {
  2555. if (this.modeType === 2) {
  2556. // 艺术家详情页: 重新查询该艺术家的歌曲
  2557. const mList = await this.table.querySongsByArtist(this.titleName, this.sortType, this.isShowFileName);
  2558. if (ArrayUtil.isNotEmpty(mList)) {
  2559. // 使用带排序类型的缓存键
  2560. const cacheKey = `${this.titleName}_sort_${this.sortType}`;
  2561. this.artistMap.set(cacheKey, mList);
  2562. this.totalCount = mList.length;
  2563. // 使用 noSort=true 避免在 updateListData 中重新排序导致死循环
  2564. this.updateListData(mList, true);
  2565. Logger.info('heanup LocalMusic', `reloadCurrentDetailSongs: 艺术家详情页重新加载完成, 歌曲数=${mList.length}`);
  2566. }
  2567. } else if (this.modeType === 3) {
  2568. // 专辑详情页: 重新查询该专辑的歌曲
  2569. const albumList = await this.table.querySongsByAlbum(this.titleName, this.sortType, this.isShowFileName);
  2570. if (ArrayUtil.isNotEmpty(albumList)) {
  2571. // 使用带排序类型的缓存键
  2572. const cacheKey = `${this.titleName}_sort_${this.sortType}`;
  2573. this.albumMap.set(cacheKey, albumList);
  2574. this.totalCount = albumList.length;
  2575. // 使用 noSort=true 避免在 updateListData 中重新排序导致死循环
  2576. this.updateListData(albumList, true);
  2577. Logger.info('heanup LocalMusic', `reloadCurrentDetailSongs: 专辑详情页重新加载完成, 歌曲数=${albumList.length}`);
  2578. }
  2579. }
  2580. } catch (err) {
  2581. const error = err as Error;
  2582. Logger.error('heanup LocalMusic', `reloadCurrentDetailSongs error: ${error.message}`);
  2583. ToastUtil.showToast('重新加载数据失败');
  2584. }
  2585. }
  2586. /**
  2587. * 根据当前模式保存排序类型到不同的存储键
  2588. * 区分列表页和详情页的排序设置
  2589. */
  2590. private saveSortTypeForCurrentMode(sortType: number): void {
  2591. let storageKey = SettingPage.SORT_TYPE;
  2592. if (this.modeType === 2) {
  2593. // 艺术家模式
  2594. if (this.isCanBack) {
  2595. storageKey = 'SORT_TYPE_ARTIST_DETAIL'; // 艺术家详情页排序
  2596. } else {
  2597. storageKey = 'SORT_TYPE_ARTIST'; // 艺术家列表页排序
  2598. }
  2599. } else if (this.modeType === 3) {
  2600. // 专辑模式
  2601. if (this.isCanBack) {
  2602. storageKey = 'SORT_TYPE_ALBUM_DETAIL'; // 专辑详情页排序
  2603. } else {
  2604. storageKey = 'SORT_TYPE_ALBUM'; // 专辑列表页排序
  2605. }
  2606. } else {
  2607. storageKey = SettingPage.SORT_TYPE;
  2608. }
  2609. PreferencesUtil.putSync(storageKey, sortType);
  2610. Logger.info('heanup LocalMusic', `saveSortTypeForCurrentMode: mode=${this.modeType}, isCanBack=${this.isCanBack}, sortType=${sortType}, key=${storageKey}`);
  2611. }
  2612. /**
  2613. * 根据当前模式加载排序类型
  2614. * 区分列表页和详情页的排序设置
  2615. */
  2616. private loadSortTypeForCurrentMode(): number {
  2617. let storageKey = SettingPage.SORT_TYPE;
  2618. let defaultSortType = 4;
  2619. if (this.modeType === 2) {
  2620. // 艺术家模式
  2621. if (this.isCanBack) {
  2622. storageKey = 'SORT_TYPE_ARTIST_DETAIL'; // 艺术家详情页排序
  2623. defaultSortType = 4; // 详情页默认按名称升序
  2624. } else {
  2625. storageKey = 'SORT_TYPE_ARTIST'; // 艺术家列表页排序
  2626. defaultSortType = 9; // 列表页默认按数量降序
  2627. }
  2628. } else if (this.modeType === 3) {
  2629. // 专辑模式
  2630. if (this.isCanBack) {
  2631. storageKey = 'SORT_TYPE_ALBUM_DETAIL'; // 专辑详情页排序
  2632. defaultSortType = 4; // 详情页默认按名称升序
  2633. } else {
  2634. storageKey = 'SORT_TYPE_ALBUM'; // 专辑列表页排序
  2635. defaultSortType = 9; // 列表页默认按数量降序
  2636. }
  2637. }
  2638. return PreferencesUtil.getNumberSync(storageKey, defaultSortType);
  2639. }
  2640. /**
  2641. * 检查当前sortType是否在指定排序类型的范围内
  2642. * 用于判断是否显示打勾图标
  2643. * @param baseSortType 基础排序类型(升序的值)
  2644. * @returns 如果当前sortType是该排序类型的升序或降序,返回true
  2645. */
  2646. private isSortTypeInRange(baseSortType: number): boolean {
  2647. return this.sortType === baseSortType || this.sortType === baseSortType + 1;
  2648. }
  2649. private getSortModeItemBackground(isSelected: boolean): ResourceColor {
  2650. if (!isSelected) {
  2651. return Color.Transparent;
  2652. }
  2653. return this.isDarkMode ? '#334967' : '#EAF2FF';
  2654. }
  2655. private getSortOrderItemBackground(isSelected: boolean, isAsc: boolean): ResourceColor {
  2656. if (!isSelected) {
  2657. return Color.Transparent;
  2658. }
  2659. if (isAsc) {
  2660. return this.isDarkMode ? '#295B8A' : '#DCEEFF';
  2661. }
  2662. return this.isDarkMode ? '#7A4D22' : '#FFE9D5';
  2663. }
  2664. showSheelDialog() {
  2665. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  2666. // this.showTips()
  2667. // return
  2668. // }
  2669. this.showAddDialog()
  2670. }
  2671. showAddDialog() {
  2672. if (this.modeType === 2 || this.modeType === 3) {
  2673. return
  2674. }
  2675. DialogHelper.showActionSheetDialog({
  2676. title: "请选择添加方式(建议歌词文件一起导入)",
  2677. sheets: [
  2678. { value: "新建文件夹", fontColor: $r('app.color.text_color') },
  2679. { value: "手动导入", fontColor: $r('app.color.text_color') },
  2680. { value: "自动导入", fontColor: $r('app.color.text_color') },
  2681. { value: "全选导入", fontColor: $r('app.color.text_color') },
  2682. ],
  2683. maskColor: Color.Transparent,
  2684. backgroundColor: $r('app.color.bg_card'),
  2685. transition: AnimationHelper.transitionInDown(555),
  2686. onAction: (index) => {
  2687. switch (index) {
  2688. case 0:
  2689. if (this.modeType === 0) {
  2690. this.showMkDialog()
  2691. } else {
  2692. ToastUtil.showToast('请切换到首页才能新建文件夹!')
  2693. }
  2694. break;
  2695. case 1:
  2696. this.callFilePickerSelectFile()
  2697. break;
  2698. case 2:
  2699. this.showTips()
  2700. break;
  2701. case 3:
  2702. this.goSelectMusic()
  2703. break;
  2704. }
  2705. }
  2706. })
  2707. }
  2708. //拉起音频
  2709. goSelectMusic() {
  2710. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  2711. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  2712. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  2713. ) {
  2714. ToastUtil.showToast('暂时不支持该设备')
  2715. return
  2716. }
  2717. try {
  2718. let documentSelectOptions = new picker.DocumentSelectOptions();
  2719. documentSelectOptions.authMode = true
  2720. documentSelectOptions.multiAuthMode = true
  2721. if( deviceInfo.sdkApiVersion>=21){//如果api大于21 ,可以支持1w首歌以上
  2722. documentSelectOptions.maxSelectNumber = 20000
  2723. }
  2724. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  2725. let documentPicker = new picker.DocumentViewPicker(this.context);
  2726. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  2727. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  2728. this.saveVideoDatas(documentSelectResult)
  2729. }
  2730. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  2731. JSON.stringify(documentSelectResult));
  2732. }).catch((err: BusinessError) => {
  2733. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  2734. });
  2735. } catch (error) {
  2736. let err: BusinessError = error as BusinessError;
  2737. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2738. }
  2739. }
  2740. async showTips() {
  2741. try {
  2742. this.getUIContext().getPromptAction().showDialog({
  2743. title: '导入指南',
  2744. message:'用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  2745. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  2746. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  2747. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后去文件扫描一下。\n',
  2748. buttons: [
  2749. {
  2750. text: '知道了',
  2751. color: '#000000'
  2752. },
  2753. ]
  2754. }, (err, data) => {
  2755. if (err) {
  2756. console.error('showDialog err: ' + err);
  2757. return;
  2758. }
  2759. console.info('showDialog success callback, click button: ' + data.index);
  2760. });
  2761. } catch (error) {
  2762. let message = (error as BusinessError).message;
  2763. let code = (error as BusinessError).code;
  2764. console.error(`showDialog args error code is ${code}, message is ${message}`);
  2765. };
  2766. }
  2767. showMkDialog() {
  2768. DialogHelper.showTextInputDialog({
  2769. title: '新建歌单',
  2770. maskColor: Color.Transparent,
  2771. text: '',
  2772. transition: AnimationHelper.transitionInDown(666),
  2773. onChange: (text) => {
  2774. console.error("onChange: " + text);
  2775. },
  2776. onAction: (action, dialogId, content) => {
  2777. // ToastUtil.showToast('content = ' +content)
  2778. if (action == DialogAction.TWO) {
  2779. const newName = content
  2780. const newPath = this.currentPath + '/' + newName
  2781. FileUtil.mkdir(newPath, true).then(() => {
  2782. this.cache.delete(this.currentPath); // 删除目标路径缓存
  2783. this.getSortedFiles(this.currentPath)
  2784. }).catch((error: BusinessError) => {
  2785. console.error(error.message);
  2786. });
  2787. }
  2788. }
  2789. })
  2790. }
  2791. @State progress: number = 0;
  2792. async saveVideoDatas(uris:string[],isOpen?:boolean){
  2793. if (ArrayUtil.isEmpty(uris)) {
  2794. return;
  2795. }
  2796. console.info('onecold this.isCopyFileToDownLoad = ' + this.isCopyFileToDownLoad);
  2797. if(this.isCopyFileToDownLoad||this.currentPath==this.lockPath||isOpen){
  2798. this.saveVideoDatasToDownLoad(uris,isOpen)
  2799. return
  2800. }
  2801. // 初始化进度条
  2802. this.progress = 0;
  2803. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  2804. progress: this.progress,
  2805. backCancel: false,
  2806. autoCancel: false,
  2807. loadColor: $r('app.color.title_bar_bg'),
  2808. fontColor: $r('app.color.title_bar_bg')
  2809. });
  2810. // 计算处理总数用于进度计算
  2811. const totalItems = uris.length;
  2812. let processedItems = 0;
  2813. for (let i = 0; i < uris.length; i++) {
  2814. let filePath = uris[i];
  2815. try {
  2816. if (this.currentPath !== this.lockPath) { // 判断不是私密音乐,才入库
  2817. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2818. let mediaItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context,
  2819. filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2820. console.info('onecold saveVideoDatas filePath = ' + filePath)
  2821. if (!filePath.includes(this.rootPath)) {
  2822. console.info('onecold saveVideoDatas mediaItem.parentPath111 = ' + mediaItem.parentPath)
  2823. mediaItem.parentPath = this.currentPath;
  2824. }
  2825. console.info('onecold saveVideoDatas mediaItem.parentPath = ' + mediaItem.parentPath)
  2826. this.table.insert(mediaItem, (id: number) => {
  2827. // 插入完成回调
  2828. });
  2829. }
  2830. }
  2831. // 更新进度
  2832. processedItems++;
  2833. this.progress = Math.floor((processedItems / totalItems) * 100);
  2834. DialogHelper.updateLoading(this.loadingProgressDialogId,` 正在处理 ${this.progress}%`, this.progress);
  2835. } catch (error) {
  2836. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2837. // 即使出错也更新进度
  2838. processedItems++;
  2839. this.progress = Math.floor((processedItems / totalItems) * 100);
  2840. DialogHelper.updateLoading(this.loadingProgressDialogId,` 正在处理 ${this.progress}%`, this.progress);
  2841. }
  2842. }
  2843. // 关闭进度条
  2844. DialogHelper.closeDialog(this.loadingProgressDialogId)
  2845. this.isZero = false
  2846. // 删除目标路径缓存
  2847. setTimeout(() => {
  2848. this.cache.delete(this.currentPath);
  2849. this.getSortedFiles(this.currentPath,false,uris[0],isOpen)
  2850. this.setButtonStatus()
  2851. }, 500);
  2852. }
  2853. async saveVideoDatasToDownLoad(uris: string[], isOpen?: boolean) {
  2854. if (ArrayUtil.isEmpty(uris)) {
  2855. return;
  2856. }
  2857. let newUris: string[] = [];
  2858. this.progress = 0
  2859. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  2860. progress: this.progress,
  2861. backCancel: false,
  2862. autoCancel: false,
  2863. loadColor: this.themeColor,
  2864. fontColor: this.themeColor
  2865. });
  2866. // 计算所有文件的总大小
  2867. let totalSize = 0;
  2868. for (let uri of uris) {
  2869. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  2870. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  2871. await fileIo.close(sourceFile.fd);
  2872. }
  2873. let totalRead = 0;
  2874. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  2875. Logger.info(TAG, 'destPath uri: ' + destPath);
  2876. for (let i = 0; i < uris.length; i++) {
  2877. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  2878. Logger.info(TAG, 'filePath uri: ' + filePath);
  2879. newUris.push(filePath);
  2880. try {
  2881. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  2882. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  2883. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  2884. const buffer = new ArrayBuffer(buffSize);
  2885. let len = await fileIo.read(sourceFile.fd, buffer);
  2886. while (len > 0) {
  2887. await fileIo.write(destFile.fd, buffer.slice(0, len));
  2888. totalRead += len;
  2889. // 计算总进度
  2890. this.progress = Math.floor((totalRead / totalSize) * 100);
  2891. DialogHelper.updateLoading( this.loadingProgressDialogId,`正在导入 ${this.progress}%`, this.progress);
  2892. len = await fileIo.read(sourceFile.fd, buffer);
  2893. }
  2894. await fileIo.close(sourceFile.fd);
  2895. await fileIo.close(destFile.fd);
  2896. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  2897. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2898. let mediaItem: VideoItem =
  2899. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2900. this.table.insert(mediaItem, (id: number) => {
  2901. // 删除目标路径缓存
  2902. this.cache.delete(this.currentPath);
  2903. this.getSortedFiles(this.currentPath, true, destPath, isOpen,mediaItem)
  2904. });
  2905. }
  2906. }
  2907. } catch (error) {
  2908. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2909. }
  2910. }
  2911. DialogHelper.closeDialog(this.loadingProgressDialogId);
  2912. this.isZero = false
  2913. Logger.info(TAG, 'scan select video result:' + newUris)
  2914. }
  2915. //拉起音频
  2916. // goSelectMusic(){
  2917. //
  2918. // try {
  2919. // let audioSelectOptions = new picker.AudioSelectOptions();
  2920. // let audioPicker = new picker.AudioViewPicker(this.context);
  2921. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  2922. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  2923. // this.saveVideoDatas(audioSelectResult)
  2924. // }
  2925. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  2926. // }).catch((err: BusinessError) => {
  2927. //
  2928. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  2929. // });
  2930. // } catch (error) {
  2931. // let err: BusinessError = error as BusinessError;
  2932. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2933. // }
  2934. //
  2935. //
  2936. //
  2937. // }
  2938. async goSelectImage(item: VideoItem): Promise<string | undefined> {
  2939. if (!item) {
  2940. return undefined;
  2941. }
  2942. try {
  2943. let selectUris: Array<string> = [];
  2944. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  2945. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  2946. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  2947. photoSelectOptions.maxSelectNumber = 1;
  2948. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  2949. selectUris = photoSelectResult.photoUris;
  2950. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  2951. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  2952. console.info('file fd: ' + file.fd);
  2953. let name = await MD5.digestSync(this.videoUrl)+'.jpg'
  2954. let imagePath = this.context.filesDir + FileUtil.separator + name
  2955. imagePath = fileUri.getUriFromPath(imagePath)
  2956. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  2957. fileIo.copyFileSync(file.fd, file2.fd)
  2958. fileIo.closeSync(file);
  2959. fileIo.closeSync(file2);
  2960. if (item.filePath == this.currentSong?.filePath) {
  2961. this.cover = imagePath
  2962. if (this.currentSong) {
  2963. this.currentSong.isCustomCover = 1;
  2964. }
  2965. }
  2966. if (item) {
  2967. item.pixelMapPath = imagePath
  2968. item.isCustomCover = 1;
  2969. }
  2970. if (isRemoteCloudType(item.type)) {
  2971. return FileUtil.getFilePath(imagePath);
  2972. }
  2973. this.table.updateCustomCoverPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  2974. if (success) {
  2975. this.doUpdateData()
  2976. console.log("onecold 更新音乐封面成功,数据库已同步");
  2977. } else {
  2978. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  2979. }
  2980. });
  2981. LogUtil.debug("onecold this.cover =" + this.cover)
  2982. return FileUtil.getFilePath(imagePath); // Return the image path here
  2983. } catch (err) {
  2984. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  2985. return undefined;
  2986. }
  2987. }
  2988. private async pickCoverImageToSandbox(): Promise<string | undefined> {
  2989. try {
  2990. const photoPicker = new photoAccessHelper.PhotoViewPicker();
  2991. const photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  2992. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  2993. photoSelectOptions.maxSelectNumber = 1;
  2994. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  2995. const selectUris = photoSelectResult.photoUris;
  2996. if (!selectUris || selectUris.length === 0) {
  2997. return undefined;
  2998. }
  2999. const coverDir = this.context.filesDir + FileUtil.separator + 'ttmusic_cover';
  3000. if (!FileUtil.accessSync(coverDir)) {
  3001. FileUtil.mkdirSync(coverDir);
  3002. }
  3003. const sourceUri = selectUris[0];
  3004. const sourceName = FileUtil.getFileName(sourceUri) || '';
  3005. let suffix = '.jpg';
  3006. const dotIndex = sourceName.lastIndexOf('.');
  3007. if (dotIndex >= 0) {
  3008. suffix = sourceName.substring(dotIndex);
  3009. }
  3010. const targetName = `${Date.now()}_${await MD5.digestSync(sourceUri)}${suffix}`;
  3011. const targetPath = coverDir + FileUtil.separator + targetName;
  3012. const sourceFile = fileIo.openSync(sourceUri, fileIo.OpenMode.READ_ONLY);
  3013. const targetFile = fileIo.openSync(targetPath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
  3014. fileIo.copyFileSync(sourceFile.fd, targetFile.fd);
  3015. fileIo.closeSync(sourceFile.fd);
  3016. fileIo.closeSync(targetFile.fd);
  3017. return fileUri.getUriFromPath(targetPath);
  3018. } catch (error) {
  3019. const err = error as BusinessError;
  3020. Logger.error(TAG, `pickCoverImageToSandbox failed, code: ${err.code}, message: ${err.message}`);
  3021. return undefined;
  3022. }
  3023. }
  3024. private async replaceCurrentSongCoverByAlbum(): Promise<void> {
  3025. if (!this.currentSong || StrUtil.isEmpty(this.currentSong.filePath)) {
  3026. ToastUtil.showToast('当前歌曲无效');
  3027. return;
  3028. }
  3029. const sandboxCoverUri = await this.pickCoverImageToSandbox();
  3030. if (StrUtil.isEmpty(sandboxCoverUri)) {
  3031. return;
  3032. }
  3033. const coverUri = sandboxCoverUri as string;
  3034. this.loadingDialogId = DialogHelper.showLoadingDialog();
  3035. try {
  3036. if (isRemoteCloudType(this.currentSong.type)) {
  3037. this.cover = coverUri;
  3038. this.currentSong.pixelMapPath = coverUri;
  3039. this.currentSong.isCustomCover = 1;
  3040. this.syncRemoteManagerSong(this.currentSong);
  3041. await this.persistRemoteMetadataToDb(this.currentSong);
  3042. this.emitRemoteMetadataUpdated(this.currentSong);
  3043. this.currentSong = cloneVideoItem(this.currentSong);
  3044. AppStorage.setOrCreate('currentSong', this.currentSong);
  3045. ToastUtil.showToast('更换封面成功');
  3046. return;
  3047. }
  3048. if (this.currentSong.type !== CommonConstants.TYPE_LOCAL) {
  3049. ToastUtil.showToast('当前歌曲类型暂不支持更换封面');
  3050. return;
  3051. }
  3052. const task = new taskpool.Task(
  3053. replaceLocalMusicCoverTask,
  3054. this.context,
  3055. this.currentSong.filePath,
  3056. FileUtil.getFilePath(coverUri)
  3057. );
  3058. const result = await taskpool.execute(task, taskpool.Priority.HIGH) as boolean;
  3059. if (!result) {
  3060. ToastUtil.showToast('更换封面失败');
  3061. return;
  3062. }
  3063. this.cover = coverUri;
  3064. this.currentSong.pixelMapPath = coverUri;
  3065. this.currentSong.isCustomCover = 1;
  3066. await this.doUpateEditedFields(this.currentSong);
  3067. ToastUtil.showToast('更换封面成功');
  3068. } catch (error) {
  3069. Logger.error(TAG, `replaceCurrentSongCoverByAlbum failed: ${JSON.stringify(error)}`);
  3070. ToastUtil.showToast('更换封面失败');
  3071. } finally {
  3072. DialogHelper.closeDialog(this.loadingDialogId);
  3073. }
  3074. }
  3075. // 拉起picker选择文件管理器
  3076. async callFilePickerSelectFile(): Promise<void> {
  3077. try {
  3078. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  3079. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  3080. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  3081. } else {
  3082. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  3083. }
  3084. let documentPicker = new picker.DocumentViewPicker();
  3085. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  3086. Logger.info(TAG,
  3087. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  3088. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  3089. this.saveVideoDatas(DocumentSelectResult)
  3090. }
  3091. }).catch((err: BusinessError) => {
  3092. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  3093. });
  3094. } catch (err) {
  3095. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  3096. }
  3097. }
  3098. //重命名的对话框
  3099. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  3100. if(!item.filePath.includes(this.packName)){
  3101. ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限重命名')
  3102. return
  3103. }
  3104. DialogHelper.showTextInputDialog({
  3105. title: '重命名',
  3106. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : (item.fileName || item.name),
  3107. maskColor: Color.Transparent,
  3108. backgroundColor: Color.Grey,
  3109. transition: AnimationHelper.transitionInDown(666),
  3110. onChange: (text) => {
  3111. console.error("onChange: " + text);
  3112. },
  3113. onAction: (action, dialogId, content) => {
  3114. // ToastUtil.showToast('content = ' +content)
  3115. if (action == DialogAction.TWO) {
  3116. const newName = content
  3117. const newPath = this.currentPath + '/' + newName
  3118. console.log("onecold item = " + item.type);
  3119. this.doReName(index, newName, filePath, newPath, item)
  3120. }
  3121. }
  3122. })
  3123. }
  3124. //剪切 移动到另个文件夹的对话框
  3125. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  3126. Logger.info('onecold showCutDialog')
  3127. let mList: Array<string> = []
  3128. let rPath = this.rootPath
  3129. if (isCurrent) {
  3130. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  3131. rPath = this.currentPath
  3132. } else {
  3133. mList = Utility.getNameList(this.dirList);
  3134. rPath = this.rootPath
  3135. }
  3136. let dataBean = new BubbleBean()
  3137. dataBean.data = mList
  3138. dataBean.color = this.themeColor
  3139. dataBean.onItemClick = (i) => {
  3140. const targetName = item.fileName || item.name
  3141. const newPath = rPath + '/' + mList[i] + '/' + targetName
  3142. Logger.info('newPath = ' + newPath)
  3143. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  3144. ToastUtil.showToast('移动成功')
  3145. this.table.deleteData(item, () => {
  3146. });
  3147. if (!Utility.isIsoByExtension(newPath)) {
  3148. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  3149. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3150. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  3151. this.table.insert(newItem, (id: number) => {
  3152. //加入数据库
  3153. });
  3154. }
  3155. }
  3156. this.cache.delete(this.currentPath); // 删除原路径缓存
  3157. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  3158. this.getSortedFiles(this.currentPath, true)
  3159. }).catch((error: BusinessError) => {
  3160. console.error(error.message);
  3161. });
  3162. XPopup.dismissTop()
  3163. }
  3164. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  3165. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  3166. popupPosition = PopupPosition.TOP
  3167. }
  3168. if (index <= 3) {
  3169. popupPosition = PopupPosition.BOTTOM
  3170. }
  3171. let pup: XPopup
  3172. if (this.isDarkMode) {
  3173. pup = XPopup.Builder()
  3174. .setPopupPosition(popupPosition)
  3175. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  3176. .setBackgroundColor(Color.Black)
  3177. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3178. .show()
  3179. } else {
  3180. pup = XPopup.Builder()
  3181. .setPopupPosition(popupPosition)
  3182. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  3183. .setBackgroundColor(Color.White)
  3184. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3185. .show()
  3186. }
  3187. }
  3188. //复制 到另个文件夹的对话框
  3189. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  3190. Logger.info('onecoldv showCopyDialog')
  3191. let mList: Array<string> = []
  3192. let rPath = this.rootPath
  3193. if (isCurrent) {
  3194. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  3195. rPath = this.currentPath
  3196. } else {
  3197. mList = Utility.getNameList(this.dirList);
  3198. rPath = this.rootPath
  3199. }
  3200. let dataBean = new BubbleBean()
  3201. dataBean.data = mList
  3202. dataBean.isCopy = true
  3203. dataBean.color = this.themeColor
  3204. dataBean.onItemClick = (i) => {
  3205. const targetName = item.fileName || item.name
  3206. const newPath = rPath + '/' + mList[i] + '/' + targetName
  3207. Logger.info('newPath = ' + newPath)
  3208. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  3209. ToastUtil.showToast('复制成功')
  3210. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  3211. this.getSortedFiles(this.currentPath)
  3212. if (!Utility.isIsoByExtension(newPath)) {
  3213. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  3214. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3215. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  3216. this.table.insert(newItem, (id: number) => {
  3217. //加入数据库
  3218. });
  3219. }
  3220. }
  3221. }).catch((error: BusinessError) => {
  3222. console.error(error.message);
  3223. });
  3224. XPopup.dismissTop()
  3225. }
  3226. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  3227. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  3228. popupPosition = PopupPosition.TOP
  3229. }
  3230. if (index <= 3) {
  3231. popupPosition = PopupPosition.BOTTOM
  3232. }
  3233. let pup: XPopup
  3234. if (this.isDarkMode) {
  3235. pup = XPopup.Builder()
  3236. .setPopupPosition(popupPosition)
  3237. .atView(id)
  3238. .setMaxHeight('60%')
  3239. .setBackgroundColor(Color.Black)
  3240. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3241. .show();
  3242. } else {
  3243. pup = XPopup.Builder()
  3244. .setPopupPosition(popupPosition)
  3245. .atView(id)
  3246. .setMaxHeight('60%')
  3247. .setBackgroundColor(Color.White)
  3248. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3249. .show();
  3250. }
  3251. }
  3252. //重命名索引index的视频
  3253. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  3254. FileUtil.rename(oldPath, newPath).then(async () => {
  3255. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  3256. let refreshedItem: VideoItem = info
  3257. if (info.type === CommonConstants.TYPE_IS_DIR) {
  3258. //如果是文件夹先删除源数据,再添加新数据
  3259. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  3260. if (success) {
  3261. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  3262. } else {
  3263. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  3264. }
  3265. });
  3266. this.scanDirectory(newPath)
  3267. refreshedItem = new VideoItem(newName, newName, newPath, CommonConstants.TYPE_IS_DIR, 0, '')
  3268. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  3269. if (Utility.isIsoByExtension(oldPath) || Utility.isIsoByExtension(newPath)) {
  3270. refreshedItem = this.buildLocalIsoItem(newPath, newName)
  3271. } else {
  3272. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  3273. if (success) {
  3274. console.log(" onecold 重命名成功,数据库已同步");
  3275. } else {
  3276. console.error(" onecold 重命名数据库失败原因: " + error);
  3277. }
  3278. });
  3279. refreshedItem =
  3280. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3281. }
  3282. } else {
  3283. return
  3284. }
  3285. this.videoLocalList[index] = refreshedItem;
  3286. }
  3287. this.cache.delete(this.currentPath)
  3288. this.cache.delete(oldPath)
  3289. this.cache.delete(newPath)
  3290. this.getSortedFiles(this.currentPath, true)
  3291. }).catch((error: BusinessError) => {
  3292. console.error(error.message);
  3293. });
  3294. }
  3295. build() {
  3296. Stack() {
  3297. this.ContentBuild()
  3298. Stack() {
  3299. Column()
  3300. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  3301. height: '95%',
  3302. dragBar: true,
  3303. showClose: true,
  3304. blurStyle: BlurStyle.Thin,
  3305. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3306. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  3307. title: {
  3308. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  3309. + `(${this.getPlayListDisplayCount()}首)`
  3310. }
  3311. })
  3312. }
  3313. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  3314. modalTransition:ModalTransition.DEFAULT,
  3315. onWillDisappear: () => {
  3316. this.setShowPlayFalse()
  3317. },
  3318. })
  3319. }
  3320. .alignContent(Alignment.Bottom)
  3321. .width('100%')
  3322. .height('100%')
  3323. }
  3324. @Builder
  3325. ContentBuild() {
  3326. Scroll() {
  3327. Column() {
  3328. Stack() {
  3329. //libraryname加上去后onKeyEvent监听不了,因为目前的解决方案是上面的XComponent,去掉libraryname
  3330. XComponent({ id: 'for_onKeyEvent',type: XComponentType.SURFACE,
  3331. controller: this.xcomponentController })
  3332. .onLoad(async (event?: object) => {
  3333. })
  3334. .focusable(true)
  3335. .height(0)
  3336. .focusOnTouch(true)
  3337. .defaultFocus(true) // 自动获取键盘焦点
  3338. .onKeyEvent((event?: KeyEvent) => {
  3339. console.info('onecold点击 onKeyEvent')
  3340. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  3341. if (!event || event.type !== KeyType.Down) {
  3342. return;
  3343. }
  3344. console.info('onecold点击 onKeyEvent event.keyCode: ' + event.keyCode)
  3345. //空格键 Space key controls pause/play
  3346. if (event.keyCode === KeyCode.KEYCODE_SPACE|| event.keyCode === KeyCode.KEYCODE_MEDIA_PLAY_PAUSE) {
  3347. this.playOrPause()
  3348. }
  3349. if (event.keyCode === KeyCode.KEYCODE_DPAD_UP) {
  3350. this.playPrevious()
  3351. }
  3352. if (event.keyCode === KeyCode.KEYCODE_DPAD_DOWN) {
  3353. this.playNext()
  3354. }
  3355. // Right-click to fast forward
  3356. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  3357. this.fastForward()
  3358. }
  3359. // Left-click to rewind
  3360. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  3361. this.backForward()
  3362. }
  3363. })
  3364. Column() {
  3365. XComponent({
  3366. id: 'xcomponentId',
  3367. type: 'surface',
  3368. libraryname: 'ijkplayer_napi',
  3369. controller: this.xcomponentController
  3370. })
  3371. .onLoad((event?: object) => {
  3372. if (!!event) {
  3373. this.initDelayPlay(event);
  3374. }
  3375. })
  3376. .onDestroy(() => {
  3377. })
  3378. .width('100%')// .width(this.videoWidth)
  3379. .aspectRatio(this.videoAspectRatio)
  3380. }
  3381. .aspectRatio(this.videoAspectRatio)
  3382. .justifyContent(FlexAlign.Center)
  3383. .backgroundColor(Color.Transparent)
  3384. .visibility(Visibility.Hidden)
  3385. .height(CommonConstants.FULL_PERCENT)
  3386. .width(CommonConstants.FULL_PERCENT)
  3387. .bindSheet($$this.isABSheet, this.ABLoopSheet(), {
  3388. height:this.isLandscape?'80%': '43%',
  3389. dragBar: true,
  3390. showClose: true,
  3391. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3392. blurStyle:BlurStyle.Thin,
  3393. backgroundColor:Color.Transparent,
  3394. title: { title: 'AB循环' }
  3395. })
  3396. Stack() {
  3397. Column() {
  3398. if(this.twoFingerType==4){
  3399. this.getWaterView()
  3400. }else{
  3401. if(this.isGridMusic){
  3402. this.getGridView()
  3403. }else {
  3404. this.getListView()
  3405. }
  3406. }
  3407. if (this.modeType ==0||this.modeType==4) {
  3408. Column() {
  3409. emptyView(this.themeColor)
  3410. }
  3411. .padding({ right:6 })
  3412. .onClick(()=>{
  3413. this.asyncCurrentPathOnlyFile()
  3414. })
  3415. .alignItems(HorizontalAlign.Center)
  3416. .position({ top: 200 })
  3417. .justifyContent(FlexAlign.Center)
  3418. .opacity(this.isZero ? 1 : 0)
  3419. .visibility(this.isZero&&!this.isLoadingPage && !this.isFavMusic && !this.isHistory
  3420. ? Visibility.Visible : Visibility.None)
  3421. .animation({
  3422. duration: 500,
  3423. curve: Curve.Friction // 可选动画曲线
  3424. })
  3425. .width('100%')
  3426. }
  3427. }
  3428. .layoutWeight(1)
  3429. .height('100%')
  3430. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  3431. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3432. .onDrop((event?: DragEvent) => {
  3433. try {
  3434. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3435. if (dragData !== undefined) {
  3436. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3437. if (records.length > 0) {
  3438. for (let i = 0; i < records.length; i++) {
  3439. let types = records[i].getTypes();
  3440. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3441. const fileUriUds =
  3442. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3443. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3444. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3445. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3446. this.targetFile = fileUriUds.oriUri;
  3447. this.saveVideoDatas([this.targetFile])
  3448. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3449. }
  3450. }
  3451. }
  3452. } else {
  3453. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3454. }
  3455. } else {
  3456. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3457. }
  3458. } catch (error) {
  3459. const err = error as BusinessError;
  3460. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3461. }
  3462. })
  3463. // 右侧居中的字母表索引
  3464. this.indexBuilder()
  3465. this.topTitleBar()
  3466. }
  3467. .alignContent(Alignment.Top)
  3468. .layoutWeight(1)
  3469. .height('100%')
  3470. Row() {
  3471. Button(this.isAllSelected ? '反选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  3472. .width(45)
  3473. .height(45)
  3474. .fontSize(10)
  3475. .margin({ top: 10, bottom: 10, right: 6 })
  3476. .backgroundColor(this.themeColor)
  3477. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3478. .onClick(() => {
  3479. if (this.isAllSelected) {
  3480. // 全不选
  3481. this.selectedFiles = [];
  3482. } else {
  3483. // 全选
  3484. this.selectedFiles = [...this.getCurFileList()];
  3485. }
  3486. this.syncLocalSelectionState();
  3487. })
  3488. Button('内嵌标签', { type: ButtonType.Capsule, stateEffect: true })
  3489. .width(72)
  3490. .height(45)
  3491. .fontSize(10)
  3492. .margin({ top: 10, bottom: 10, right: 6 })
  3493. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3494. .backgroundColor(this.themeColor)
  3495. .enabled(!this.hasSelectedDirectories() && this.getSelectedPlayableFiles().length > 0)
  3496. .bindContentCover($$this.isOneKeyTags, this.TagsContentCoverBuilder(), {
  3497. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3498. })
  3499. .onClick(() => {
  3500. if (this.hasSelectedDirectories()) {
  3501. ToastUtil.showToast('文件夹不支持批量内嵌标签')
  3502. return
  3503. }
  3504. this.isOneKeyTags = !this.isOneKeyTags
  3505. })
  3506. Button('合并', { type: ButtonType.Circle, stateEffect: true })
  3507. .width(45)
  3508. .height(45)
  3509. .fontSize(10)
  3510. .margin({ top: 10, bottom: 10, right: 6 })
  3511. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3512. .backgroundColor(this.themeColor)
  3513. .enabled(!this.hasSelectedDirectories() && this.getSelectedPlayableFiles().length > 0)
  3514. .bindContentCover($$this.isMergeAudio, this.MergeAudioBuilder(), {
  3515. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3516. })
  3517. .onClick(() => {
  3518. const selectedMediaFiles = this.getSelectedPlayableFiles()
  3519. if (this.hasSelectedDirectories()) {
  3520. ToastUtil.showToast('文件夹不支持合并')
  3521. return
  3522. }
  3523. if(ArrayUtil.isNotEmpty(selectedMediaFiles)&&Utility.isMerge(selectedMediaFiles,this.packName)){
  3524. this.isMergeAudio = !this.isMergeAudio
  3525. }else{
  3526. ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限合并')
  3527. }
  3528. })
  3529. Button('+歌单', { type: ButtonType.Circle, stateEffect: true })
  3530. .width(45)
  3531. .height(45)
  3532. .fontSize(10)
  3533. .margin({ top: 10, bottom: 10, right: 6 })
  3534. .backgroundColor(this.themeColor)
  3535. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3536. .enabled(!this.hasSelectedDirectories() && this.getSelectedPlayableFiles().length > 0)
  3537. .onClick(async () => {
  3538. this.longItemFilePath = ''
  3539. const selectedMediaFiles = this.getSelectedPlayableFiles()
  3540. if (ArrayUtil.isEmpty(selectedMediaFiles)) {
  3541. ToastUtil.showToast('请先选择音频文件')
  3542. return
  3543. }
  3544. await this.openAddToPlaylistDialog(selectedMediaFiles)
  3545. })
  3546. // Button('乱码', { type: ButtonType.Circle, stateEffect: true })
  3547. // .width(45)
  3548. // .height(45)
  3549. // .fontSize(10)
  3550. // .margin({ top: 10, bottom: 10, right: 6 })
  3551. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3552. // .backgroundColor(this.themeColor)
  3553. // .bindContentCover($$this.isFixMessy, this.FixMessyViewBuilder(), {
  3554. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3555. // })
  3556. // .onClick(() => {
  3557. // this.isFixMessy = !this.isFixMessy
  3558. // })
  3559. // Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  3560. // .width('35%')
  3561. // .height(60)
  3562. // .id('music_cut')
  3563. // .margin({ top: 10, bottom: 10, right: 6 })
  3564. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3565. // .backgroundColor(this.themeColor)
  3566. // .onClick(() => {
  3567. // this.showCutDialogForMultipleFiles(false, 'music_cut')
  3568. // })
  3569. //
  3570. // Button('移动', { type: ButtonType.Circle, stateEffect: true })
  3571. // .width('35%')
  3572. // .height(60)
  3573. // .id('music_cut_current')
  3574. // .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  3575. // .margin({ top: 10, bottom: 10, right: 6 })
  3576. // .backgroundColor(this.themeColor)
  3577. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3578. // .onClick(() => {
  3579. //
  3580. // this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  3581. // })
  3582. // Button('复制', { type: ButtonType.Circle, stateEffect: true })
  3583. // .width('35%')
  3584. // .height(60)
  3585. // .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  3586. // .margin({ top: 10, bottom: 10, right: 6 })
  3587. // .backgroundColor(this.themeColor)
  3588. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3589. // .onClick(() => {
  3590. // this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  3591. // })
  3592. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  3593. .width(45)
  3594. .height(45)
  3595. .fontSize(10)
  3596. .margin({ top: 10, bottom: 10, right: 6 })
  3597. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  3598. .backgroundColor(this.themeColor)
  3599. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3600. .onClick(() => {
  3601. this.showWarnIsDelete()
  3602. })
  3603. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  3604. .width(45)
  3605. .height(45)
  3606. .fontSize(10)
  3607. .margin({ top: 10, bottom: 10, right: 6 })
  3608. .backgroundColor(this.themeColor)
  3609. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3610. .onClick(() => {
  3611. this.selectedFiles = [];
  3612. this.isAllSelected = false
  3613. this.isMultiSelect = false
  3614. })
  3615. }
  3616. .width('100%')
  3617. .justifyContent(FlexAlign.Center)
  3618. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  3619. .opacity(this.isMultiSelect ? 1 : 0)
  3620. .animation({
  3621. duration: 666,
  3622. curve: 'ease-in-out' // 可选动画曲线
  3623. })
  3624. .position({ bottom: 20 }) // 将 Row 固定在底部
  3625. }
  3626. .width('100%')
  3627. .height('100%')
  3628. .alignContent(Alignment.Top)
  3629. }
  3630. .width('100%')
  3631. .height('100%')
  3632. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  3633. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  3634. .backgroundImagePosition(Alignment.Center)
  3635. .backdropBlur(this.blurValue)
  3636. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  3637. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  3638. }
  3639. }
  3640. //字母表索引
  3641. @Builder
  3642. indexBuilder(){
  3643. Column({space: 5}){
  3644. if(this.showZMIndex&&this.enableShowAlphabet){
  3645. if(this.isShowAlphaBet&&!(this.modeType==2&&!this.isCanBack)
  3646. &&!(this.modeType==3&&!this.isCanBack)&&(this.sortType==4||this.sortType==5)){
  3647. AlphabetIndexer({arrayValue: this.alphaBet,selected: this.selectAlphaBetIndex})
  3648. .attributeModifier(this.alphaBetStyle)
  3649. .usingPopup(this.isTouchingAlphaBet)
  3650. .onAreaChange((old_value,new_value)=>{
  3651. this.alphabetHeight = new_value.height as number
  3652. })
  3653. .popupPosition({
  3654. x: 40,
  3655. y: this.alphabetHeight / 2
  3656. })
  3657. .onSelect((index: number) => {
  3658. void this.onSelectIndexItem(this.alphaBet[index])
  3659. })
  3660. .onTouch((event: TouchEvent) =>{
  3661. this.showAlphabetIndex()
  3662. if(event.type === TouchType.Up || event.type === TouchType.Cancel){
  3663. this.isTouchingAlphaBet = false
  3664. this.hideAlphabetIndexAfterDelay(1500)
  3665. }else{
  3666. this.isTouchingAlphaBet = true
  3667. }
  3668. })
  3669. .transition(
  3670. TransitionEffect.translate({x: 10})
  3671. .combine(TransitionEffect.opacity(0.1))
  3672. .animation({
  3673. duration: 150,
  3674. curve: Curve.EaseInOut,
  3675. })
  3676. )
  3677. }
  3678. }
  3679. if(this.showFindLocation){
  3680. if(!(this.showZMIndex&&this.enableShowAlphabet)){
  3681. Blank()
  3682. .layoutWeight(1)
  3683. }
  3684. PointLightDefaultButton({
  3685. isSysBol:true,
  3686. pointColor:Color.Gray,
  3687. imageResource:$r('sys.symbol.local_fill'),
  3688. isPx: false,
  3689. builderHeight: 30,
  3690. builderWidth: 30,
  3691. })
  3692. .onClick(() =>{
  3693. void this.locateCurrentSong();
  3694. })
  3695. .clickEffect({level:ClickEffectLevel.LIGHT,scale: 0.5})
  3696. .margin({
  3697. bottom: this.bottomSafeHeight+100,right:10
  3698. })
  3699. }
  3700. }
  3701. .padding({
  3702. bottom: 0
  3703. })
  3704. .margin({right:5})
  3705. .position({x:'92%'})
  3706. .height('100%')
  3707. .justifyContent(FlexAlign.Center)
  3708. .bindSheet($$this.isEqualizerSheet, this.EqualizerSheet(), {
  3709. height: '100%',
  3710. dragBar: true,
  3711. showClose: true,
  3712. preferType: SheetType.CENTER ,
  3713. blurStyle: BlurStyle.Thin,
  3714. title: { title: '均衡器' },
  3715. onDisappear: () => {
  3716. this.isEqualizerSheet = false
  3717. }
  3718. })
  3719. }
  3720. async onSelectIndexItem(letter: string) {
  3721. await this.ensureFullListForAlphabetIndex();
  3722. const findTargetIndex = (): number => {
  3723. const songs = this.videoLocalList;
  3724. for (let i = 0; i < songs.length; i++) {
  3725. const song = songs[i];
  3726. let text = this.isShowFileName ? song.fileName :
  3727. (song.type != CommonConstants.TYPE_IS_DIR && song.pyStr) ? song.pyStr : song.name;
  3728. if (this.sortType === 0 || this.sortType == 1) {
  3729. text = song.artist;
  3730. } else if (this.sortType === 2 || this.sortType == 3) {
  3731. text = song.album;
  3732. }
  3733. if (text) {
  3734. const firstPinyin = getFirstLetter(text);
  3735. if (firstPinyin && firstPinyin === letter) {
  3736. return i;
  3737. }
  3738. }
  3739. }
  3740. return -1;
  3741. };
  3742. const targetIndex = findTargetIndex();
  3743. if (targetIndex !== -1) {
  3744. if (this.isGridMusic || this.twoFingerType == 4) {
  3745. this.scroller.scrollToIndex(targetIndex, false);
  3746. } else {
  3747. this.listScroller.scrollToIndex(targetIndex);
  3748. }
  3749. }
  3750. }
  3751. private showAlphabetIndex(): void {
  3752. this.isShowAlphaBet = true;
  3753. if (this.alphaBetHideTimer) {
  3754. clearTimeout(this.alphaBetHideTimer);
  3755. this.alphaBetHideTimer = 0;
  3756. }
  3757. }
  3758. private hideAlphabetIndexAfterDelay(delayMs: number): void {
  3759. if (this.alphaBetHideTimer) {
  3760. clearTimeout(this.alphaBetHideTimer);
  3761. }
  3762. this.alphaBetHideTimer = setTimeout(() => {
  3763. if (!this.isTouchingAlphaBet) {
  3764. this.isShowAlphaBet = false;
  3765. }
  3766. this.alphaBetHideTimer = 0;
  3767. }, delayMs) as number;
  3768. }
  3769. private scheduleAlphaBetRebuild(delayMs: number = 120): void {
  3770. if (!this.showZMIndex) {
  3771. return;
  3772. }
  3773. if (this.alphaBetRebuildTimer) {
  3774. clearTimeout(this.alphaBetRebuildTimer);
  3775. }
  3776. this.alphaBetRebuildTimer = setTimeout(() => {
  3777. this.alphaBetRebuildTimer = 0;
  3778. if (this.isScrolling) {
  3779. this.alphaBetDirty = true;
  3780. return;
  3781. }
  3782. this.alphaBetDirty = false;
  3783. void this.setAlphaBet();
  3784. }, delayMs) as number;
  3785. }
  3786. private markAlphaBetDirty(): void {
  3787. if (!this.showZMIndex) {
  3788. return;
  3789. }
  3790. if (this.isMediaLibraryWarmupWindow()) {
  3791. this.alphaBetDirty = true;
  3792. this.scheduleAlphaBetRebuild(900);
  3793. return;
  3794. }
  3795. this.alphaBetDirty = true;
  3796. if (!this.isScrolling) {
  3797. this.scheduleAlphaBetRebuild(80);
  3798. }
  3799. }
  3800. private async ensureFullListForAlphabetIndex(): Promise<void> {
  3801. if (this.isLoadingPage) {
  3802. return;
  3803. }
  3804. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  3805. return;
  3806. }
  3807. if (this.totalCount === 0 || this.videoLocalList.length >= this.totalCount) {
  3808. return;
  3809. }
  3810. if (this.modeType !== 0 && this.modeType !== 1) {
  3811. return;
  3812. }
  3813. this.isLoadingPage = true;
  3814. try {
  3815. const options: PageQueryOptions = {
  3816. pageIndex: 0,
  3817. pageSize: this.totalCount,
  3818. sortType: this.sortType,
  3819. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  3820. isShowFileName: this.isShowFileName
  3821. };
  3822. if (this.modeType === 0) {
  3823. options.parentPath = this.currentPath;
  3824. }
  3825. let result: PageQueryResult;
  3826. if (this.modeType === 0) {
  3827. result = await this.table.queryByParentPathPaged(options);
  3828. const dbItems = this.filterOutLocalIsoItems(result.items);
  3829. if (!this.isSearchMode) {
  3830. const directories: VideoItem[] = await this.loadDirectories(this.currentPath);
  3831. const isoItems: VideoItem[] = this.getLocalIsoItems(this.currentPath);
  3832. result.items = [...directories, ...isoItems, ...dbItems];
  3833. } else {
  3834. result.items = dbItems;
  3835. }
  3836. } else {
  3837. result = await this.table.queryMediaLibraryPaged(options);
  3838. }
  3839. this.videoLocalList = result.items;
  3840. this.dataSource.pushArrayData(this.videoLocalList);
  3841. this.pageCache.clear();
  3842. this.pageHasMoreCache.clear();
  3843. this.pageTotalCountCache.clear();
  3844. this.prefetchingPages.clear();
  3845. this.currentPage = 0;
  3846. this.totalCount = this.modeType === 0 ? result.items.length : result.totalCount;
  3847. this.hasMoreData = false;
  3848. this.lastScrollTriggerPage = -1;
  3849. this.lastVisibleEndIndex = -1;
  3850. this.isPagingTransition = false;
  3851. if (this.pagingScheduleTimer) {
  3852. clearTimeout(this.pagingScheduleTimer);
  3853. this.pagingScheduleTimer = 0;
  3854. }
  3855. if (this.modeType === 1) {
  3856. this.mediaKuCount = result.totalCount;
  3857. }
  3858. this.setButtonStatus();
  3859. this.markAlphaBetDirty();
  3860. } catch (err) {
  3861. const error = err as Error;
  3862. Logger.warn('heanup LocalMusic', `ensureFullListForAlphabetIndex error: ${error.message}`);
  3863. } finally {
  3864. this.isLoadingPage = false;
  3865. }
  3866. }
  3867. // 找到对应字母表的索引
  3868. findAlphaBetIndex(song: VideoItem):number{
  3869. let text = this.isShowFileName?song.fileName:
  3870. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  3871. if(this.sortType === 0||this.sortType==1){
  3872. text = song.artist
  3873. }else if(this.sortType === 2||this.sortType==3){
  3874. text = song.album
  3875. }
  3876. if(text){
  3877. let firstLetter = getFirstLetter(text)
  3878. for(let i=0;i<this.alphaBet.length;i++){
  3879. if(this.alphaBet[i] === firstLetter){
  3880. return i
  3881. }
  3882. }
  3883. }
  3884. return 0
  3885. }
  3886. private buildAlphaTaskItems(songs: Array<VideoItem>): Array<AlphaTaskItem> {
  3887. const items: Array<AlphaTaskItem> = []
  3888. for (const song of songs) {
  3889. items.push({
  3890. type: song.type,
  3891. name: song.name,
  3892. pyStr: song.pyStr,
  3893. fileName: song.fileName,
  3894. artist: song.artist,
  3895. album: song.album
  3896. })
  3897. }
  3898. return items
  3899. }
  3900. private async buildAlphaBetByTask(songs: Array<VideoItem>, version: number): Promise<void> {
  3901. const taskItems = this.buildAlphaTaskItems(songs)
  3902. const task = new taskpool.Task(buildAlphabetIndexTask, taskItems, this.sortType, this.isShowFileName)
  3903. const result = await taskpool.execute(task, taskpool.Priority.MEDIUM) as Array<string>
  3904. if (version !== this.alphaBetBuildVersion) {
  3905. return
  3906. }
  3907. this.alphaBet = result
  3908. if (this.videoLocalList.length > 0) {
  3909. this.selectAlphaBetIndex = 0
  3910. }
  3911. }
  3912. async setAlphaBet(){
  3913. if(!this.showZMIndex){
  3914. return
  3915. }
  3916. if (this.modeType === 1 && this.totalCount > this.videoLocalList.length) {
  3917. await this.refreshAlphaBetFromMediaLibrary()
  3918. return
  3919. }
  3920. try {
  3921. const songs = this.videoLocalList
  3922. if (songs.length > 40000) {
  3923. this.alphaBet = []
  3924. return
  3925. }
  3926. const version = ++this.alphaBetBuildVersion
  3927. await this.buildAlphaBetByTask(songs, version)
  3928. } catch (e) {
  3929. console.error('testTag','排序字母表出错',JSON.stringify(e))
  3930. }
  3931. }
  3932. private async refreshAlphaBetFromMediaLibrary(): Promise<void> {
  3933. if (this.totalCount <= 0) {
  3934. return
  3935. }
  3936. if (this.totalCount > 40000) {
  3937. this.alphaBet = []
  3938. return
  3939. }
  3940. const keyword = this.isSearchMode ? this.searchText : ''
  3941. const cacheKey = `${this.modeType}-${this.sortType}-${this.isShowFileName}-${keyword}-${this.totalCount}`
  3942. if (this.alphaBetCacheKey === cacheKey && this.alphaBet.length > 0) {
  3943. return
  3944. }
  3945. const result = await this.table.queryMediaLibraryPaged({
  3946. pageIndex: 0,
  3947. pageSize: this.totalCount,
  3948. sortType: this.sortType,
  3949. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  3950. isShowFileName: this.isShowFileName
  3951. })
  3952. const version = ++this.alphaBetBuildVersion
  3953. await this.buildAlphaBetByTask(result.items, version)
  3954. this.alphaBetCacheKey = cacheKey
  3955. }
  3956. @Builder
  3957. topTitleBar(){
  3958. Column() {
  3959. Row({ space: 15 }) {
  3960. if (!this.isSearchMode ) {
  3961. //左侧滑动按钮
  3962. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3963. SymbolGlyph(this.rightTopImage)
  3964. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3965. }
  3966. .attributeModifier(new ButtonFancyModifier(40, 40))
  3967. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3968. .animation({ duration: 300, curve: Curve.Ease })
  3969. .onClick(() => {
  3970. this.triggerSwipeBackWithAnimation()
  3971. })
  3972. .attributeModifier(new ShadowModifier())
  3973. .zIndex(0)
  3974. }else{
  3975. //左侧搜索返回按钮
  3976. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3977. SymbolGlyph($r('sys.symbol.chevron_left'))
  3978. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3979. }
  3980. .attributeModifier(new ButtonFancyModifier(40, 40))
  3981. .margin({bottom:5})
  3982. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3983. .animation({ duration: 300, curve: Curve.Ease })
  3984. .onClick(() => {
  3985. this.isSearchMode = false
  3986. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  3987. this.searchText = ''
  3988. this.getSortedFiles(this.currentPath)
  3989. return
  3990. }
  3991. this.onSearchInput('')
  3992. })
  3993. .attributeModifier(new ShadowModifier())
  3994. .zIndex(0)
  3995. }
  3996. if (!this.isSearchMode) {
  3997. Text(this.modeType==1?`${this.titleName}(${this.mediaKuCount}首)`:this.titleName)
  3998. .margin({left:3,right:10})
  3999. .fontColor($r('app.color.text_color'))
  4000. .fontSize(this.twoFingerType==3?17:16)
  4001. .maxLines(1)
  4002. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4003. .layoutWeight(1)
  4004. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  4005. }
  4006. //搜索框
  4007. Search({ controller: this.searchController,value: this.searchText, placeholder: '搜索标题、艺术家...' })
  4008. .searchButton('搜索',{fontColor:this.themeColor})
  4009. .searchIcon({
  4010. src: $r('sys.media.ohos_ic_public_search_filled')
  4011. })
  4012. .cancelButton({
  4013. style: CancelButtonStyle.CONSTANT,
  4014. icon: {
  4015. src: $r('sys.media.ohos_ic_public_cancel_filled')
  4016. }
  4017. })
  4018. .layoutWeight(1)
  4019. .height(40)
  4020. .maxLength(20)
  4021. .backgroundColor(this.isDarkMode?Color.Black:'#F5F5F5')
  4022. .placeholderColor(Color.Grey)
  4023. .placeholderFont({ size: 14, weight: 400 })
  4024. .textFont({ size: 14, weight: 400 })
  4025. .onSubmit((value: string) => {
  4026. console.log('onecold onSubmit ='+value)
  4027. this.searchController.stopEditing()
  4028. if(this.modeType==0){
  4029. this.modeType =1//如果是首页 切换到媒体库搜索
  4030. }
  4031. this.commitSearchHistory(value)
  4032. this.onSearchInput(this.searchText);
  4033. })
  4034. .onChange((value: string) => {
  4035. console.log('onecold onChange ='+value)
  4036. if(this.modeType==0){
  4037. this.modeType =1//如果是首页 切换到媒体库搜索
  4038. }
  4039. this.onSearchInput(value);
  4040. })
  4041. .visibility(this.isSearchMode?Visibility.Visible:Visibility.None)
  4042. .animation({ duration: 300, curve: Curve.Ease })
  4043. //搜索按钮
  4044. if (!this.isSearchMode) {
  4045. Button({ type: ButtonType.Circle, stateEffect: true }) {
  4046. SymbolGlyph($r('sys.symbol.magnifyingglass'))
  4047. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  4048. }
  4049. .attributeModifier(new ButtonFancyModifier(40, 40))
  4050. .animation({ duration: 300, curve: Curve.Ease })
  4051. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  4052. .attributeModifier(new ShadowModifier())
  4053. .zIndex(0)
  4054. .onClick(()=>{
  4055. this.isSearchMode = true
  4056. this.loadSearchHistory()
  4057. })
  4058. //排序按钮
  4059. Button({ type: ButtonType.Circle, stateEffect: true }) {
  4060. SymbolGlyph($r('sys.symbol.list_number'))
  4061. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  4062. }
  4063. .attributeModifier(new ButtonFancyModifier(40, 40))
  4064. .animation({ duration: 300, curve: Curve.Ease })
  4065. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  4066. .bindMenu((this.modeType==2&&!this.isCanBack)||(this.modeType==3&&!this.isCanBack)
  4067. ?this.SortMenuForArtistAblumBuilder:this.SortMenuBuilder)
  4068. .attributeModifier(new ShadowModifier())
  4069. .zIndex(0)
  4070. //添加按钮
  4071. Button({ type: ButtonType.Circle, stateEffect: true }) {
  4072. SymbolGlyph($r('sys.symbol.plus'))
  4073. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  4074. }
  4075. .attributeModifier(new ButtonFancyModifier(40, 40))
  4076. .animation({ duration: 300, curve: Curve.Ease })
  4077. .visibility(this.modeType==0||this.modeType==1?Visibility.Visible:Visibility.None)
  4078. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  4079. .bindSheet($$this.showAddSheet, this.addSheet(), {
  4080. height: SheetSize.FIT_CONTENT,
  4081. dragBar: true,
  4082. showClose: true,
  4083. preferType: SheetType.CENTER ,
  4084. title: {
  4085. title: '导入音乐'
  4086. }
  4087. })
  4088. .onClick(() => {
  4089. this.showAddSheet = !this.showAddSheet;
  4090. })
  4091. .attributeModifier(new ShadowModifier())
  4092. .zIndex(0)
  4093. }
  4094. }
  4095. }
  4096. .padding({ top: this.topSafeHeight+10, left: 10, right: 10 })
  4097. .width('100%')
  4098. .translate({
  4099. x: 0,
  4100. y: (this.isShowTitleBar || !this.autoHideTitle) ? 0 : -80
  4101. })
  4102. .opacity((this.isShowTitleBar || !this.autoHideTitle) ? 1 : 0)
  4103. .animation({
  4104. duration: 240,
  4105. curve: Curve.EaseInOut
  4106. })
  4107. }
  4108. @Builder
  4109. addSheet() {
  4110. Scroll() {
  4111. Column() {
  4112. Column() {
  4113. Row() {
  4114. SymbolGlyph($r('sys.symbol.info_circle'))
  4115. .fontSize(22)
  4116. .fontColor([this.themeColor])
  4117. .alignSelf(ItemAlign.Center)
  4118. .margin({ left: 8 })
  4119. Text('导入音乐复制到DownLoad目录')
  4120. .margin({ left: 8 })
  4121. .fontSize(14)
  4122. .fontColor($r('app.color.text_color'))
  4123. .fontWeight(480)
  4124. .layoutWeight(1)
  4125. Toggle({ type: ToggleType.Switch, isOn: this.isCopyFileToDownLoad })
  4126. .selectedColor(this.themeColor)
  4127. .switchPointColor(Color.White)
  4128. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  4129. .margin({ right: 2 })
  4130. .onChange((checked: boolean) => {
  4131. this.isCopyFileToDownLoad = checked;
  4132. PreferencesUtil.put(SettingPage.IS_COPYFILE_TO_DOWNLOAD, this.isCopyFileToDownLoad)
  4133. })
  4134. .width(50)
  4135. .height(30);
  4136. }
  4137. .height(72)
  4138. .padding({ left:8,right:8 })
  4139. }
  4140. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  4141. .backgroundColor($r('app.color.start_window_background'))
  4142. .borderRadius(15)
  4143. .width('85%')
  4144. .margin({
  4145. top: 10,
  4146. bottom: 10
  4147. })
  4148. .padding(0)
  4149. .border({
  4150. color: Color.White,
  4151. width: 1.8
  4152. })
  4153. Menu() {
  4154. MenuItem({
  4155. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder_badge_plus')),
  4156. content: "新建文件夹"
  4157. })
  4158. .backgroundColor($r('app.color.silvery'))
  4159. .border({
  4160. width: { bottom: 1 },
  4161. color: '#12ec5c87'
  4162. })
  4163. .margin(10)
  4164. .height(60)
  4165. .padding({left:15,right:15})
  4166. .onClick(async () => {
  4167. this.showMkDialog()
  4168. this.showAddSheet = !this.showAddSheet
  4169. })
  4170. MenuItem({
  4171. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder')),
  4172. content: $r('app.string.import_from_files')
  4173. })
  4174. .padding({left:15,right:15})
  4175. .backgroundColor($r('app.color.silvery'))
  4176. .border({
  4177. width: { bottom: 1 },
  4178. color: '#12ec5c87'
  4179. })
  4180. .margin(10)
  4181. .height(60)
  4182. .onClick(async () => {
  4183. this.callFilePickerSelectFile()
  4184. this.showAddSheet = !this.showAddSheet
  4185. })
  4186. MenuItem({
  4187. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square')),
  4188. content: '全选导入'
  4189. // content: '从下载文件夹导入(路径:Download/' +
  4190. // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
  4191. })
  4192. .padding({left:15,right:15})
  4193. .backgroundColor($r('app.color.silvery'))
  4194. .border({
  4195. width: { bottom: 1 },
  4196. color: '#12ec5c87'
  4197. })
  4198. .margin(10)
  4199. .height(60)
  4200. .onClick(async () => {
  4201. this.goSelectMusic()
  4202. this.showAddSheet = !this.showAddSheet
  4203. })
  4204. MenuItem({
  4205. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.save')),
  4206. content: '自动导入教程'
  4207. })
  4208. .padding({left:15,right:15})
  4209. .backgroundColor($r('app.color.silvery'))
  4210. .border({
  4211. width: { bottom: 1 },
  4212. color: '#12ec5c87'
  4213. })
  4214. .margin(10)
  4215. .height(60)
  4216. .onClick(async () => {
  4217. this.showTips()
  4218. this.showAddSheet = !this.showAddSheet
  4219. })
  4220. MenuItem({
  4221. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.questionmark_circle')),
  4222. content: '导入疑问'
  4223. })
  4224. .height(60)
  4225. .padding({left:15,right:15})
  4226. .backgroundColor($r('app.color.silvery'))
  4227. .border({
  4228. width: { bottom: 1 },
  4229. color: '#12ec5c87'
  4230. })
  4231. .margin(10)
  4232. .onClick(async () => {
  4233. this.showProblomTips()
  4234. this.showAddSheet = !this.showAddSheet
  4235. })
  4236. }.attributeModifier(new MenuModifier())
  4237. .margin({bottom:30})
  4238. .width('90%')
  4239. .borderRadius(15)
  4240. }
  4241. .layoutWeight(1)
  4242. }
  4243. }
  4244. async showProblomTips() {
  4245. try {
  4246. this.getUIContext().getPromptAction().showDialog({
  4247. title: '导入疑问',
  4248. message:'为什么有些歌曲导入成功后,内嵌标签或者其他功能不能用?:\n\n1、由于鸿蒙系统的安全策略,文件权限不够,请将文件移动到Download/天天静听目录下。' +
  4249. '这样内嵌标签功能就没有权限问题。\n\n2、导入可以也选择不复制,这样可以省略空间。\n\n',
  4250. buttons: [
  4251. {
  4252. text: '知道了',
  4253. color: '#000000'
  4254. },
  4255. ]
  4256. }, (err, data) => {
  4257. if (err) {
  4258. console.error('showDialog err: ' + err);
  4259. return;
  4260. }
  4261. console.info('showDialog success callback, click button: ' + data.index);
  4262. });
  4263. } catch (error) {
  4264. let message = (error as BusinessError).message;
  4265. let code = (error as BusinessError).code;
  4266. console.error(`showDialog args error code is ${code}, message is ${message}`);
  4267. };
  4268. }
  4269. @Builder
  4270. TagsContentCoverBuilder() {
  4271. Scroll() {
  4272. Column() {
  4273. TagsContentCover(
  4274. {
  4275. selectedFiles:this.selectedFiles,
  4276. isOneKeyTags:this.isOneKeyTags,
  4277. onSeePath:(path:string)=>{
  4278. this.modeType = 0
  4279. this.deleteCache(path)
  4280. this.getSortedFiles(path)
  4281. },
  4282. onTagsResult:(result: boolean,deleteCache_path?:string)=>{
  4283. this.isMultiSelect = false
  4284. if(result){//如果嵌入成功,更新数据
  4285. this.listRefreshKey++
  4286. setTimeout(()=>{
  4287. this.doUpdateData()
  4288. },500)
  4289. }
  4290. console.info('onecold onTagsResult deleteCache_path =' +deleteCache_path)
  4291. if(deleteCache_path){
  4292. this.deleteCache(deleteCache_path)
  4293. }
  4294. }
  4295. }
  4296. )
  4297. }
  4298. }
  4299. .width('100%')
  4300. .height('100%')
  4301. }
  4302. @Builder
  4303. FixMessyViewBuilder() {
  4304. Scroll() {
  4305. Column() {
  4306. FixMessyView(
  4307. {
  4308. selectedFiles:this.selectedFiles,
  4309. isFixMessy:this.isFixMessy,
  4310. onFixResult:(result: boolean)=>{
  4311. this.isMultiSelect = false
  4312. if(result){//如果嵌入成功,更新数据
  4313. this.deleteCache(this.currentPath)
  4314. this.doUpdateData()
  4315. }
  4316. }
  4317. }
  4318. )
  4319. }
  4320. }
  4321. .width('100%')
  4322. .height('100%')
  4323. }
  4324. //剪辑音频
  4325. @Builder
  4326. EditAudioBuilder(item:VideoItem) {
  4327. Scroll() {
  4328. Column() {
  4329. EditAudio(
  4330. {
  4331. mVideoItem:item,
  4332. currentPath:this.currentPath,
  4333. videoUrl:this.videoUrl,
  4334. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4335. currentTime:this.currentTime,
  4336. progressValue:this.progressValue,
  4337. onBack:()=>{
  4338. this.isEditAudio = !this.isEditAudio
  4339. },
  4340. onSeeOutputPath:(outPutPath:string)=>{
  4341. this.isEditAudio = !this.isEditAudio
  4342. this.longItemFilePath = ''
  4343. this.modeType = 0
  4344. this.isShowFileName = true
  4345. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4346. },
  4347. onPlayOrPause:()=>{
  4348. if(this.videoUrl==item.filePath){
  4349. this.playOrPause()
  4350. }else{//如果不是当前播放的,则播放该文件
  4351. this.videoUrl==item.filePath
  4352. this.doPlay(item,0,false,true)
  4353. }
  4354. },
  4355. onSliderChange:(value:number)=>{
  4356. if(this.videoUrl!=item.filePath){
  4357. this.videoUrl==item.filePath
  4358. return
  4359. }
  4360. this.isSeekTo = true;
  4361. this.mDestroyPage = false;
  4362. this.showLoadIng();
  4363. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  4364. let seekValue = value * (this.getActiveDuration() / 100);
  4365. this.seekTo(seekValue + "");
  4366. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  4367. this.isSeekTo = false;
  4368. },
  4369. onResult:(result: boolean,outPath:string)=>{
  4370. if(result){//如果剪辑成功,更新数据
  4371. this.doUpdateData()
  4372. }else{
  4373. ToastUtil.showToast('剪辑失败')
  4374. }
  4375. }
  4376. }
  4377. )
  4378. }
  4379. }
  4380. .width('100%')
  4381. .height('100%')
  4382. }
  4383. //提取伴奏
  4384. @Builder
  4385. ConverterBuilder(item:VideoItem) {
  4386. Scroll() {
  4387. Column() {
  4388. AudioFormatConverter(
  4389. {
  4390. mVideoItem:item,
  4391. videoUrl:this.videoUrl,
  4392. currentPath:this.currentPath,
  4393. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4394. currentTime:this.currentTime,
  4395. progressValue:this.progressValue,
  4396. onBack:()=>{
  4397. this.isConverter = !this.isConverter
  4398. this.longItemFilePath = ''
  4399. },
  4400. onPlayOrPause:()=>{
  4401. if(this.videoUrl==item.filePath){
  4402. this.playOrPause()
  4403. }else{//如果不是当前播放的,则播放该文件
  4404. this.videoUrl==item.filePath
  4405. this.doPlay(item,0,false,true)
  4406. }
  4407. },
  4408. onSeeOutputPath:(outPutPath:string)=>{
  4409. this.isConverter = !this.isConverter
  4410. this.longItemFilePath = ''
  4411. this.modeType = 0
  4412. this.isShowFileName = true
  4413. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4414. },
  4415. onSliderChange:(value:number)=>{
  4416. if(this.videoUrl!=item.filePath){
  4417. this.videoUrl==item.filePath
  4418. return
  4419. }
  4420. this.isSeekTo = true;
  4421. this.mDestroyPage = false;
  4422. this.showLoadIng();
  4423. let seekValue = value * (this.getActiveDuration() / 100);
  4424. this.seekTo(seekValue + "");
  4425. this.isSeekTo = false;
  4426. },
  4427. onResult:(result: boolean,outPath:string)=>{
  4428. if(result){//如果成功,更新数据
  4429. this.doUpdateData()
  4430. }else{
  4431. ToastUtil.showToast('格式转化失败')
  4432. }
  4433. }
  4434. }
  4435. )
  4436. }
  4437. }
  4438. .width('100%')
  4439. .height('100%')
  4440. }
  4441. //提取伴奏
  4442. @Builder
  4443. ExtractAccBuilder(item:VideoItem) {
  4444. Scroll() {
  4445. Column() {
  4446. ExtractAccompaniment(
  4447. {
  4448. mVideoItem:item,
  4449. currentPath:this.currentPath,
  4450. videoUrl:this.videoUrl,
  4451. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4452. currentTime:this.currentTime,
  4453. progressValue:this.progressValue,
  4454. onBack:()=>{
  4455. this.isExtractAcc = !this.isExtractAcc
  4456. this.longItemFilePath = ''
  4457. },
  4458. onPlayOrPause:()=>{
  4459. if(this.videoUrl==item.filePath){
  4460. this.playOrPause()
  4461. }else{//如果不是当前播放的,则播放该文件
  4462. this.videoUrl==item.filePath
  4463. this.doPlay(item,0,false,true)
  4464. }
  4465. },
  4466. onSeeOutputPath:(outPutPath:string)=>{
  4467. this.isExtractAcc = !this.isExtractAcc
  4468. this.longItemFilePath = ''
  4469. this.modeType = 0
  4470. this.isShowFileName = true
  4471. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4472. },
  4473. onSliderChange:(value:number)=>{
  4474. if(this.videoUrl!=item.filePath){
  4475. this.videoUrl==item.filePath
  4476. return
  4477. }
  4478. this.isSeekTo = true;
  4479. this.mDestroyPage = false;
  4480. this.showLoadIng();
  4481. let seekValue = value * (this.getActiveDuration() / 100);
  4482. this.seekTo(seekValue + "");
  4483. this.isSeekTo = false;
  4484. },
  4485. onResult:(result: boolean,outPath:string)=>{
  4486. if(result){//如果成功,更新数据
  4487. this.doUpdateData()
  4488. }else{
  4489. ToastUtil.showToast('提取伴奏失败')
  4490. }
  4491. }
  4492. }
  4493. )
  4494. }
  4495. }
  4496. .width('100%')
  4497. .height('100%')
  4498. }
  4499. //AI人声分离
  4500. @Builder
  4501. AiBuilder(item:VideoItem) {
  4502. Scroll() {
  4503. Column() {
  4504. AIVoiceSeparation(
  4505. {
  4506. mVideoItem:item,
  4507. videoUrl:this.videoUrl,
  4508. currentPath:this.currentPath,
  4509. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4510. currentTime:this.currentTime,
  4511. progressValue:this.progressValue,
  4512. onBack:()=>{
  4513. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  4514. this.longItemFilePath = ''
  4515. },
  4516. onPlayOrPause:()=>{
  4517. if(this.videoUrl==item.filePath||this.isPlaying){
  4518. this.playOrPause()
  4519. }else{//如果不是当前播放的,则播放该文件
  4520. this.videoUrl==item.filePath
  4521. this.doPlay(item,0,false,true)
  4522. }
  4523. },
  4524. onPlayPath:(path:string)=>{
  4525. this.videoUrl==path
  4526. const itemP = Utility.getItemByFilePath(this.videoLocalList,path)
  4527. if(itemP)
  4528. this.doPlay(itemP,0,false,true)
  4529. },
  4530. onSeeOutputPath:(outPutPath:string)=>{
  4531. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  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('Ai人声分离失败')
  4554. }
  4555. }
  4556. }
  4557. )
  4558. }
  4559. }
  4560. .width('100%')
  4561. .height('100%')
  4562. }
  4563. //变速变调
  4564. @Builder
  4565. ChangeToneBuilder(item:VideoItem) {
  4566. Scroll() {
  4567. Column() {
  4568. ChangeTone(
  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.isChangeTone = !this.isChangeTone
  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.isChangeTone = !this.isChangeTone
  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. //提取视频中的音频
  4622. @Builder
  4623. extractAudioFromVideoBuilder(item:VideoItem) {
  4624. Scroll() {
  4625. Column() {
  4626. ExtractAudioFromVideo(
  4627. {
  4628. mVideoItem:item,
  4629. currentPath:this.currentPath,
  4630. videoUrl:this.videoUrl,
  4631. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4632. currentTime:this.currentTime,
  4633. progressValue:this.progressValue,
  4634. onBack:()=>{
  4635. this.isExtractAudio = !this.isExtractAudio
  4636. this.longItemFilePath = ''
  4637. },
  4638. onPlayOrPause:()=>{
  4639. if(this.videoUrl==item.filePath){
  4640. this.playOrPause()
  4641. }else{//如果不是当前播放的,则播放该文件
  4642. this.videoUrl==item.filePath
  4643. this.doPlay(item,0,false,true)
  4644. }
  4645. },
  4646. onSeeOutputPath:(outPutPath:string)=>{
  4647. this.isExtractAudio = !this.isExtractAudio
  4648. this.longItemFilePath = ''
  4649. this.modeType = 0
  4650. this.isShowFileName = true
  4651. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4652. },
  4653. onSliderChange:(value:number)=>{
  4654. if(this.videoUrl!=item.filePath){
  4655. this.videoUrl==item.filePath
  4656. return
  4657. }
  4658. this.isSeekTo = true;
  4659. this.mDestroyPage = false;
  4660. this.showLoadIng();
  4661. let seekValue = value * (this.getActiveDuration() / 100);
  4662. this.seekTo(seekValue + "");
  4663. this.isSeekTo = false;
  4664. },
  4665. onResult:(result: boolean,outPath:string)=>{
  4666. if(result){//如果成功,更新数据
  4667. this.doUpdateData()
  4668. }else{
  4669. ToastUtil.showToast('提取音频失败')
  4670. }
  4671. }
  4672. }
  4673. )
  4674. }
  4675. }
  4676. .width('100%')
  4677. .height('100%')
  4678. }
  4679. //合并音频
  4680. @Builder
  4681. MergeAudioBuilder() {
  4682. Scroll() {
  4683. Column() {
  4684. MergeAudio(
  4685. {
  4686. videoUrl:this.videoUrl,
  4687. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4688. currentPath:this.currentPath,
  4689. selectedFiles:this.selectedFiles,
  4690. currentTime:this.currentTime,
  4691. progressValue:this.progressValue,
  4692. onBack:()=>{
  4693. this.isMergeAudio = !this.isMergeAudio
  4694. this.longItemFilePath = ''
  4695. },
  4696. // onPlayPath:(path:string)=>{
  4697. // if(this.videoUrl==item.filePath){
  4698. // this.playOrPause()
  4699. // }else{//如果不是当前播放的,则播放该文件
  4700. // this.videoUrl==item.filePath
  4701. // this.doPlay(item,0,false,true)
  4702. // }
  4703. //
  4704. // },
  4705. onSeeOutputPath:(outPutPath:string)=>{
  4706. this.isMergeAudio = !this.isMergeAudio
  4707. this.longItemFilePath = ''
  4708. this.modeType = 0
  4709. this.isShowFileName = true
  4710. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4711. },
  4712. onResult:(result: boolean,outPath:string)=>{
  4713. if(result){//如果成功,更新数据
  4714. this.doUpdateData()
  4715. }else{
  4716. if(this.selectedFiles.length>=3){
  4717. ToastUtil.showToast('合并数量太多导致失败')
  4718. }else{
  4719. ToastUtil.showToast('合并失败')
  4720. }
  4721. }
  4722. }
  4723. }
  4724. )
  4725. }
  4726. }
  4727. .width('100%')
  4728. .height('100%')
  4729. }
  4730. asyncCurrentPathData() {
  4731. if (this.modeType == 0) {
  4732. workerInstance.postMessage({
  4733. code: 1,
  4734. data1: this.context,
  4735. data2: this.currentPath,
  4736. data3: this.lockPath,
  4737. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  4738. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  4739. });
  4740. }
  4741. }
  4742. // 处理文件选择的函数
  4743. handleFileSelection(item: VideoItem, checked: boolean) {
  4744. if (!this.isSelectableLocalItem(item)) {
  4745. return
  4746. }
  4747. const exists = this.isLocalItemSelected(item)
  4748. if (checked) {
  4749. if (!exists) {
  4750. this.selectedFiles = [...this.selectedFiles, item];
  4751. }
  4752. } else if (exists) {
  4753. this.selectedFiles = this.selectedFiles.filter(selected => selected.filePath !== item.filePath);
  4754. if (this.selectedFiles.length === 0) {
  4755. this.isAllSelected = false
  4756. }
  4757. }
  4758. this.syncLocalSelectionState()
  4759. }
  4760. private deleteComponentId: number = 0
  4761. private closeDeleteDialog(afterClose?: () => void): void {
  4762. if (this.deleteComponentId > 0) {
  4763. try {
  4764. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  4765. } catch (_error) {
  4766. }
  4767. this.deleteComponentId = 0
  4768. }
  4769. if (afterClose) {
  4770. setTimeout(() => {
  4771. afterClose()
  4772. }, 16)
  4773. }
  4774. }
  4775. private resetDeleteSelectionState(): void {
  4776. this.isMultiSelect = false
  4777. this.selectedFiles = []
  4778. this.isAllSelected = false
  4779. }
  4780. private removeDisplayedLocalItemsByKeys(deletedKeys: Set<string>): void {
  4781. for (let index = this.dataSource.dataArray.length - 1; index >= 0; index--) {
  4782. const item = this.dataSource.dataArray[index]
  4783. if (item && deletedKeys.has(item.filePath)) {
  4784. this.dataSource.deleteData(index)
  4785. }
  4786. }
  4787. }
  4788. private async removeDeletedLocalItemsLocally(deletedItems: Array<VideoItem>): Promise<void> {
  4789. if (ArrayUtil.isEmpty(deletedItems) || this.modeType !== 0) {
  4790. return
  4791. }
  4792. const deletedKeys: Set<string> = new Set<string>()
  4793. for (let i = 0; i < deletedItems.length; i++) {
  4794. const item = deletedItems[i]
  4795. if (StrUtil.isNotEmpty(item?.filePath)) {
  4796. deletedKeys.add(item.filePath)
  4797. }
  4798. }
  4799. if (deletedKeys.size <= 0) {
  4800. return
  4801. }
  4802. const nextVideoLocalList = this.videoLocalList.filter((item: VideoItem) => !deletedKeys.has(item.filePath))
  4803. const nextDirList = this.dirList.filter((item: VideoItem) => !deletedKeys.has(item.filePath))
  4804. const nextFilteredList = this.filteredList.filter((item: VideoItem) => !deletedKeys.has(item.filePath))
  4805. const removedCount = this.videoLocalList.length - nextVideoLocalList.length
  4806. this.videoLocalList = nextVideoLocalList
  4807. this.dirList = nextDirList
  4808. this.filteredList = nextFilteredList
  4809. this.removeDisplayedLocalItemsByKeys(deletedKeys)
  4810. if (removedCount > 0 && this.totalCount > 0) {
  4811. this.totalCount = Math.max(0, this.totalCount - removedCount)
  4812. }
  4813. this.pageCache.clear()
  4814. this.pageHasMoreCache.clear()
  4815. this.pageTotalCountCache.clear()
  4816. this.setButtonStatus()
  4817. this.markAlphaBetDirty()
  4818. this.syncLocalSelectionState()
  4819. this.addCache(this.currentPath, nextVideoLocalList)
  4820. if (this.currentPath === this.rootPath) {
  4821. this.addCache(this.currentPath + '_dirList', nextDirList)
  4822. }
  4823. this.deleteStringCache(this.currentPath + '_hash')
  4824. await this.saveCacheToStorage()
  4825. }
  4826. //多选删除文件
  4827. showWarnIsDelete(){
  4828. this.getUIContext().getPromptAction().openCustomDialog({
  4829. builder: () => {
  4830. this.deleteComptentBuilder()
  4831. },
  4832. isModal:true,
  4833. showInSubWindow:false,
  4834. maskColor: Color.Transparent,
  4835. dialogTransition: // 设置弹窗内容显示的过渡效果
  4836. TransitionEffect.translate({ x: 0, y: 120, z: 0 })
  4837. .combine(TransitionEffect.opacity(0.01))
  4838. .animation({ duration: 260, curve: Curve.EaseOut }),
  4839. maskTransition: // 设置蒙层显示的过渡效果
  4840. TransitionEffect.opacity(0)
  4841. .animation({ duration: 220, curve: Curve.EaseOut })
  4842. }).then((dialogId: number) => {
  4843. this.deleteComponentId = dialogId
  4844. })
  4845. .catch((error: BusinessError) => {
  4846. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  4847. })
  4848. }
  4849. @Builder
  4850. deleteComptentBuilder(){
  4851. DeleteComptent({
  4852. selectedFiles:this.selectedFiles,
  4853. isPlaylistMode: this.modeType == 4,
  4854. playlistId: this.currentSongListID,
  4855. onCancel:()=>{
  4856. this.closeDeleteDialog(() => {
  4857. this.resetDeleteSelectionState()
  4858. })
  4859. },
  4860. onDeleteResult:(result: boolean)=>{
  4861. const deletedItems = [...this.selectedFiles]
  4862. this.closeDeleteDialog(() => {
  4863. this.resetDeleteSelectionState()
  4864. if(result){//如果删除成功,更新数据
  4865. if (this.modeType == 4) {
  4866. this.doSongListTask()
  4867. } else {
  4868. void this.removeDeletedLocalItemsLocally(deletedItems)
  4869. }
  4870. }
  4871. })
  4872. }
  4873. })
  4874. }
  4875. //多选移动文件
  4876. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  4877. Logger.info('onecold showCutDialogForMultipleFiles')
  4878. let mList: Array<string> = []
  4879. let rPath = this.rootPath
  4880. if (isCurrent) {
  4881. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  4882. rPath = this.currentPath
  4883. } else {
  4884. mList = Utility.getNameList(this.dirList);
  4885. rPath = this.rootPath
  4886. }
  4887. let dataBean = new BubbleBean();
  4888. dataBean.data = mList;
  4889. dataBean.color = this.themeColor
  4890. dataBean.onItemClick = (i) => {
  4891. const newDirPath = rPath + '/' + mList[i];
  4892. // Logger.info('newDirPath = ' + newDirPath)
  4893. this.selectedFiles.forEach((item) => {
  4894. const targetName = item.fileName || item.name;
  4895. const newPath = newDirPath + '/' + targetName;
  4896. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  4897. ToastUtil.showToast('移动成功');
  4898. this.table.deleteData(item, () => {
  4899. this.cache.delete(this.currentPath); // 删除原路径缓存
  4900. this.cache.delete(newDirPath); // 删除目标路径缓存
  4901. this.getSortedFiles(this.currentPath, true);
  4902. });
  4903. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  4904. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  4905. if (!Utility.isIsoByExtension(newPath)) {
  4906. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  4907. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  4908. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  4909. this.table.insert(newItem, (id: number) => {
  4910. //加入数据库
  4911. });
  4912. }
  4913. }
  4914. }).catch((error: Error) => {
  4915. console.error(error.message);
  4916. });
  4917. });
  4918. this.isMultiSelect = false
  4919. this.selectedFiles = [];
  4920. this.isAllSelected = false
  4921. XPopup.dismissTop();
  4922. };
  4923. let pup: XPopup
  4924. if (this.isDarkMode) {
  4925. pup = XPopup.Builder()
  4926. .setPopupPosition(PopupPosition.TOP)
  4927. .atView(viewId)
  4928. .setBackgroundColor(Color.Black)
  4929. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4930. .show();
  4931. } else {
  4932. pup = XPopup.Builder()
  4933. .setPopupPosition(PopupPosition.TOP)
  4934. .atView(viewId)
  4935. .setBackgroundColor(Color.White)
  4936. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4937. .show();
  4938. }
  4939. }
  4940. /**
  4941. * 加载所有歌单
  4942. */
  4943. async loadAllPlaylists() {
  4944. try {
  4945. this.allPlaylists = await this.playlistTable?.queryAllPlaylists()!
  4946. LogUtil.info('heanup Loaded playlists: ' + this.allPlaylists.length)
  4947. } catch (error) {
  4948. LogUtil.error('heaunp Failed to load playlists: ' + error.message)
  4949. }
  4950. }
  4951. /**
  4952. * 显示添加到歌单对话框
  4953. */
  4954. async openAddToPlaylistDialog(items: VideoItem | VideoItem[]) {
  4955. const songs = Array.isArray(items) ? items : [items]
  4956. const musicItems = songs.filter(song =>
  4957. song.type !== CommonConstants.TYPE_IS_DIR && !this.isIsoLocalFile(song))
  4958. if (musicItems.length === 0) {
  4959. ToastUtil.showToast('请选择要添加的歌曲')
  4960. return
  4961. }
  4962. // 加载最新的歌单列表
  4963. await this.loadAllPlaylists()
  4964. showAddToPlaylistDialog(
  4965. musicItems,
  4966. this.allPlaylists,
  4967. async (playlistId: string) => {
  4968. // 添加歌曲到歌单
  4969. const success = await this.playlistTable?.addSongsToPlaylist(playlistId,
  4970. musicItems.map(song => song.filePath))
  4971. if (success) {
  4972. const count = musicItems.length
  4973. ToastUtil.showToast(count > 1 ? `已添加 ${count} 首歌曲` : '已添加到歌单')
  4974. // 重新加载歌单列表
  4975. await this.loadAllPlaylists()
  4976. } else {
  4977. ToastUtil.showToast(musicItems.length > 1 ? '选中的歌曲已在该歌单中' : '歌曲已在该歌单中')
  4978. }
  4979. this.longItemFilePath = ''
  4980. if (this.isMultiSelect) {
  4981. this.isMultiSelect = false
  4982. this.isAllSelected = false
  4983. this.selectedFiles = []
  4984. }
  4985. },
  4986. () => {
  4987. LogUtil.info('取消添加到歌单')
  4988. },
  4989. () => {
  4990. // 创建新歌单
  4991. showCreatePlaylistDialog(
  4992. async (name: string, description: string, coverPath?: string) => {
  4993. const success = await this.playlistTable?.createPlaylist(name, description, coverPath)
  4994. if (success) {
  4995. ToastUtil.showToast('歌单创建成功')
  4996. // 重新加载歌单列表并打开添加对话框
  4997. await this.loadAllPlaylists()
  4998. await this.openAddToPlaylistDialog(musicItems)
  4999. } else {
  5000. ToastUtil.showToast('歌单创建失败')
  5001. }
  5002. },
  5003. () => {
  5004. // 取消创建歌单
  5005. }
  5006. )
  5007. }
  5008. )
  5009. }
  5010. private syncFavStateLocal(item: VideoItem, isFav: number): void {
  5011. const nextFavList = [...this.favList];
  5012. const favIndex = nextFavList.findIndex((favItem: VideoItem) => favItem.filePath === item.filePath);
  5013. if (isFav === 1) {
  5014. if (favIndex >= 0) {
  5015. nextFavList[favIndex].isFav = 1;
  5016. } else {
  5017. const favItem = cloneVideoItem(item);
  5018. favItem.isFav = 1;
  5019. nextFavList.push(favItem);
  5020. }
  5021. } else if (favIndex >= 0) {
  5022. nextFavList.splice(favIndex, 1);
  5023. }
  5024. this.favList = nextFavList;
  5025. item.isFav = isFav;
  5026. if (this.currentSong && this.currentSong.filePath === item.filePath) {
  5027. this.currentSong.isFav = isFav;
  5028. this.isFac = isFav === 1;
  5029. }
  5030. }
  5031. doFav(item: VideoItem) {
  5032. LogUtil.info('onecold doFav isFav=' + item.isFav)
  5033. let isFav = 0
  5034. if (Utility.getIsFav(this.favList, item)) {
  5035. isFav = 0
  5036. } else {
  5037. isFav = 1
  5038. }
  5039. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  5040. if (result) {
  5041. this.syncFavStateLocal(item, isFav);
  5042. if (isFav === 1) {
  5043. ToastUtil.showToast('收藏成功');
  5044. } else {
  5045. ToastUtil.showToast('取消收藏成功');
  5046. }
  5047. this.deleteCache(this.currentPath)
  5048. this.getFavList(false)
  5049. if (this.modeType === 0 && !this.isFavMusic) {
  5050. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  5051. this.getSortedFiles(this.currentPath)
  5052. }
  5053. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  5054. workerInstance.postMessage({ code: 3, data: this.context });
  5055. workerInstance.postMessage({ code: 4, data: this.context });
  5056. }
  5057. })
  5058. }
  5059. //多选复制文件
  5060. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  5061. console.log('onecold showCopyDialogForMultipleFiles');
  5062. let mList: Array<string> = []
  5063. let rPath = this.rootPath
  5064. if (isCurrent) {
  5065. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  5066. rPath = this.currentPath
  5067. } else {
  5068. mList = Utility.getNameList(this.dirList);
  5069. rPath = this.rootPath
  5070. }
  5071. let dataBean = new BubbleBean();
  5072. dataBean.data = mList;
  5073. dataBean.isCopy = true
  5074. dataBean.color = this.themeColor
  5075. dataBean.onItemClick = (i) => {
  5076. const newDirPath = rPath + '/' + mList[i];
  5077. // Logger.info('newDirPath = ' + newDirPath)
  5078. this.selectedFiles.forEach((item) => {
  5079. const targetName = item.fileName || item.name;
  5080. const newPath = newDirPath + '/' + targetName;
  5081. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  5082. ToastUtil.showToast('复制成功');
  5083. this.cache.delete(newDirPath); // 删除目标路径缓存
  5084. this.getSortedFiles(this.currentPath);
  5085. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  5086. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  5087. if (!Utility.isIsoByExtension(newPath)) {
  5088. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  5089. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  5090. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  5091. this.table.insert(newItem, (id: number) => {
  5092. //加入数据库
  5093. });
  5094. }
  5095. }
  5096. }).catch((error: Error) => {
  5097. console.error(error.message);
  5098. });
  5099. });
  5100. this.isMultiSelect = false
  5101. this.selectedFiles = [];
  5102. this.isAllSelected = false
  5103. XPopup.dismissTop();
  5104. };
  5105. let pup: XPopup
  5106. if (this.isDarkMode) {
  5107. pup = XPopup.Builder()
  5108. .setPopupPosition(PopupPosition.TOP)
  5109. .atView(viewId)
  5110. .setBackgroundColor(Color.Black)
  5111. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  5112. .show();
  5113. } else {
  5114. pup = XPopup.Builder()
  5115. .setPopupPosition(PopupPosition.TOP)
  5116. .atView(viewId)
  5117. .setBackgroundColor(Color.White)
  5118. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  5119. .show();
  5120. }
  5121. }
  5122. @Builder
  5123. private DirItem(item: VideoItem, index?: number) {
  5124. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5125. Row() {
  5126. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ?
  5127. this.getListImageSource(item, index ?? -1, this.coverThumbVersion) :
  5128. $r('app.media.music_group'))
  5129. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  5130. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  5131. .fillColor(this.themeColor)// .fontSize(33)
  5132. .alt($r('app.media.music_group'))
  5133. .borderRadius(this.isCoverRectangle?9:'100%')
  5134. .clip(true)
  5135. .shadow({
  5136. radius: 2,
  5137. type: ShadowType.BLUR,
  5138. color: 'on_primary'
  5139. })
  5140. .sourceSize({width:38, height:38})
  5141. .margin({ left: 20, top: 8, bottom: 8 })
  5142. Column() {
  5143. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  5144. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5145. .maxLines(1)// .width('88%')
  5146. .textOverflow({ overflow: TextOverflow.Ellipsis })//列表模式固定省略,避免滚动跑马灯开销
  5147. .margin({ left: 10, right: 20 })
  5148. .fontColor($r('app.color.text_color'))
  5149. Row() {
  5150. Text(`${this.getArtistSongCount(item.name)}首`)
  5151. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5152. .padding({ top: 8 })
  5153. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  5154. .fontColor($r('app.color.text_color'))
  5155. .margin({ left: 10 })
  5156. Text(`${this.getAlbumSongCount(item.name)}首`)
  5157. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5158. .padding({ top: 8 })
  5159. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  5160. .fontColor($r('app.color.text_color'))
  5161. .margin({ left: 10 })
  5162. Blank()
  5163. }
  5164. }
  5165. .height('100%')
  5166. .width('100%')
  5167. .justifyContent(FlexAlign.Center)
  5168. .alignItems(HorizontalAlign.Start)
  5169. Blank()
  5170. Checkbox({ name: 'dir_checkbox' + (index ?? -1) })
  5171. .select(this.isLocalItemSelected(item))
  5172. .selectedColor(this.themeColor)
  5173. .shape(CheckBoxShape.CIRCLE)
  5174. .opacity(this.isMultiSelect && this.isSelectableLocalItem(item) ? 1 : 0)
  5175. .visibility(this.isMultiSelect && this.isSelectableLocalItem(item) ? Visibility.Visible : Visibility.None)
  5176. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5177. .margin({ left: 20, top: 8, bottom: 8, right: 18 })
  5178. .width(22)
  5179. .height(22)
  5180. Image($r('app.media.arrow_right'))
  5181. .height(25)
  5182. .alignSelf(ItemAlign.Center)
  5183. .id(item.filePath)
  5184. .visibility(this.isShowAlphaBet || (this.isMultiSelect && this.isSelectableLocalItem(item)) ?
  5185. Visibility.None : Visibility.Visible)
  5186. }
  5187. }
  5188. .backgroundColor(Color.Transparent)
  5189. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  5190. .width('98%')
  5191. .reuseId('dir_item')
  5192. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  5193. .opacity(this.opacityItem) // 绑定透明度
  5194. }
  5195. private refreshDirVisibilitySettings(): void {
  5196. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  5197. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  5198. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  5199. }
  5200. isShowDir(dirName: string) {
  5201. if (dirName === undefined) {
  5202. return true
  5203. }
  5204. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  5205. return this.isShowSimi
  5206. }
  5207. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  5208. return this.isShowFAV
  5209. }
  5210. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  5211. return this.isShowHistory
  5212. }
  5213. return true
  5214. }
  5215. @State opacityItem: number = 1; // 控制透明度的状态变量
  5216. @Builder
  5217. private MusicItem(item: VideoItem, index?: number) {
  5218. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5219. Row() {
  5220. Stack() {
  5221. Image(this.getListImageSource(item, index ?? -1, this.coverThumbVersion))
  5222. .fillColor(this.themeColor)
  5223. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  5224. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  5225. .alt($r('app.media.alt'))
  5226. .borderRadius(this.isCoverRectangle?9:'100%')
  5227. .clip(true)
  5228. .draggable(false)
  5229. .sourceSize({width:38, height:38})
  5230. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  5231. // .autoResize(true) // 重采样,可减少内存占用
  5232. .opacity(this.opacityItem)// 绑定透明度
  5233. .margin({ left: 20 })
  5234. .shadow({
  5235. radius: this.isScrolling ? 0 : 10,
  5236. type: ShadowType.BLUR,
  5237. color: 'on_primary'
  5238. })
  5239. .onClick(()=>{
  5240. if (this.isMultiSelect) {
  5241. const isChecked = this.isLocalItemSelected(item);
  5242. this.handleFileSelection(item, !isChecked);
  5243. } else {
  5244. this.doPlay(item,index)
  5245. this.setShowPlayTrue()
  5246. }
  5247. })
  5248. }
  5249. Column() {
  5250. Column() {
  5251. Text(this.isShowFileName?item.fileName :item.name)
  5252. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5253. .maxLines(1)
  5254. .textOverflow({ overflow: this.isLongNameRoLL&&!this.isScrolling?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5255. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5256. $r('app.color.text_color'))
  5257. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5258. .padding({right:25})
  5259. .bindPopup(this.longItemFilePath === item.filePath, {
  5260. builder: this.MenuBuilder(item,index,item.filePath),
  5261. placement: Placement.Top,
  5262. // autoCancel: true,
  5263. mask: {color:'#33000000'},
  5264. // popupColor: Color.Yellow,
  5265. enableArrow: false,//是否显示箭头
  5266. showInSubWindow: false,
  5267. onStateChange: (e) => {
  5268. if (!e.isVisible) {
  5269. this.longItemFilePath = ''
  5270. this.tempLyricContent = ''
  5271. }
  5272. }
  5273. })
  5274. Row() {
  5275. Column(){
  5276. Text(item.md5Str?.includes('Lossless')?
  5277. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5278. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  5279. .padding({ top: 3,right:6,left:6,bottom:3 })
  5280. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5281. $r('app.color.text_color'))
  5282. .fontWeight(500)
  5283. .borderRadius(12)
  5284. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  5285. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5286. .backgroundColor('#FFC107')
  5287. }
  5288. .padding({ top: 8 })
  5289. Text(StrUtil.isEmpty(item.artist) ? item.duration
  5290. :this.twoFingerType==2? item.artist +' ' + item.duration
  5291. : item.artist + ' ' + item?.duration)
  5292. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5293. .padding({ top: 8 ,right:25})
  5294. .visibility(this.isShowFileName?Visibility.None:Visibility.Visible)
  5295. .maxLines(1)
  5296. .textOverflow({ overflow: TextOverflow.Ellipsis })//列表模式固定省略
  5297. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5298. Color.Gray)
  5299. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5300. Blank()
  5301. Text(this.isShowFileName?item.duration:item.size)
  5302. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5303. .padding({ top: 8 })
  5304. .maxLines(1)
  5305. .visibility(this.isShowFileName?Visibility.Visible:StrUtil.isEmpty(item.artist)
  5306. ? Visibility.Visible : Visibility.None)
  5307. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5308. Color.Gray)
  5309. .margin({ left: StrUtil.isEmpty(item.artist) ?0:10 })
  5310. }
  5311. }
  5312. .height('100%')
  5313. .width('100%')
  5314. .margin({ right: 10 })
  5315. .justifyContent(FlexAlign.Center)
  5316. .alignItems(HorizontalAlign.Start)
  5317. }
  5318. .height('100%')
  5319. .margin({ left: 5 })
  5320. .layoutWeight(1)
  5321. Column() {
  5322. Checkbox({ name: 'checkbox' + index })
  5323. .select(this.isLocalItemSelected(item))
  5324. .selectedColor(this.themeColor)
  5325. .shape(CheckBoxShape.CIRCLE)
  5326. .opacity(this.isMultiSelect ? 1 : 0)
  5327. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  5328. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5329. .margin({ left: 20, top: 8, bottom: 8,right:18 })
  5330. .width(22)
  5331. .height(22)
  5332. PlayingIndicator({
  5333. isActive: this.videoUrl === item.filePath && !this.isMultiSelect,
  5334. indicatorSize: 18,
  5335. marginRight: 20,
  5336. marginTop: 8,
  5337. marginBottom: 8
  5338. })
  5339. }
  5340. }
  5341. }
  5342. .gesture(LongPressGesture()
  5343. .onAction(async () => {
  5344. //如果是专辑和艺术家的首页,不能长按
  5345. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  5346. return
  5347. //如果是我的收藏 最近播放等也不能长按
  5348. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5349. item.name === LocalMusic.STR_HISTORY_MUSIC
  5350. )
  5351. return
  5352. this.longItemFilePath = item.filePath
  5353. this.tempLyricContent = this.supportsLocalAudioActions(item) ? await this.getLyricContent(item) : ''
  5354. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  5355. })
  5356. .onActionEnd((event: GestureEvent) => {
  5357. }))
  5358. .backgroundColor(Color.Transparent)
  5359. .width('100%')
  5360. .reuseId('file_item')
  5361. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  5362. }
  5363. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  5364. @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
  5365. buttons: [{ text: '文件夹' }, { text: '媒体库' },{ text: '艺术家' }, { text: '专辑' }],
  5366. direction: Direction.Ltr,
  5367. buttonPadding:{top:12,bottom:12},
  5368. backgroundColor: Color.Transparent,
  5369. fontSize:14,
  5370. selectedFontSize:15,
  5371. selectedFontColor:Color.White,
  5372. selectedBackgroundColor: this.themeColor,
  5373. localizedTextPadding: {
  5374. end: LengthMetrics.vp(20),
  5375. start: LengthMetrics.vp(20)
  5376. }
  5377. })
  5378. @State @Watch('capsuleSelectedIndexesChanged')tabSelectedIndexes: number[] = [0]
  5379. //当胶囊按钮的选择发生变化时调用此函数
  5380. capsuleSelectedIndexesChanged() {
  5381. this.modeType = this.tabSelectedIndexes[0]
  5382. }
  5383. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  5384. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  5385. isShowCoverHeader() {
  5386. if (!this.isShowHeader) {
  5387. return false
  5388. }
  5389. if (this.modeType == 0) {
  5390. if (this.isHistory || this.isFavMusic) {
  5391. return true
  5392. }
  5393. if (this.currentPath != this.rootPath) {
  5394. return true
  5395. }
  5396. }
  5397. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  5398. }
  5399. getCoverTitleBg(): ResourceStr | image.PixelMap {
  5400. if (this.isCustomizeBg) {
  5401. return ('rgba(255,255,255,0.2)')
  5402. }
  5403. if (this.isDarkMode) {
  5404. return $r('app.color.user_center_card_background')
  5405. }
  5406. return this.currentTitleCover
  5407. }
  5408. // 第二步:popup构造器定义弹框内容
  5409. @Builder popupBuilder() {
  5410. Column({ space: 2 }) {
  5411. Text('友情提示:双指缩放可以放大缩小列表')
  5412. .fontSize(12)
  5413. .fontWeight(FontWeight.Regular)
  5414. .fontColor($r('app.color.text_color'))
  5415. }
  5416. .justifyContent(FlexAlign.SpaceAround)
  5417. .width(220)
  5418. .height(55)
  5419. .padding(15)
  5420. }
  5421. //搜索功能的实现
  5422. @State searchText: string = ''; // 用户输入内容
  5423. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  5424. @State isSearchMode: boolean = false
  5425. @State searchHistoryItems: string[] = []
  5426. private readonly searchHistoryScope: string = 'local_music'
  5427. private loadSearchHistory(): void {
  5428. this.searchHistoryItems = SearchHistoryUtil.load(this.searchHistoryScope)
  5429. }
  5430. private saveSearchHistory(keyword: string): void {
  5431. this.searchHistoryItems = SearchHistoryUtil.save(this.searchHistoryScope, keyword)
  5432. }
  5433. private commitSearchHistory(keyword: string): void {
  5434. const normalized = keyword.trim()
  5435. if (normalized.length === 0) {
  5436. return
  5437. }
  5438. this.saveSearchHistory(normalized)
  5439. }
  5440. private applySearchHistory(keyword: string): void {
  5441. this.searchText = keyword
  5442. this.searchController.stopEditing()
  5443. void this.onSearchInput(keyword)
  5444. }
  5445. // 实时搜索逻辑(带防抖)
  5446. private async onSearchInput(value: string): Promise<void> {
  5447. this.searchText = value.trim();
  5448. Logger.info('heanup LocalMusic', `onSearchInput: keyword="${this.searchText}", mode=${this.modeType}`);
  5449. // 清空搜索文本时保持搜索态,只重置为不带关键词的结果列表
  5450. if (this.searchText === '') {
  5451. this.loadSearchHistory()
  5452. await this.resetAndLoadFirstPage();
  5453. return;
  5454. }
  5455. // 进入搜索模式
  5456. if (!this.isSearchMode) {
  5457. this.isSearchMode = true;
  5458. }
  5459. // 使用数据库分页查询(带搜索条件)
  5460. await this.resetAndLoadFirstPage();
  5461. }
  5462. @Builder
  5463. private SearchHistoryView(): void {
  5464. Column({ space: 10 }) {
  5465. Row() {
  5466. Text('搜索历史')
  5467. .fontSize(14)
  5468. .fontWeight(FontWeight.Medium)
  5469. .fontColor($r('app.color.text_color'))
  5470. Blank()
  5471. Button('清空')
  5472. .fontSize(12)
  5473. .fontColor(this.themeColor)
  5474. .backgroundColor(Color.Transparent)
  5475. .padding({ left: 8, right: 8, top: 4, bottom: 4 })
  5476. .onClick(() => {
  5477. SearchHistoryUtil.clear(this.searchHistoryScope)
  5478. this.searchHistoryItems = []
  5479. })
  5480. }
  5481. .width('100%')
  5482. Flex({ wrap: FlexWrap.Wrap }) {
  5483. ForEach(this.searchHistoryItems, (keyword: string) => {
  5484. Button(keyword)
  5485. .fontSize(12)
  5486. .fontColor($r('app.color.text_color'))
  5487. .backgroundColor(this.isDarkMode ? '#222222' : '#F2F3F5')
  5488. .borderRadius(16)
  5489. .margin({ right: 8, bottom: 8 })
  5490. .padding({ left: 12, right: 12, top: 8, bottom: 8 })
  5491. .onClick(() => {
  5492. this.applySearchHistory(keyword)
  5493. })
  5494. })
  5495. }
  5496. .width('100%')
  5497. }
  5498. .width('100%')
  5499. .padding({ left: 16, right: 16, top: 10, bottom: 10 })
  5500. }
  5501. @State dragItem: number = -1
  5502. @State scaleItem: number = -1
  5503. @State neighborItem: number = -1
  5504. @State neighborScale: number = -1
  5505. @State offsetY: number = 0
  5506. private dragRefOffset: number = 0
  5507. private ITEM_INTV: number = 78
  5508. scaleSelect(item: number): number {
  5509. if (this.scaleItem === item) {
  5510. return 1.05
  5511. } else if (this.neighborItem === item) {
  5512. return this.neighborScale
  5513. } else {
  5514. return 1
  5515. }
  5516. }
  5517. itemMove(index: number, newIndex: number): void {
  5518. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  5519. return;
  5520. }
  5521. let tmp = this.videoLocalList.splice(index, 1);
  5522. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  5523. this.dataSource.pushArrayData(this.videoLocalList)
  5524. if(this.modeType==4&&this.playlistTable){
  5525. updateAllSongsSortOrder(this.playlistTable, this.videoLocalList,this.currentSongListID)
  5526. }
  5527. }
  5528. //瀑布流布局 支持双指缩放
  5529. @State columns: number = 2;
  5530. @State waterFlowScale: number = 1;
  5531. @State imageScale: number = 1;
  5532. @State waterFlowOpacity: number = 1;
  5533. @State waterFlowSnapshot: image.PixelMap | undefined = undefined;
  5534. private columnChanged: boolean = false;
  5535. private oldColumn: number = this.columns;
  5536. private pinchTime: number = 0;
  5537. // 根据缩放阈值改变列数,触发WaterFlow重新布局
  5538. changeColumns(scale: number): void {
  5539. if (scale > (this.columns / (this.columns - 0.5)) && this.columns > 1) {
  5540. this.columns--;
  5541. this.columnChanged = true;
  5542. } else if (scale < 1 && this.columns < 4) {
  5543. this.columns++;
  5544. this.columnChanged = true;
  5545. }
  5546. }
  5547. @Builder
  5548. getWaterView(){
  5549. Scroll(this.scroller) {
  5550. Column() {
  5551. Blank().height(this.topSafeHeight + 55)
  5552. WaterFlow({
  5553. scroller:this.waterScroller,
  5554. layoutMode: WaterFlowLayoutMode.SLIDING_WINDOW
  5555. }) {
  5556. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5557. FlowItem() {
  5558. this.MusicWaterCardItem(item,index)
  5559. }
  5560. .width('100%')
  5561. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  5562. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  5563. {
  5564. preview: MenuPreviewMode.IMAGE
  5565. })
  5566. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  5567. {
  5568. preview: MenuPreviewMode.IMAGE
  5569. })
  5570. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5571. }
  5572. // .columnsTemplate('repeat(auto-fit, 160)')
  5573. .id('waterflow') // 设置id用于截图
  5574. .columnsTemplate('1fr '.repeat(this.columns)) // 动态生成列模板,如:'1fr 1fr 1fr'表示3列等宽
  5575. .columnsGap(12) // 列间距
  5576. .rowsGap(this.columns >= 4 ? 8 : (this.columns == 3 ? 10 : 14)) // 行间距
  5577. .cachedCount(this.columns >= 4 ? 2 : (this.columns == 3 ? 3 : 4))
  5578. .padding({bottom:this.bottomBarHeight+10})
  5579. .scrollBar(BarState.Off)
  5580. // .fadingEdge(true, { fadingEdgeLength: LengthMetrics.vp(38) })
  5581. // 效果:只有向上或者向下滑动到顶部时才会有弹簧回弹效果
  5582. .edgeEffect(EdgeEffect.None)
  5583. .width('90%')
  5584. .height('100%')
  5585. .opacity(this.waterFlowOpacity)
  5586. .scale({
  5587. x: this.waterFlowScale,
  5588. y: this.waterFlowScale,
  5589. centerX: 0,
  5590. centerY: 0
  5591. })
  5592. .onReachEnd(() => {
  5593. if(this.modeType === 4 )
  5594. return;
  5595. // 触底加载下一页
  5596. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  5597. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  5598. return;
  5599. }
  5600. if (this.hasMoreData && !this.isLoadingPage && !this.isPagingTransition) {
  5601. this.scheduleLoadNextPage();
  5602. }
  5603. })
  5604. .onAppear(() => {
  5605. this.scroller.scrollEdge(Edge.Top)
  5606. })
  5607. .nestedScroll({
  5608. scrollForward: NestedScrollMode.PARENT_FIRST,
  5609. scrollBackward: NestedScrollMode.SELF_FIRST
  5610. })
  5611. .priorityGesture(
  5612. PinchGesture()
  5613. .onActionStart((event: GestureEvent) => {
  5614. // 双指捏合手势识别成功时截图
  5615. this.pinchTime = event.timestamp;
  5616. this.columnChanged = false;
  5617. this.oldColumn = this.columns;
  5618. this.getUIContext().getComponentSnapshot().get('waterflow', (error: Error, pixmap: image.PixelMap) => {
  5619. if (error) {
  5620. console.info('error:' + JSON.stringify(error));
  5621. return;
  5622. }
  5623. this.waterFlowSnapshot = pixmap;
  5624. if ((this.oldColumn === 1 ) && event.scale > 1|| (this.oldColumn === 4 && event.scale < 1)) {
  5625. console.info("onecold onActionStart oldColumn:" + this.oldColumn)
  5626. if (this.oldColumn ===4) {
  5627. this.twoFingerType =3
  5628. this.isGridMusic = true
  5629. }else if (this.oldColumn ===1) {
  5630. this.twoFingerType =1
  5631. this.isGridMusic = false
  5632. }
  5633. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  5634. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5635. return;
  5636. }
  5637. })
  5638. })
  5639. .onActionUpdate((event: GestureEvent) => {
  5640. // 手势更新:处理缩放逻辑和视觉效果
  5641. // 边界限制:防止超出列数范围时继续缩放
  5642. if ((this.oldColumn === 1 && event.scale > 1) || (this.oldColumn === 4 && event.scale < 1)) {
  5643. return;
  5644. }
  5645. // 节流处理:避免过于频繁的更新,提升性能
  5646. if (event.timestamp - this.pinchTime < 10000000) {
  5647. return;
  5648. }
  5649. this.pinchTime = event.timestamp;
  5650. this.waterFlowScale = event.scale;
  5651. this.imageScale = event.scale;
  5652. // 根据缩放比例设置WaterFlow透明度
  5653. this.waterFlowOpacity = (this.waterFlowScale > 1) ? (this.waterFlowScale - 1) : (1 - this.waterFlowScale);
  5654. this.waterFlowOpacity *= 3;
  5655. if (!this.columnChanged) {
  5656. this.changeColumns(event.scale);
  5657. }
  5658. // 列数改变后的缩放比例调整:避免出现空白区域
  5659. if (this.columnChanged) {
  5660. this.waterFlowScale = this.imageScale * this.columns / this.oldColumn;
  5661. // 限制缩放范围,确保视觉效果自然
  5662. if (event.scale < 1) {
  5663. this.waterFlowScale = this.waterFlowScale > 1 ? this.waterFlowScale : 1;
  5664. } else {
  5665. this.waterFlowScale = this.waterFlowScale < 1 ? this.waterFlowScale : 1;
  5666. }
  5667. }
  5668. })
  5669. .onActionEnd((event: GestureEvent) => {
  5670. // 手势结束:执行归位动画并保存状态
  5671. // 执行归位动画:平滑过渡到正常状态
  5672. this.getUIContext()?.animateTo({ duration: 300 }, () => {
  5673. this.waterFlowScale = 1;
  5674. this.waterFlowOpacity = 1;
  5675. })
  5676. // 持久化保存当前列数:下次启动时恢复
  5677. PreferencesUtil.putSync('lastColumns', this.columns);
  5678. })
  5679. )
  5680. .onScrollFrameBegin((offset: number) => {
  5681. this.markGridWaterScrollingActive()
  5682. // 获取当前滚动偏移量
  5683. const currentOffsetY = this.waterScroller.currentOffset().yOffset;
  5684. this.tryTriggerLoadForWaterByOffset(currentOffsetY)
  5685. this.updateTitleBarByScrollOffset(currentOffsetY)
  5686. return { offsetRemain: offset };
  5687. })
  5688. }
  5689. }
  5690. .scrollBar(BarState.Off)
  5691. }
  5692. //瀑布流卡片布局
  5693. @Builder
  5694. private MusicWaterCardItem(item: VideoItem, index: number) {
  5695. Button({ type: ButtonType.Normal, stateEffect: false }) {
  5696. Stack() {
  5697. Column() {
  5698. Image(this.getGridWaterImageSource(item, index, true, this.coverThumbVersion))
  5699. .backgroundImageSize(ImageSize.Auto)
  5700. .borderRadius({
  5701. topLeft: 12,
  5702. topRight : 12,
  5703. bottomLeft: 0,
  5704. bottomRight: 0
  5705. })
  5706. .draggable(false)// 禁止长按手势拖动
  5707. .autoResize(true) // 重采样,可减少内存占用
  5708. .sourceSize({
  5709. width: this.getCoverThumbTargetSize(true),
  5710. height: this.getCoverThumbTargetSize(true)
  5711. })
  5712. .width('100%')
  5713. .height('auto')
  5714. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  5715. .objectFit(ImageFit.Cover)
  5716. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  5717. height: '99%' ,
  5718. dragBar: true,
  5719. onDisappear: () => {
  5720. this.longItemFilePath = '';
  5721. this.tempLyricContent = ''
  5722. },
  5723. showClose: true,
  5724. preferType: SheetType.CENTER ,
  5725. title: { title: '编辑标签' }
  5726. })
  5727. .draggable(false)
  5728. .opacity(this.opacityItem)// 绑定透明度
  5729. .margin({
  5730. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5731. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5732. })
  5733. Column() {
  5734. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  5735. .fontSize(this.columns == 4 ||this.columns==3? 12 : this.columns == 2 ? 15 : 18)
  5736. .maxLines(1)
  5737. .fontWeight(FontWeight.Bold)
  5738. .textOverflow({ overflow: this.isLongNameRoLL&&!this.isScrolling?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5739. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  5740. height: '95%',
  5741. dragBar: true,
  5742. showClose: true,
  5743. onDisappear: () => {
  5744. this.longItemFilePathDetail = '';
  5745. },
  5746. blurStyle:BlurStyle.Thin,
  5747. backgroundColor:Color.Transparent,
  5748. preferType: SheetType.CENTER ,
  5749. title: { title: '详情' }
  5750. })
  5751. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5752. $r('app.color.text_color'))
  5753. Column() {
  5754. Text(`${this.getArtistSongCount(item.name)}首`)
  5755. .fontSize(11)
  5756. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  5757. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5758. .fontColor($r('app.color.text_color'))
  5759. Text(`${this.getAlbumSongCount(item.name)}首`)
  5760. .fontSize(11)
  5761. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  5762. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5763. .fontColor($r('app.color.text_color'))
  5764. Row(){
  5765. Column(){
  5766. Text(item.md5Str?.includes('Lossless')?
  5767. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5768. .fontSize(this.columns == 4 ||this.columns==3? 8 : this.columns == 2 ? 9 : 11)
  5769. .padding({ top: 3,right:6,left:6,bottom:3 })
  5770. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5771. $r('app.color.text_color'))
  5772. .fontWeight(500)
  5773. .borderRadius(12)
  5774. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5775. .backgroundColor('#FFC107')
  5776. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  5777. }
  5778. .margin({ top: 2 ,right:6})
  5779. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  5780. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  5781. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  5782. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 13)
  5783. .maxLines(1)
  5784. .textOverflow({ overflow: TextOverflow.Ellipsis })//瀑布流固定省略
  5785. .margin({ top: 2})
  5786. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  5787. || item.type == CommonConstants.TYPE_IS_ALBUM
  5788. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5789. .fontWeight(FontWeight.Medium)
  5790. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5791. $r('app.color.text_color'))
  5792. }
  5793. }
  5794. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  5795. }
  5796. .height(this.columns == 4 ||this.columns==3? item.type==CommonConstants.TYPE_IS_DIR?30:40
  5797. : this.columns == 2 ? (item.type==CommonConstants.TYPE_IS_DIR?38:48) :
  5798. (item.type==CommonConstants.TYPE_IS_DIR?48:58))
  5799. .width('100%')
  5800. .justifyContent(FlexAlign.Center)
  5801. .margin({
  5802. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5803. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5804. })
  5805. }
  5806. .width('100%')
  5807. .borderRadius(12)
  5808. .backgroundColor($r('app.color.com_bg'))
  5809. Checkbox({ name: 'checkbox' + index })
  5810. .select(this.isLocalItemSelected(item))
  5811. .selectedColor(this.themeColor)
  5812. .shape(CheckBoxShape.CIRCLE)
  5813. .opacity(this.isMultiSelect && this.isSelectableLocalItem(item) ? 1 : 0)
  5814. .visibility(this.isMultiSelect && this.isSelectableLocalItem(item) ? Visibility.Visible :
  5815. Visibility.None)
  5816. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5817. .margin({ left: 20, top: 8, bottom: 8 })
  5818. .width(38)
  5819. .height(38)
  5820. }
  5821. }
  5822. .backgroundColor(Color.Transparent)
  5823. .width('100%')
  5824. .height('auto')
  5825. .padding({top:2})
  5826. .shadow({
  5827. radius: this.isScrolling ? 0 : 8,
  5828. type: ShadowType.BLUR,
  5829. color: 'on_primary'
  5830. })
  5831. .reuseId('card_item')
  5832. .onClick(() => {
  5833. if (this.isMultiSelect) {
  5834. if (this.isSelectableLocalItem(item)) {
  5835. const isChecked = this.isLocalItemSelected(item);
  5836. this.handleFileSelection(item, !isChecked);
  5837. }
  5838. return
  5839. }
  5840. this.doPlay(item, index)
  5841. })
  5842. }
  5843. // Grid布局的开始
  5844. private dragRefOffSetX: number = 0;
  5845. private dragRefOffSetY: number = 0;
  5846. private FIX_VP_X: number = 180;
  5847. private FIX_VP_Y: number = 84;
  5848. isDraggable(index: number): boolean {
  5849. return index >= 0;
  5850. }
  5851. getRowEnd(item: number) {
  5852. if (item.toString() === '0') {
  5853. return 1;
  5854. } else {
  5855. return 0;
  5856. }
  5857. }
  5858. isInLeft(index: number) {
  5859. return index % 2 == 0;
  5860. }
  5861. down(index: number): void {
  5862. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  5863. return;
  5864. }
  5865. this.offsetY -= this.FIX_VP_Y;
  5866. this.dragRefOffSetY += this.FIX_VP_Y;
  5867. this.itemMove(index, index + 1);
  5868. }
  5869. up(index: number): void {
  5870. if (!this.isDraggable(index - 2)) {
  5871. return;
  5872. }
  5873. this.offsetY += this.FIX_VP_Y;
  5874. this.dragRefOffSetY -= this.FIX_VP_Y;
  5875. this.itemMove(index, index - 1);
  5876. }
  5877. left(index: number): void {
  5878. if (this.isInLeft(index)) {
  5879. return;
  5880. }
  5881. if (!this.isDraggable(index - 1)) {
  5882. return;
  5883. }
  5884. this.offsetX += this.FIX_VP_X;
  5885. this.dragRefOffSetX -= this.FIX_VP_X;
  5886. this.itemMove(index, index - 1)
  5887. }
  5888. right(index: number): void {
  5889. if (!this.isInLeft(index)) {
  5890. return;
  5891. }
  5892. if (!this.isDraggable(index + 1)) {
  5893. return;
  5894. }
  5895. this.offsetX -= this.FIX_VP_X;
  5896. this.dragRefOffSetX += this.FIX_VP_X;
  5897. this.itemMove(index, index + 1)
  5898. }
  5899. private scroller: Scroller = new Scroller();
  5900. private waterScroller: Scroller = new Scroller();
  5901. private startIndex: number = 0
  5902. private endIndex: number = 0
  5903. @State scaleValue: number = 1
  5904. @State pinchValue: number = 1
  5905. layoutOptionsForHeader: GridLayoutOptions = {
  5906. regularSize: [1, 1], // 只支持[1, 1]
  5907. irregularIndexes: [0], // 索引为0的GridItem占用一行
  5908. };
  5909. @Builder
  5910. getGridView() {
  5911. Grid(this.scroller, this.layoutOptionsForHeader) {
  5912. GridItem() {
  5913. Column(){
  5914. Blank().height(this.topSafeHeight + 45)
  5915. }
  5916. }
  5917. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5918. GridItem() {
  5919. Stack() {
  5920. this.MusicItemGrid(item, index)
  5921. }
  5922. }
  5923. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  5924. {
  5925. preview: MenuPreviewMode.IMAGE
  5926. })
  5927. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  5928. {
  5929. preview: MenuPreviewMode.IMAGE
  5930. })
  5931. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.9, y: 0.9 }).animation({ duration: 300 }),
  5932. // TransitionEffect.scale({ x: 0, y: 0 })))
  5933. .clickEffect({ level: ClickEffectLevel.LIGHT })
  5934. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  5935. .zIndex(this.dragItem === index ? 1 : 0)
  5936. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  5937. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5938. }
  5939. .width('94%')
  5940. .height('100%')
  5941. .editMode(true)
  5942. .padding({bottom:this.bottomBarHeight+this.bottomSafeHeight+10})
  5943. .reuseId('grid_item')
  5944. .layoutWeight(1)
  5945. .scrollBar(BarState.Off)
  5946. .supportAnimation(false)
  5947. .onReachEnd(() => {
  5948. if(this.modeType === 4 )
  5949. return;
  5950. // 触底加载下一页
  5951. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  5952. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  5953. return;
  5954. }
  5955. if (this.hasMoreData && !this.isLoadingPage && !this.isPagingTransition) {
  5956. this.scheduleLoadNextPage();
  5957. }
  5958. })
  5959. .cachedCount(this.twoFingerType==1?1:this.twoFingerType==2?2:2)
  5960. .columnsTemplate(
  5961. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  5962. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  5963. )
  5964. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  5965. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  5966. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  5967. .gesture(PinchGesture({ fingers: 2 })
  5968. .onActionEnd((event: GestureEvent) => {
  5969. this.setGridTwoFingers()
  5970. })
  5971. .onActionUpdate(e => {
  5972. this.scaleValue = this.pinchValue * e.scale
  5973. })
  5974. .onActionStart(e => {
  5975. }))
  5976. .enableScrollInteraction(true)
  5977. .onScrollIndex((start: number, end: number) => {
  5978. this.startIndex = start
  5979. this.endIndex = end
  5980. this.gridVisibleStart = start
  5981. this.gridVisibleEnd = end
  5982. this.lastVisibleEndIndex = end
  5983. this.warmupGridWaterVisibleThumbs(start, end, false)
  5984. const now = Date.now()
  5985. const pagingDelta = this.gridScrollLastPagingEnd >= 0 ? Math.abs(end - this.gridScrollLastPagingEnd) : 999
  5986. if (pagingDelta >= 2 || now - this.gridScrollPagingCheckAt >= 40) {
  5987. this.gridScrollPagingCheckAt = now
  5988. this.gridScrollLastPagingEnd = end
  5989. this.tryTriggerLoadNextPageByScroll(end)
  5990. }
  5991. })
  5992. .onScrollFrameBegin((offset: number) => {
  5993. this.markGridWaterScrollingActive()
  5994. const currentOffsetY = this.scroller.currentOffset().yOffset;
  5995. this.updateTitleBarByScrollOffset(currentOffsetY)
  5996. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  5997. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  5998. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  5999. if (this.isScrollHide) {
  6000. this.setBarHeightHide2(offset)
  6001. } else {
  6002. this.setBarHeightNormal()
  6003. }
  6004. } else {
  6005. this.setBarHeightHide(offset)
  6006. }
  6007. return { offsetRemain: offset };
  6008. })
  6009. }
  6010. @State targetFile: string = '';
  6011. setGridTwoFingers() {
  6012. this.pinchValue = this.scaleValue;
  6013. Logger.info('this.pinchValue = ' + this.pinchValue);
  6014. if (this.pinchValue >= 1) {
  6015. this.twoFingerType++
  6016. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  6017. if(this.twoFingerType >= 4){
  6018. this.twoFingerType = 4//切换成瀑布流
  6019. this.columns = 4
  6020. }
  6021. } else {
  6022. this.twoFingerType--
  6023. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  6024. if (this.twoFingerType < 1) {
  6025. this.twoFingerType = 3
  6026. this.isGridMusic = false
  6027. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6028. }
  6029. }
  6030. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  6031. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6032. this.pinchValue = 1;
  6033. this.scaleValue = 1;
  6034. }
  6035. @State longItemFilePath: string = ''
  6036. @State tempLyricContent: string = ''
  6037. @State editingItem: VideoItem | null = null
  6038. @Builder
  6039. private MusicItemGrid(item: VideoItem, index: number) {
  6040. Button({ type: ButtonType.Normal, stateEffect: false }) {
  6041. Stack() {
  6042. Column() {
  6043. Image(this.getGridWaterImageSource(item, index, false, this.coverThumbVersion))
  6044. .height(this.getGridHeight())
  6045. .width(this.getGridWight())
  6046. .draggable(false)
  6047. .autoResize(true) // 重采样,可减少内存占用
  6048. .sourceSize({
  6049. width: this.getCoverThumbTargetSize(false),
  6050. height: this.getCoverThumbTargetSize(false)
  6051. })
  6052. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  6053. .clip(true)
  6054. .borderRadius({
  6055. topLeft: 12,
  6056. topRight: 12,
  6057. bottomLeft: 0,
  6058. bottomRight: 0
  6059. })
  6060. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  6061. height: '99%' ,
  6062. dragBar: true,
  6063. onDisappear: () => {
  6064. this.longItemFilePath = '';
  6065. this.tempLyricContent = ''
  6066. },
  6067. showClose: true,
  6068. preferType: SheetType.CENTER ,
  6069. title: { title: '编辑标签' }
  6070. })
  6071. .draggable(false)
  6072. .opacity(this.opacityItem)// 绑定透明度
  6073. .margin({
  6074. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  6075. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  6076. })
  6077. Column() {
  6078. Text(this.isShowFileName&&this.modeType !== 2&&this.modeType !== 3&&
  6079. item.type!=CommonConstants.TYPE_IS_DIR?item.fileName :item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  6080. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  6081. .maxLines(1)
  6082. .fontWeight(FontWeight.Bold)
  6083. .textOverflow({ overflow: this.isLongNameRoLL&&!this.isScrolling?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  6084. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  6085. height: '100%',
  6086. dragBar: true,
  6087. showClose: true,
  6088. onDisappear: () => {
  6089. this.longItemFilePathDetail = '';
  6090. },
  6091. blurStyle:BlurStyle.Thin,
  6092. backgroundColor:Color.Transparent,
  6093. preferType: SheetType.CENTER ,
  6094. title: { title: '详情' }
  6095. })
  6096. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6097. $r('app.color.text_color'))
  6098. Column() {
  6099. Text(`${this.getArtistSongCount(item.name)}首`)
  6100. .fontSize(11)
  6101. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  6102. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  6103. .fontColor($r('app.color.text_color'))
  6104. Text(`${this.getAlbumSongCount(item.name)}首`)
  6105. .fontSize(11)
  6106. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  6107. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  6108. .fontColor($r('app.color.text_color'))
  6109. Row(){
  6110. Column(){
  6111. Text(item.md5Str?.includes('Lossless')?
  6112. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  6113. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  6114. .padding({ top: 3,right:6,left:6,bottom:3 })
  6115. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6116. $r('app.color.text_color'))
  6117. .fontWeight(500)
  6118. .borderRadius(12)
  6119. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  6120. .backgroundColor('#FFC107')
  6121. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  6122. }
  6123. .margin({ top: 2 ,right:6})
  6124. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  6125. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  6126. Text(this.isShowFileName?item.duration:StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  6127. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  6128. .maxLines(1)
  6129. .textOverflow({ overflow: TextOverflow.Ellipsis })//Grid固定省略
  6130. .margin({ top: 2})
  6131. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  6132. || item.type == CommonConstants.TYPE_IS_ALBUM
  6133. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6134. .fontWeight(FontWeight.Medium)
  6135. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6136. $r('app.color.text_color'))
  6137. }
  6138. }
  6139. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  6140. }
  6141. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  6142. .width(this.getGridWight())
  6143. .justifyContent(FlexAlign.Center)
  6144. .margin({
  6145. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  6146. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  6147. })
  6148. }
  6149. .width(this.getGridWight())
  6150. .borderRadius(12)
  6151. .backgroundColor($r('app.color.com_bg'))
  6152. Checkbox({ name: 'checkbox' + index })
  6153. .select(this.isLocalItemSelected(item))
  6154. .selectedColor(this.themeColor)
  6155. .shape(CheckBoxShape.CIRCLE)
  6156. .opacity(this.isMultiSelect && this.isSelectableLocalItem(item) ? 1 : 0)
  6157. .visibility(this.isMultiSelect && this.isSelectableLocalItem(item) ? Visibility.Visible :
  6158. Visibility.None)
  6159. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  6160. .margin({ left: 20, top: 8, bottom: 8 })
  6161. .width(38)
  6162. .height(38)
  6163. }
  6164. }
  6165. .backgroundColor(Color.Transparent)
  6166. .width('100%')
  6167. .padding({ top: 15 })
  6168. .height(this.getGridAllHeight())
  6169. .onClick(() => {
  6170. if (this.isMultiSelect) {
  6171. if (this.isSelectableLocalItem(item)) {
  6172. const isChecked = this.isLocalItemSelected(item);
  6173. this.handleFileSelection(item, !isChecked);
  6174. }
  6175. return
  6176. }
  6177. this.doPlay(item, index)
  6178. })
  6179. }
  6180. getGridAllHeight() {
  6181. let heightG = 222
  6182. switch (this.twoFingerType) {
  6183. case 1:
  6184. heightG = 143
  6185. break;
  6186. case 2:
  6187. heightG = 178
  6188. break;
  6189. case 3:
  6190. heightG = 222
  6191. break;
  6192. }
  6193. return heightG
  6194. }
  6195. getGridHeight() {
  6196. let heightG = 150
  6197. switch (this.twoFingerType) {
  6198. case 1:
  6199. heightG = 80
  6200. break;
  6201. case 2:
  6202. heightG = 110
  6203. break;
  6204. case 3:
  6205. heightG = 150
  6206. break;
  6207. }
  6208. return heightG
  6209. }
  6210. getGridWight() {
  6211. let wightG = 158
  6212. switch (this.twoFingerType) {
  6213. case 1:
  6214. wightG = 80
  6215. break;
  6216. case 2:
  6217. wightG = 110
  6218. break;
  6219. case 3:
  6220. wightG = 158
  6221. break;
  6222. }
  6223. return wightG
  6224. }
  6225. @State isShowDetail:boolean = false
  6226. @State longItemFilePathDetail:string =''
  6227. @Builder
  6228. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  6229. if(
  6230. ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  6231. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  6232. item.name === LocalMusic.STR_HISTORY_MUSIC)
  6233. ){
  6234. //如果是专辑和艺术家的首页,不能长按
  6235. //如果是我的收藏 最近播放等也不能长按
  6236. }else{
  6237. Scroll() {
  6238. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  6239. Menu() {
  6240. MenuItem({
  6241. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  6242. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  6243. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  6244. })
  6245. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6246. .onClick(() => {
  6247. if (item) {
  6248. this.doFav(item)
  6249. }
  6250. this.longItemFilePath = ''
  6251. })
  6252. MenuItem({
  6253. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  6254. content: '下一首播放'
  6255. })
  6256. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6257. .onClick(() => {
  6258. this.addToNextPlay(item);
  6259. this.longItemFilePath = ''
  6260. })
  6261. MenuItem({
  6262. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  6263. content: '添加到歌单'
  6264. })
  6265. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6266. .onClick(async () => {
  6267. this.longItemFilePath = ''
  6268. await this.openAddToPlaylistDialog(item)
  6269. })
  6270. MenuItem({
  6271. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  6272. content: '编辑标签'
  6273. })
  6274. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  6275. height: '99%',
  6276. dragBar: true,
  6277. showClose: true,
  6278. preferType: SheetType.CENTER ,
  6279. title: { title: '编辑标签' }
  6280. })
  6281. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6282. .onClick(async() => {
  6283. this.initEditFields(item)
  6284. this.tempLyricContent = await this.getLyricContent(item);
  6285. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  6286. this.lyricConStr = this.tempLyricContent
  6287. }
  6288. if(this.isGridMusic||this.twoFingerType==4){
  6289. this.longItemFilePath = item.filePath
  6290. }else{
  6291. this.isShowEdit = !this.isShowEdit;
  6292. }
  6293. })
  6294. MenuItem({
  6295. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  6296. content: $r('app.string.select_all')
  6297. })
  6298. .onClick(() => {
  6299. this.longItemFilePath = ''
  6300. this.enterLocalMultiSelect(item)
  6301. })
  6302. MenuItem({
  6303. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  6304. content: '提取ISO文件'
  6305. })
  6306. .visibility(this.isIsoLocalFile(item) ? Visibility.Visible : Visibility.None)
  6307. .onClick(async () => {
  6308. this.longItemFilePath = ''
  6309. await this.openIsoArchiveDialog(item)
  6310. })
  6311. MenuItem({
  6312. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.cut')),
  6313. content: $r('app.string.edit_audio')
  6314. })
  6315. .bindContentCover($$this.isEditAudio, this.EditAudioBuilder(item), {
  6316. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6317. })
  6318. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6319. .onClick(() => {
  6320. this.isEditAudio = !this.isEditAudio
  6321. })
  6322. MenuItem({
  6323. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  6324. content: $r('app.string.extract_accompaniment')
  6325. })
  6326. .bindContentCover($$this.isExtractAcc, this.ExtractAccBuilder(item), {
  6327. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6328. })
  6329. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6330. .onClick(() => {
  6331. if (!Utility.isNoble()) {
  6332. this.showVipDialog()
  6333. return
  6334. }
  6335. this.isExtractAcc = !this.isExtractAcc
  6336. })
  6337. MenuItem({
  6338. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.repeat')),
  6339. content: $r('app.string.converter_audio')
  6340. })
  6341. .bindContentCover($$this.isConverter, this.ConverterBuilder(item), {
  6342. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6343. })
  6344. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6345. .onClick(() => {
  6346. if (!Utility.isNoble()) {
  6347. this.showVipDialog()
  6348. return
  6349. }
  6350. this.isConverter = !this.isConverter
  6351. })
  6352. // MenuItem({
  6353. // symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.ai_edit')),
  6354. // content: $r('app.string.vocal_separation')
  6355. // })
  6356. // .bindContentCover($$this.isAIVoiceSeparation, this.AiBuilder(item), {
  6357. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6358. // })
  6359. // .onClick(() => {
  6360. // this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  6361. // })
  6362. MenuItem({
  6363. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_counterclockwise_clock')),
  6364. content: $r('app.string.change_tone')
  6365. })
  6366. .bindContentCover($$this.isChangeTone, this.ChangeToneBuilder(item), {
  6367. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6368. })
  6369. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6370. .onClick(() => {
  6371. this.isChangeTone = !this.isChangeTone
  6372. })
  6373. if(Utility.isVideoByExtension(item.filePath)){
  6374. MenuItem({
  6375. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.identify_song')),
  6376. content: $r('app.string.extract_audio')
  6377. })
  6378. .bindContentCover($$this.isExtractAudio, this.extractAudioFromVideoBuilder(item), {
  6379. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6380. })
  6381. .onClick(() => {
  6382. this.isExtractAudio = !this.isExtractAudio
  6383. })
  6384. }
  6385. MenuItem({
  6386. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.phone')),
  6387. content: $r('app.string.set_ring')
  6388. })
  6389. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6390. .onClick(async () => {
  6391. await PermissionUtil.activatePermission(item.filePath)
  6392. // if(item.filePath.includes(this.packName)){
  6393. setRingTone(this.context, item.filePath,item.name)
  6394. // }else{
  6395. // ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限设置铃声')
  6396. // }
  6397. this.longItemFilePath = ''
  6398. })
  6399. MenuItem({
  6400. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  6401. content: $r('app.string.rename')
  6402. })
  6403. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  6404. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  6405. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  6406. .onClick(() => {
  6407. this.showReNameDialog(item, index + '', filePath)
  6408. this.longItemFilePath = ''
  6409. })
  6410. MenuItem({
  6411. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  6412. content: $r('app.string.delete')
  6413. })
  6414. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  6415. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  6416. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  6417. .onClick(() => {
  6418. this.selectSingleItemForDelete(item)
  6419. this.showWarnIsDelete()
  6420. this.longItemFilePath = ''
  6421. })
  6422. MenuItem({
  6423. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  6424. content: $r('app.string.detail')
  6425. })
  6426. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  6427. height:'100%',
  6428. dragBar: true,
  6429. showClose: true,
  6430. blurStyle:BlurStyle.Thin,
  6431. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6432. backgroundColor:Color.Transparent,
  6433. title: { title: '详情信息' }
  6434. })
  6435. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6436. .onClick(() => {
  6437. if(this.isGridMusic||this.twoFingerType==4){
  6438. this.longItemFilePathDetail = item.filePath
  6439. }else{
  6440. this.isShowDetail = !this.isShowDetail
  6441. }
  6442. })
  6443. MenuItem({
  6444. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  6445. content: $r('app.string.share')
  6446. })
  6447. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6448. .onClick(() => {
  6449. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  6450. this.longItemFilePath = ''
  6451. })
  6452. }
  6453. .font({ size: 14, weight: FontWeight.Normal })
  6454. }
  6455. .width(180)
  6456. }
  6457. .height('auto')
  6458. .enableScrollInteraction(true)
  6459. .scrollBar(this.isGridMusic?BarState.On:BarState.Off)
  6460. }
  6461. }
  6462. private listMaxScrollOffsetY: number = 0
  6463. private selectedIndex: number = -1
  6464. setlistTwoFingers() {
  6465. this.pinchValue = this.scaleValue;
  6466. Logger.info('this.pinchValue = ' + this.pinchValue);
  6467. if (this.pinchValue >= 1) {
  6468. this.twoFingerType++
  6469. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  6470. if (this.twoFingerType > 3) {
  6471. this.twoFingerType = 1
  6472. this.isGridMusic = true
  6473. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6474. }
  6475. } else {
  6476. this.twoFingerType--
  6477. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  6478. if (this.twoFingerType < 1) {
  6479. this.twoFingerType = 4
  6480. this.columns = 1
  6481. }
  6482. }
  6483. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  6484. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6485. this.pinchValue = 1;
  6486. this.scaleValue = 1;
  6487. }
  6488. @Builder
  6489. getList(){
  6490. Stack() {
  6491. Refresh({ refreshing: $$this.isRefreshing, refreshingContent: this.contentNode }) {
  6492. this.getListView()
  6493. }
  6494. .pullDownRatio(this.ratioL)
  6495. .pullToRefresh(true)
  6496. .refreshOffset(0)
  6497. .onOffsetChange((offset: number) => {
  6498. // 越接近最大距离,下拉跟手系数越小。
  6499. this.ratioL = 1 - Math.pow((offset / this.maxRefreshingHeight), 3);
  6500. })
  6501. .onStateChange((refreshStatus: RefreshStatus) => {
  6502. console.info('onecold Refresh onStatueChange state is ' + refreshStatus);
  6503. })
  6504. .onRefreshing(async () => {
  6505. if(this.modeType==0){
  6506. this.getHistoryList(false)
  6507. this.asyncCurrentPathOnlyFile()
  6508. }else if(this.modeType == 1){
  6509. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6510. }else if(this.modeType == 2){
  6511. workerInstance.postMessage({ code: 3, data: this.context });
  6512. }else if(this.modeType == 3){
  6513. workerInstance.postMessage({ code: 4, data: this.context });
  6514. }else if(this.modeType == 4){
  6515. this.doSongListTask()
  6516. }
  6517. console.log('onRefreshing test');
  6518. })
  6519. if (this.isLoadingPage) {
  6520. Row() {
  6521. LoadingProgress()
  6522. .width(24)
  6523. .height(24)
  6524. .color(this.themeColor)
  6525. Text('加载中...')
  6526. .margin({ left: 8 })
  6527. .fontSize(13)
  6528. .fontColor($r('app.color.text_color'))
  6529. }
  6530. .padding({ left: 12, right: 12, top: 6, bottom: 6 })
  6531. .backgroundColor(this.isDarkMode ? '#66000000' : '#66FFFFFF')
  6532. .borderRadius(16)
  6533. .align(Alignment.Bottom)
  6534. .margin({ bottom: this.bottomBarHeight + this.bottomSafeHeight + 14 })
  6535. }
  6536. }
  6537. }
  6538. // 扫描当前目录下的文件,不扫描子目录
  6539. asyncCurrentPathOnlyFile(){
  6540. if(this.modeType==0){
  6541. const task = new taskpool.Task(scanCurrentDirectoryTask, getContext(this), this.currentPath,
  6542. this.lockPath,PreferencesUtil.getStringSync('COVER_API',''));
  6543. taskpool.execute(task, taskpool.Priority.HIGH).then(()=>{
  6544. if(this.modeType==0){
  6545. setTimeout(()=>{
  6546. this.isRefreshing =false
  6547. this.deleteCache(this.currentPath)
  6548. this.getSortedFiles(this.currentPath)
  6549. },500)
  6550. }
  6551. }).catch((e:object)=>{
  6552. this.isRefreshing =false
  6553. console.info("onecold task1 catch e: " + e);
  6554. })
  6555. }
  6556. }
  6557. @Builder
  6558. getListView() {
  6559. List({ scroller: this.listScroller }) {
  6560. // ListItemGroup({ header: this.coverHeader() }) {
  6561. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  6562. ListItem() {
  6563. Column() {
  6564. if (item.type === CommonConstants.TYPE_IS_DIR
  6565. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  6566. this.DirItem(item, index)
  6567. } else {
  6568. this.MusicItem(item, index)
  6569. }
  6570. }
  6571. }
  6572. .clickEffect({ level: ClickEffectLevel.LIGHT })
  6573. .swipeAction((
  6574. ((this.isSwipe && !this.isScrolling) &&
  6575. (this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack)))
  6576. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  6577. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath),
  6578. edgeEffect: SwipeEdgeEffect.None } : {}) //左滑
  6579. .onClick(() => {
  6580. if (this.isMultiSelect) {
  6581. if (this.isSelectableLocalItem(item)) {
  6582. const isChecked = this.isLocalItemSelected(item);
  6583. this.handleFileSelection(item, !isChecked);
  6584. }
  6585. return
  6586. }
  6587. this.doPlay(item, index)
  6588. })
  6589. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  6590. }
  6591. .onScrollStart(() => {
  6592. this.isScrolling = true
  6593. this.listVisibleStart = -1
  6594. this.listVisibleEnd = -1
  6595. this.listScrollAlphaCheckAt = 0
  6596. this.listScrollPagingCheckAt = 0
  6597. this.listScrollLastAlphaStart = -1
  6598. this.listScrollLastPagingEnd = -1
  6599. if (this.alphaBetRebuildTimer) {
  6600. clearTimeout(this.alphaBetRebuildTimer)
  6601. this.alphaBetRebuildTimer = 0
  6602. }
  6603. this.showAlphabetIndex()
  6604. })
  6605. .onScrollIndex((start: number,center:number,end:number) => {
  6606. this.selectedIndex = start
  6607. this.listVisibleStart = start
  6608. this.listVisibleEnd = end
  6609. this.lastVisibleEndIndex = end
  6610. if (!this.isMediaLibraryWarmupWindow()) {
  6611. this.warmupListVisibleThumbs(start, end)
  6612. }
  6613. const now = Date.now()
  6614. const alphaDelta = this.listScrollLastAlphaStart >= 0 ? Math.abs(start - this.listScrollLastAlphaStart) : 999
  6615. if (!this.isMediaLibraryWarmupWindow() &&
  6616. start >= 0 && start < this.videoLocalList.length &&
  6617. (alphaDelta >= 2 || now - this.listScrollAlphaCheckAt >= 48)) {
  6618. this.listScrollAlphaCheckAt = now
  6619. this.listScrollLastAlphaStart = start
  6620. const nextAlphaIndex = this.findAlphaBetIndex(this.videoLocalList[start])
  6621. if (nextAlphaIndex !== this.selectAlphaBetIndex) {
  6622. this.selectAlphaBetIndex = nextAlphaIndex
  6623. }
  6624. }
  6625. const pagingDelta = this.listScrollLastPagingEnd >= 0 ? Math.abs(end - this.listScrollLastPagingEnd) : 999
  6626. if (pagingDelta >= 2 || now - this.listScrollPagingCheckAt >= 32) {
  6627. this.listScrollPagingCheckAt = now
  6628. this.listScrollLastPagingEnd = end
  6629. this.tryTriggerLoadNextPageByScroll(end)
  6630. }
  6631. })
  6632. .onScrollStop(() => {
  6633. if(this.isScrolling){
  6634. this.isScrolling = false
  6635. }
  6636. this.flushPendingCoverThumbRefresh()
  6637. if (this.alphaBetDirty) {
  6638. this.scheduleAlphaBetRebuild(0)
  6639. }
  6640. this.hideAlphabetIndexAfterDelay(1500)
  6641. })
  6642. .onReachEnd(() => {
  6643. if(this.modeType === 4 )//歌单不能加载下一页
  6644. return;
  6645. // 触底加载下一页
  6646. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  6647. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  6648. return;
  6649. }
  6650. if (this.hasMoreData && !this.isLoadingPage && !this.isPagingTransition) {
  6651. this.scheduleLoadNextPage();
  6652. }
  6653. })
  6654. .scrollBar(BarState.Off)
  6655. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  6656. .gesture(PinchGesture({ fingers: 2 })
  6657. .onActionEnd((event: GestureEvent) => {
  6658. this.setlistTwoFingers()
  6659. })
  6660. .onActionUpdate(e => {
  6661. this.scaleValue = this.pinchValue * e.scale
  6662. })
  6663. .onActionStart(e => {
  6664. }))
  6665. .contentStartOffset(this.topSafeHeight + 55)
  6666. .scrollBar(BarState.Off)
  6667. .contentEndOffset(this.bottomBarHeight+this.bottomSafeHeight)
  6668. .cachedCount(this.modeType == 1 ? 4 : 8)
  6669. // .reuseId('list_item')
  6670. .borderRadius(20)
  6671. .layoutWeight(1)
  6672. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  6673. .lanes(
  6674. new BreakpointType<number>({
  6675. sm: 1,
  6676. md: 2,
  6677. lg: 2,
  6678. xl: 3,
  6679. xxl: 4
  6680. }).getValue(this.currentBreakpoint),
  6681. new BreakpointType<number>({
  6682. sm: 0,
  6683. md: 12,
  6684. lg: 12,
  6685. xl: 16,
  6686. xxl: 20
  6687. }).getValue(this.currentBreakpoint)
  6688. )
  6689. .onAreaChange((oldValue: Area, newValue: Area) => {
  6690. this.listArea = newValue
  6691. if (this.twoFingerType == 3) {
  6692. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  6693. } else if (this.twoFingerType == 2) {
  6694. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  6695. } else if (this.twoFingerType == 1) {
  6696. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  6697. }
  6698. })
  6699. .onScrollFrameBegin((offset: number) => {
  6700. const currentOffsetY = this.listScroller.currentOffset().yOffset;
  6701. this.updateTitleBarByScrollOffset(currentOffsetY)
  6702. return { offsetRemain: offset };
  6703. })
  6704. }
  6705. setBarHeightNormal() {
  6706. this.hideDone = false;
  6707. this.getUIContext().animateTo({
  6708. duration: 300
  6709. }, () => {
  6710. this.bottomBarHeight = 68 + 0;
  6711. this.topBarHeight = 50 + 0;
  6712. this.barOpacity = 1;
  6713. this.barBottomOpacity = 1
  6714. this.currentYOffset = 0;
  6715. this.isHiding = false;
  6716. });
  6717. }
  6718. setBarHeightHide(offset: number) {
  6719. if (offset > 0 && !this.hideDone) {
  6720. this.currentYOffset += offset;
  6721. if (this.currentYOffset <= 100) {
  6722. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  6723. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  6724. this.barOpacity = 1 - this.currentYOffset / 100;
  6725. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  6726. } else {
  6727. this.topBarHeight = 0;
  6728. this.bottomBarHeight = 0;
  6729. this.barBottomOpacity = 0
  6730. this.barOpacity = 0;
  6731. this.hideDone = true;
  6732. }
  6733. this.isHiding = true;
  6734. }
  6735. if (offset < 0 && this.isHiding) {
  6736. this.hideDone = false;
  6737. this.getUIContext().animateTo({
  6738. duration: 300
  6739. }, () => {
  6740. this.bottomBarHeight = 68 + 0;
  6741. this.topBarHeight = 50 + 0;
  6742. this.barOpacity = 1;
  6743. this.barBottomOpacity = 1
  6744. this.currentYOffset = 0;
  6745. this.isHiding = false;
  6746. });
  6747. }
  6748. }
  6749. //这个方法没隐藏bottomBar,只隐藏topbar
  6750. setBarHeightHide2(offset: number) {
  6751. if (offset > 0 && !this.hideDone) {
  6752. this.currentYOffset += offset;
  6753. if (this.currentYOffset <= 100) {
  6754. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  6755. this.barOpacity = 1 - this.currentYOffset / 100;
  6756. } else {
  6757. this.topBarHeight = 0;
  6758. this.barOpacity = 0;
  6759. this.hideDone = true;
  6760. }
  6761. this.isHiding = true;
  6762. }
  6763. if (offset < 0 && this.isHiding) {
  6764. this.hideDone = false;
  6765. this.getUIContext().animateTo({
  6766. duration: 300
  6767. }, () => {
  6768. this.topBarHeight = 50 + 0;
  6769. this.barOpacity = 1;
  6770. this.currentYOffset = 0;
  6771. this.isHiding = false;
  6772. });
  6773. }
  6774. }
  6775. private async doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean,isOpen?:boolean) {
  6776. Logger.info(`heanup doPlay被调用 - 歌曲: ${item.name}, 文件路径: ${item.filePath}, 索引: ${index}, 类型: ${item.type}, isFromSonPlayList: ${isFromSonPlayList}`)
  6777. switch (item.type) {
  6778. case CommonConstants.TYPE_IS_DIR:
  6779. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  6780. let shouldScrollTopNow = true
  6781. let offsetB = 0
  6782. if(this.twoFingerType==4){
  6783. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6784. let cur = this.waterScroller.currentOffset()
  6785. if (cur && typeof cur.yOffset === 'number') {
  6786. offsetB = cur.yOffset
  6787. }
  6788. }
  6789. this.mScrollMap.set('lastWaterDirScrollOffset', offsetB)
  6790. }else
  6791. if (this.isGridMusic) {
  6792. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6793. let cur = this.scroller.currentOffset()
  6794. if (cur && typeof cur.yOffset === 'number') {
  6795. offsetB = cur.yOffset
  6796. }
  6797. }
  6798. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  6799. } else {
  6800. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6801. let cur = this.listScroller.currentOffset()
  6802. if (cur && typeof cur.yOffset === 'number') {
  6803. offsetB = cur.yOffset
  6804. }
  6805. }
  6806. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  6807. }
  6808. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  6809. this.showVerifyDialog()
  6810. this.currentTitleName = '私密音频'
  6811. this.currentTitleCover = $r('app.media.alt')
  6812. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  6813. this.titleName = '最近播放'
  6814. this.currentTitleCover = $r('app.media.alt')
  6815. this.currentTitleName = '最近播放'
  6816. //加载动画效果
  6817. this.updateListData(this.historyList, true)
  6818. // this.videoLocalList = this.historyList
  6819. if (ArrayUtil.isEmpty(this.historyList)) {
  6820. ToastUtil.showToast('最近播放记录空空如也')
  6821. } else {
  6822. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  6823. }
  6824. this.isHistory = true
  6825. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  6826. this.titleName = '我的收藏'
  6827. this.currentTitleName = '我的收藏'
  6828. this.currentTitleCover = $r('app.media.alt')
  6829. //加载动画效果
  6830. this.updateListData(this.favList, true)
  6831. if (ArrayUtil.isEmpty(this.favList)) {
  6832. ToastUtil.showToast('无音乐收藏记录')
  6833. } else {
  6834. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  6835. }
  6836. this.isFavMusic = true
  6837. } else {
  6838. this.currentTitleName = item.name
  6839. this.currentPath = item.filePath
  6840. this.currentTitleCover = $r('app.media.alt')
  6841. shouldScrollTopNow = false
  6842. this.getSortedFiles(this.currentPath, false, undefined, undefined, undefined, true, true)
  6843. }
  6844. //进入歌单的时候的滚动位置在顶部
  6845. if (shouldScrollTopNow) {
  6846. if(this.twoFingerType==4){
  6847. setTimeout(() => {
  6848. this.waterScroller.scrollEdge(Edge.Top)
  6849. this.scroller.scrollEdge(Edge.Top)
  6850. }, 200)
  6851. }else{
  6852. if (this.isGridMusic) {
  6853. this.scroller.scrollToIndex(0,false)
  6854. }else{
  6855. this.listScroller.scrollToIndex(0,false)
  6856. }
  6857. }
  6858. }
  6859. this.rightTopImage = $r('sys.symbol.chevron_left')
  6860. break;
  6861. case CommonConstants.TYPE_IS_ARTIST:
  6862. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  6863. let offsetA = 0
  6864. if(this.twoFingerType==4){
  6865. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6866. let cur = this.waterScroller.currentOffset()
  6867. if (cur && typeof cur.yOffset === 'number') {
  6868. offsetA = cur.yOffset
  6869. }
  6870. }
  6871. this.mScrollMap.set('lastWaterArtistScrollOffset', offsetA)
  6872. }else
  6873. if (this.isGridMusic) {
  6874. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6875. let cur = this.scroller.currentOffset()
  6876. if (cur && typeof cur.yOffset === 'number') {
  6877. offsetA = cur.yOffset
  6878. }
  6879. }
  6880. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  6881. } else {
  6882. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6883. let cur = this.listScroller.currentOffset()
  6884. if (cur && typeof cur.yOffset === 'number') {
  6885. offsetA = cur.yOffset
  6886. }
  6887. }
  6888. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  6889. }
  6890. // 进入艺术家详情页前,先加载详情页的排序类型
  6891. // 注意:需要临时设置isCanBack=true,以便loadSortTypeForCurrentMode读取详情页的排序设置
  6892. const artistOriginalIsCanBack = this.isCanBack;
  6893. this.isCanBack = true;
  6894. const artistDetailSortType = this.loadSortTypeForCurrentMode();
  6895. this.isCanBack = artistOriginalIsCanBack; // 恢复原值
  6896. Logger.info('heanup LocalMusic', `进入艺术家详情页: 加载详情页排序 sortType=${artistDetailSortType}`);
  6897. // 缓存键需要包含排序类型,因为不同的排序类型会产生不同的数据
  6898. const artistCacheKey = `${item.name}_sort_${artistDetailSortType}`;
  6899. let mList = this.artistMap.get(artistCacheKey)
  6900. if (mList === undefined || ArrayUtil.isEmpty(mList)) {
  6901. // 使用详情页的排序类型查询
  6902. mList = await this.table.querySongsByArtist(item.name, artistDetailSortType, this.isShowFileName);
  6903. if (ArrayUtil.isNotEmpty(mList)) {
  6904. this.artistMap.set(artistCacheKey, mList);
  6905. }
  6906. }
  6907. // 设置当前排序类型为详情页排序
  6908. this.sortType = artistDetailSortType;
  6909. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  6910. // 注意:不再调用 Utility.doSortListAscending,因为数据已经按 artistDetailSortType 排序了
  6911. const nextArtistCountMap = new Map(this.artistSongCountMap);
  6912. nextArtistCountMap.set(item.name, mList.length);
  6913. this.artistSongCountMap = nextArtistCountMap;
  6914. this.isCanBack = true
  6915. this.hasMoreData = false
  6916. this.isLoadingPage = false
  6917. this.pageCache.clear()
  6918. this.pageHasMoreCache.clear()
  6919. this.pageTotalCountCache.clear()
  6920. this.prefetchingPages.clear()
  6921. this.lastScrollTriggerPage = -1
  6922. this.lastVisibleEndIndex = -1
  6923. this.isPagingTransition = false
  6924. if (this.pagingScheduleTimer) {
  6925. clearTimeout(this.pagingScheduleTimer)
  6926. this.pagingScheduleTimer = 0
  6927. }
  6928. this.totalCount = mList.length
  6929. this.titleName = item.name
  6930. this.currentTitleName = '艺术家:' + item.name
  6931. if (item.pixelMapPath) {
  6932. this.currentTitleCover = item.pixelMapPath
  6933. }
  6934. this.updateListData(mList, true, true) // 详情页立即替换列表,避免旧列表顶部闪现
  6935. } else {
  6936. ToastUtil.showToast('未找到该艺术家的歌曲');
  6937. return;
  6938. }
  6939. this.rightTopImage = $r('sys.symbol.chevron_left')
  6940. //进入歌单的时候的滚动位置在顶部
  6941. if(this.twoFingerType==4){
  6942. setTimeout(() => {
  6943. this.waterScroller.scrollEdge(Edge.Top)
  6944. this.scroller.scrollEdge(Edge.Top)
  6945. }, 380)
  6946. }else{
  6947. if (this.isGridMusic) {
  6948. this.scroller.scrollEdge(Edge.Top)
  6949. }else{
  6950. this.listScroller.scrollEdge(Edge.Top)
  6951. }
  6952. }
  6953. break;
  6954. case CommonConstants.TYPE_IS_ALBUM:
  6955. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  6956. let offset = 0
  6957. if(this.twoFingerType==4){
  6958. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6959. let cur = this.waterScroller.currentOffset()
  6960. if (cur && typeof cur.yOffset === 'number') {
  6961. offset = cur.yOffset
  6962. }
  6963. }
  6964. this.mScrollMap.set('lastWaterAlBumScrollOffset', offset)
  6965. }else
  6966. if (this.isGridMusic) {
  6967. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6968. let cur = this.scroller.currentOffset()
  6969. if (cur && typeof cur.yOffset === 'number') {
  6970. offset = cur.yOffset
  6971. }
  6972. }
  6973. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  6974. } else {
  6975. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6976. let cur = this.listScroller.currentOffset()
  6977. if (cur && typeof cur.yOffset === 'number') {
  6978. offset = cur.yOffset
  6979. }
  6980. }
  6981. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  6982. }
  6983. // 进入专辑详情页前,先加载详情页的排序类型
  6984. // 注意:需要临时设置isCanBack=true,以便loadSortTypeForCurrentMode读取详情页的排序设置
  6985. const albumOriginalIsCanBack = this.isCanBack;
  6986. this.isCanBack = true;
  6987. const albumDetailSortType = this.loadSortTypeForCurrentMode();
  6988. this.isCanBack = albumOriginalIsCanBack; // 恢复原值
  6989. Logger.info('heanup LocalMusic', `进入专辑详情页: 加载详情页排序 sortType=${albumDetailSortType}`);
  6990. // 缓存键需要包含排序类型,因为不同的排序类型会产生不同的数据
  6991. const albumCacheKey = `${item.name}_sort_${albumDetailSortType}`;
  6992. let albumList = this.albumMap.get(albumCacheKey)
  6993. if (albumList === undefined || ArrayUtil.isEmpty(albumList)) {
  6994. // 使用详情页的排序类型查询
  6995. albumList = await this.table.querySongsByAlbum(item.name, albumDetailSortType, this.isShowFileName);
  6996. if (ArrayUtil.isNotEmpty(albumList)) {
  6997. this.albumMap.set(albumCacheKey, albumList);
  6998. }
  6999. }
  7000. // 设置当前排序类型为详情页排序
  7001. this.sortType = albumDetailSortType;
  7002. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  7003. // 注意:不再调用 Utility.doSortListAscending,因为数据已经按 albumDetailSortType 排序了
  7004. const nextAlbumCountMap = new Map(this.albumSongCountMap);
  7005. nextAlbumCountMap.set(item.name, albumList.length);
  7006. this.albumSongCountMap = nextAlbumCountMap;
  7007. this.isCanBack = true
  7008. this.hasMoreData = false
  7009. this.isLoadingPage = false
  7010. this.pageCache.clear()
  7011. this.pageHasMoreCache.clear()
  7012. this.pageTotalCountCache.clear()
  7013. this.prefetchingPages.clear()
  7014. this.lastScrollTriggerPage = -1
  7015. this.lastVisibleEndIndex = -1
  7016. this.isPagingTransition = false
  7017. if (this.pagingScheduleTimer) {
  7018. clearTimeout(this.pagingScheduleTimer)
  7019. this.pagingScheduleTimer = 0
  7020. }
  7021. this.totalCount = albumList.length
  7022. this.titleName = item.name
  7023. this.currentTitleName = '专辑:' + item.name
  7024. if (item.pixelMapPath) {
  7025. this.currentTitleCover = item.pixelMapPath
  7026. }
  7027. this.updateListData(albumList, true, true) // 详情页立即替换列表,避免旧列表顶部闪现
  7028. this.mScrollMap.set(item.name, this.selectedIndex)
  7029. this.rightTopImage = $r('sys.symbol.chevron_left')
  7030. } else {
  7031. ToastUtil.showToast('未找到该专辑的歌曲');
  7032. return;
  7033. }
  7034. //进入歌单的时候的滚动位置在顶部
  7035. if(this.twoFingerType==4){
  7036. setTimeout(() => {
  7037. this.waterScroller.scrollEdge(Edge.Top)
  7038. this.scroller.scrollEdge(Edge.Top)
  7039. }, 380)
  7040. }else{
  7041. if (this.isGridMusic) {
  7042. this.scroller.scrollEdge(Edge.Top)
  7043. }else{
  7044. this.listScroller.scrollEdge(Edge.Top)
  7045. }
  7046. }
  7047. break;
  7048. case CommonConstants.TYPE_IS_CSJAD:
  7049. return
  7050. break;
  7051. case CommonConstants.TYPE_LOCAL:
  7052. if (this.isIsoLocalFile(item)) {
  7053. await this.openIsoArchiveDialog(item)
  7054. return
  7055. }
  7056. if(item&&item.filePath.toLowerCase().endsWith('.cue')){
  7057. const cueinfo:CueInfo = await parseCueFile(item.filePath)
  7058. const cueTracks:CueTrack[] = cueinfo.tracks
  7059. console.log('onecold cue cueTracks =', JSON.stringify(cueTracks));
  7060. if(ArrayUtil.isNotEmpty(cueTracks)){
  7061. this.showCueDialog(cueTracks,cueinfo)
  7062. }
  7063. // this.showCueSheet = !this.showCueSheet
  7064. return
  7065. }
  7066. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  7067. this.stop();
  7068. }
  7069. if (isOpen) {
  7070. this.currentSong = item
  7071. if (index !== undefined) {
  7072. this.curIndex = index
  7073. }
  7074. this.songList = []
  7075. this.songList.push(item)
  7076. this.sonDataSource.pushArrayData(this.songList)
  7077. this.playQueueScope = 'single'
  7078. }else if(isFromSonPlayList){ //点击来自右下角的播放列表
  7079. this.currentSong = item
  7080. if (index !== undefined) {
  7081. this.curIndex = index
  7082. }
  7083. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  7084. Logger.info(`heanup isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  7085. this.playQueueScope = 'playlist'
  7086. // 确保歌单路径列表已设置(从songList重新构建,以防被清空)
  7087. if (this.currentPlaylistSongFilePaths.length === 0 && this.songList.length > 0) {
  7088. this.currentPlaylistSongFilePaths = this.songList.map(song => song.filePath);
  7089. Logger.info(`heanup isFromSonPlayList - 重新构建歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  7090. }
  7091. }else {
  7092. const globalVideoList = this.buildPlayQueueFromView();
  7093. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  7094. if (this.curIndex < 0) {
  7095. globalVideoList.push(item);
  7096. this.curIndex = globalVideoList.length - 1;
  7097. }
  7098. this.songList = globalVideoList
  7099. this.sonDataSource.pushArrayData(this.songList)
  7100. this.currentSong = this.songList[this.curIndex]
  7101. // 只在非歌单模式下清空歌单路径列表
  7102. if (this.modeType !== 4) {
  7103. this.currentPlaylistSongFilePaths = [];
  7104. Logger.info(`heanup doPlay设置播放列表 - 总歌曲数: ${this.songList.length}, 当前索引: ${this.curIndex}, 当前歌曲: ${this.currentSong?.name}, 已清空歌单路径列表(modeType=${this.modeType})`)
  7105. } else {
  7106. // 歌单模式:确保歌单路径列表已设置
  7107. if (this.currentPlaylistSongFilePaths.length === 0 && this.songList.length > 0) {
  7108. this.currentPlaylistSongFilePaths = this.songList.map(song => song.filePath);
  7109. Logger.info(`heanup doPlay设置播放列表 - 从songList重新构建歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  7110. } else {
  7111. Logger.info(`heanup doPlay设置播放列表 - 歌单模式,保持歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  7112. }
  7113. }
  7114. }
  7115. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  7116. try {
  7117. const localUrl = await this.resolvePlaybackUrlForCurrentSong('doPlay-local');
  7118. this.videoUrl = localUrl || this.currentSong.filePath
  7119. } catch (error) {
  7120. Logger.error(TAG, `本地歌曲构建播放地址失败: ${(error as Error).message}`);
  7121. this.videoUrl = this.currentSong.filePath
  7122. }
  7123. this.name = this.currentSong.name
  7124. this.cover = this.currentSong.pixelMapPath
  7125. this.artist = this.currentSong.artist
  7126. LogUtil.info('onecold this.currentSong.cover =' + this.currentSong.pixelMapPath)
  7127. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  7128. this.startPlayOrResumePlay()
  7129. break;
  7130. case CommonConstants.TYPE_WEBDAV:
  7131. case CommonConstants.TYPE_SMB:
  7132. case CommonConstants.TYPE_NAVIDROME:
  7133. case CommonConstants.TYPE_FTP:
  7134. case CommonConstants.TYPE_BAIDU:
  7135. case CommonConstants.TYPE_JELLYFIN:
  7136. case CommonConstants.TYPE_EMBY:
  7137. case CommonConstants.TYPE_AUDIOSTATION:
  7138. case CommonConstants.TYPE_PLEX:
  7139. case CommonConstants.TYPE_DAOLIYU:
  7140. // 处理网络音频播放(WebDAV/SMB/Navidrome/Jellyfin/Emby/AudioStation/Plex/道理鱼/Baidu)
  7141. Logger.info(`heanup 处理云端音频播放: ${item.name}, URL: ${item.filePath}`)
  7142. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  7143. this.stop();
  7144. }
  7145. if (isOpen) {
  7146. this.currentSong = item
  7147. if (index !== undefined) {
  7148. this.curIndex = index
  7149. }
  7150. this.songList = []
  7151. this.songList.push(item)
  7152. this.sonDataSource.pushArrayData(this.songList)
  7153. } else if (isFromSonPlayList) {
  7154. // 点击来自右下角的播放列表
  7155. this.currentSong = item
  7156. if (index !== undefined) {
  7157. this.curIndex = index
  7158. }
  7159. // 设置播放队列作用域为歌单
  7160. this.playQueueScope = 'playlist'
  7161. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  7162. Logger.info(`heanup 网络音频 isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}, playQueueScope=${this.playQueueScope}`)
  7163. } else {
  7164. // 从全局网络音频列表中查找
  7165. let globalVideoList = this.videoLocalList.filter(video => isRemoteCloudType(video.type)) as VideoItem[];
  7166. this.curIndex = globalVideoList.findIndex(video => video.filePath === item.filePath);
  7167. if (this.curIndex === -1 && index !== undefined) {
  7168. this.curIndex = index;
  7169. }
  7170. this.songList = globalVideoList.length > 0 ? globalVideoList : [item];
  7171. this.currentSong = this.songList[this.curIndex];
  7172. this.sonDataSource.pushArrayData(this.songList)
  7173. }
  7174. await this.hydrateRemoteSongFromDb(this.currentSong);
  7175. await this.hydrateRemoteSongFromDb(this.currentSong);
  7176. AppStorage.setOrCreate('currentSong', this.currentSong);
  7177. const remotePlayLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  7178. const playbackUrl = await this.resolvePlaybackUrlForCurrentSong('doPlay-remote');
  7179. if (!playbackUrl) {
  7180. if (remotePlayLoading) {
  7181. this.hideLoadIng();
  7182. }
  7183. return;
  7184. }
  7185. this.videoUrl = playbackUrl;
  7186. Logger.info(TAG, `WebDAV URL同步构建完成(分支2): ${this.videoUrl}`);
  7187. this.name = this.currentSong.name
  7188. this.cover = this.currentSong.pixelMapPath
  7189. this.artist = this.currentSong.artist
  7190. Logger.info(`heanup 准备播放网络音频 - 歌名: ${this.name}, 艺术家: ${this.artist}, 完整URL: ${this.videoUrl}`)
  7191. this.startPlayOrResumePlay()
  7192. break;
  7193. }
  7194. }
  7195. private async openIsoArchiveDialog(item: VideoItem): Promise<void> {
  7196. if (!item || StrUtil.isEmpty(item.filePath)) {
  7197. Logger.error(TAG, `heanup ISO open dialog invalid path=${item ? item.filePath : ''}`)
  7198. ToastUtil.showToast('ISO 文件无效')
  7199. return
  7200. }
  7201. if (this.isIsoExtracting) {
  7202. if (ArrayUtil.isNotEmpty(this.isoAudioEntries)) {
  7203. if (this.isoSourceFilePath !== item.filePath) {
  7204. ToastUtil.showToast('当前有 ISO 提取任务正在后台执行,已打开提取进度窗口')
  7205. }
  7206. this.presentIsoArchiveDialog()
  7207. return
  7208. }
  7209. ToastUtil.showToast('当前有 ISO 提取任务正在后台执行')
  7210. return
  7211. }
  7212. Logger.info(TAG, `heanup ISO open dialog path=${item.filePath}, name=${item.fileName || item.name}`)
  7213. this.closeIsoDialog()
  7214. this.isoSourceFilePath = item.filePath
  7215. this.isoSourceFileName = item.fileName || item.name
  7216. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  7217. progress: 0,
  7218. backCancel: false,
  7219. autoCancel: false,
  7220. loadColor: this.themeColor,
  7221. fontColor: this.themeColor
  7222. })
  7223. try {
  7224. const task = new taskpool.Task(listIsoAudioEntriesTask, item.filePath)
  7225. const entries = await taskpool.execute(task, taskpool.Priority.HIGH) as IsoArchiveAudioEntry[]
  7226. this.isoAudioEntries = Array.isArray(entries) ? entries : []
  7227. Logger.info(TAG, `heanup ISO list entries done count=${this.isoAudioEntries.length}, path=${item.filePath}`)
  7228. if (ArrayUtil.isEmpty(this.isoAudioEntries)) {
  7229. Logger.error(TAG, `heanup ISO list entries empty path=${item.filePath}`)
  7230. ToastUtil.showToast('ISO 内未发现可提取的媒体文件')
  7231. this.closeIsoDialog()
  7232. return
  7233. }
  7234. this.selectedIsoAudioPaths = []
  7235. } catch (error) {
  7236. Logger.error(TAG, `heanup 解析 ISO 失败: ${(error as Error).message}`)
  7237. ToastUtil.showToast('解析 ISO 失败')
  7238. this.closeIsoDialog()
  7239. return
  7240. } finally {
  7241. if (this.loadingProgressDialogId) {
  7242. DialogHelper.closeDialog(this.loadingProgressDialogId)
  7243. this.loadingProgressDialogId = ''
  7244. }
  7245. }
  7246. this.presentIsoArchiveDialog()
  7247. }
  7248. private presentIsoArchiveDialog(): void {
  7249. if (this.isoComponentId > 0) {
  7250. return
  7251. }
  7252. this.getUIContext().getPromptAction().openCustomDialog({
  7253. builder: () => {
  7254. this.isoComptentBuilder()
  7255. },
  7256. isModal: true,
  7257. showInSubWindow: false,
  7258. maskColor: Color.Transparent,
  7259. dialogTransition: TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  7260. .animation({ duration: 600, curve: Curve.Smooth }),
  7261. maskTransition: TransitionEffect.opacity(0.5)
  7262. .animation({ duration: 600, curve: Curve.Smooth })
  7263. }).then((dialogId: number) => {
  7264. this.isoComponentId = dialogId
  7265. }).catch((error: BusinessError) => {
  7266. Logger.error(TAG, `heanup 打开 ISO 弹窗失败: ${error.message}`)
  7267. this.closeIsoDialog()
  7268. })
  7269. }
  7270. private toggleIsoEntrySelection(path: string, checked: boolean): void {
  7271. const selectedPathSet: Set<string> = new Set<string>(this.selectedIsoAudioPaths)
  7272. if (checked) {
  7273. selectedPathSet.add(path)
  7274. } else {
  7275. selectedPathSet.delete(path)
  7276. }
  7277. this.selectedIsoAudioPaths = this.isoAudioEntries
  7278. .filter((entry: IsoArchiveAudioEntry) => selectedPathSet.has(entry.path))
  7279. .map((entry: IsoArchiveAudioEntry) => entry.path)
  7280. Logger.info(TAG,
  7281. `heanup ISO toggle selection path=${path}, checked=${checked}, total=${this.selectedIsoAudioPaths.length}`)
  7282. }
  7283. private toggleIsoEntrySelectAll(): void {
  7284. if (this.selectedIsoAudioPaths.length === this.isoAudioEntries.length) {
  7285. this.selectedIsoAudioPaths = []
  7286. Logger.info(TAG, 'heanup ISO toggle select all cleared')
  7287. return
  7288. }
  7289. this.selectedIsoAudioPaths = this.isoAudioEntries.map((entry: IsoArchiveAudioEntry) => entry.path)
  7290. Logger.info(TAG, `heanup ISO toggle select all count=${this.selectedIsoAudioPaths.length}`)
  7291. }
  7292. private startIsoExtractProgressWatcher(entries: Array<IsoArchiveAudioEntry>, destinationDir: string): void {
  7293. this.stopIsoExtractProgressWatcher()
  7294. this.isoExtractExpectedOutputPaths = this.buildIsoExtractExpectedOutputPaths(entries, destinationDir)
  7295. this.isoExtractTotalBytes = entries.reduce((total: number, entry: IsoArchiveAudioEntry) => {
  7296. const size = entry && entry.size > 0 ? entry.size : 0
  7297. return total + size
  7298. }, 0)
  7299. this.isoExtractReceivedTaskProgress = false
  7300. this.isoExtractDisplayedProgress = 0
  7301. this.isoExtractLastActivityTime = Date.now()
  7302. if (this.isoExtractTotalBytes <= 0 || ArrayUtil.isEmpty(this.isoExtractExpectedOutputPaths)) {
  7303. return
  7304. }
  7305. this.isoExtractProgressTimer = setInterval(() => {
  7306. this.updateIsoExtractProgressFromFiles()
  7307. }, 500)
  7308. }
  7309. private stopIsoExtractProgressWatcher(): void {
  7310. if (this.isoExtractProgressTimer) {
  7311. clearInterval(this.isoExtractProgressTimer)
  7312. this.isoExtractProgressTimer = 0
  7313. }
  7314. this.isoExtractExpectedOutputPaths = []
  7315. this.isoExtractTotalBytes = 0
  7316. this.isoExtractReceivedTaskProgress = false
  7317. this.isoExtractLastActivityTime = 0
  7318. }
  7319. private markIsoExtractActivity(): void {
  7320. this.isoExtractLastActivityTime = Date.now()
  7321. }
  7322. private updateIsoExtractProgressFromFiles(): void {
  7323. if (this.isoExtractTotalBytes <= 0 || ArrayUtil.isEmpty(this.isoExtractExpectedOutputPaths) ||
  7324. this.isoExtractReceivedTaskProgress) {
  7325. return
  7326. }
  7327. let writtenBytes = 0
  7328. let existingCount = 0
  7329. for (let i = 0; i < this.isoExtractExpectedOutputPaths.length; i++) {
  7330. const outputPath = this.isoExtractExpectedOutputPaths[i]
  7331. if (!FileUtil.accessSync(outputPath)) {
  7332. continue
  7333. }
  7334. existingCount++
  7335. try {
  7336. const stat = fs.statSync(outputPath) as fs.Stat
  7337. if (typeof stat.size === 'number' && stat.size > 0) {
  7338. writtenBytes += stat.size
  7339. }
  7340. } catch (_error) {
  7341. }
  7342. }
  7343. let progress = 0
  7344. if (writtenBytes > 0) {
  7345. progress = Math.ceil((writtenBytes / this.isoExtractTotalBytes) * 100)
  7346. if (progress > 99) {
  7347. progress = 99
  7348. }
  7349. this.markIsoExtractActivity()
  7350. } else if (existingCount > 0) {
  7351. progress = 1
  7352. this.markIsoExtractActivity()
  7353. }
  7354. if (progress > 0) {
  7355. this.updateIsoExtractProgressState(progress,
  7356. `正在提取 ${progress}% (${existingCount}/${this.isoExtractExpectedOutputPaths.length})`)
  7357. return
  7358. }
  7359. if (this.isoExtractTask && this.isoExtractLastActivityTime > 0 &&
  7360. Date.now() - this.isoExtractLastActivityTime > this.isoExtractStallTimeoutMs) {
  7361. Logger.warn(TAG, `heanup ISO 提取进度长时间无变化: timeout=${this.isoExtractStallTimeoutMs}`)
  7362. this.markIsoExtractActivity()
  7363. this.updateIsoExtractProgressState(1, '准备提取 1%')
  7364. }
  7365. }
  7366. private updateIsoExtractProgressState(progress: number, message: string, currentName: string = '',
  7367. force: boolean = false): void {
  7368. let safeProgress = progress
  7369. if (safeProgress < 0) {
  7370. safeProgress = 0
  7371. }
  7372. if (safeProgress > 100) {
  7373. safeProgress = 100
  7374. }
  7375. if (!force && safeProgress < this.isoExtractDisplayedProgress) {
  7376. return
  7377. }
  7378. this.isoExtractDisplayedProgress = safeProgress
  7379. this.isoExtractProgress = safeProgress
  7380. this.isoExtractProgressText = message
  7381. if (force || StrUtil.isNotEmpty(currentName)) {
  7382. this.isoExtractCurrentEntryName = currentName
  7383. }
  7384. }
  7385. private resetIsoExtractProgressState(): void {
  7386. this.isoExtractProgress = 0
  7387. this.isoExtractProgressText = ''
  7388. this.isoExtractCurrentEntryName = ''
  7389. this.isoExtractDisplayedProgress = 0
  7390. }
  7391. private buildIsoExtractExpectedOutputPaths(entries: Array<IsoArchiveAudioEntry>, destinationDir: string): Array<string> {
  7392. const outputPaths: Array<string> = []
  7393. const occupiedPaths: Set<string> = new Set<string>()
  7394. for (let i = 0; i < entries.length; i++) {
  7395. const entry = entries[i]
  7396. const fileName = entry.name || this.getIsoLastPathSegment(entry.path)
  7397. const outputPath = this.buildIsoExpectedOutputPath(destinationDir, fileName, occupiedPaths)
  7398. occupiedPaths.add(outputPath)
  7399. outputPaths.push(outputPath)
  7400. }
  7401. return outputPaths
  7402. }
  7403. private buildIsoExpectedOutputPath(destinationDir: string, fileName: string, occupiedPaths: Set<string>): string {
  7404. const cleanName = this.sanitizeIsoOutputFileName(fileName)
  7405. const extension = this.getIsoOutputFileExtension(cleanName)
  7406. const baseName = extension.length > 0 ? cleanName.substring(0, cleanName.length - extension.length) : cleanName
  7407. let candidatePath = `${this.trimIsoOutputTrailingSeparator(destinationDir)}/${cleanName}`
  7408. let suffix = 0
  7409. while (occupiedPaths.has(candidatePath) || FileUtil.accessSync(candidatePath)) {
  7410. suffix++
  7411. candidatePath = `${this.trimIsoOutputTrailingSeparator(destinationDir)}/${baseName} (${suffix})${extension}`
  7412. }
  7413. return candidatePath
  7414. }
  7415. private sanitizeIsoOutputFileName(fileName: string): string {
  7416. const lastSegment = this.getIsoLastPathSegment(fileName)
  7417. let sanitized = ''
  7418. for (let i = 0; i < lastSegment.length; i++) {
  7419. const char = lastSegment[i]
  7420. if (char === '/' || char === '\\' || char === ':' || char === '*' || char === '?' || char === '"' ||
  7421. char === '<' || char === '>' || char === '|') {
  7422. sanitized += '_'
  7423. } else {
  7424. sanitized += char
  7425. }
  7426. }
  7427. if (sanitized.trim().length === 0) {
  7428. return 'iso_audio.bin'
  7429. }
  7430. return sanitized
  7431. }
  7432. private getIsoLastPathSegment(path: string): string {
  7433. const normalizedPath = path.replace(/\\/g, '/')
  7434. const lastSeparator = normalizedPath.lastIndexOf('/')
  7435. if (lastSeparator < 0) {
  7436. return normalizedPath
  7437. }
  7438. return normalizedPath.substring(lastSeparator + 1)
  7439. }
  7440. private getIsoOutputFileExtension(fileName: string): string {
  7441. const lastDot = fileName.lastIndexOf('.')
  7442. if (lastDot < 0) {
  7443. return ''
  7444. }
  7445. return fileName.substring(lastDot)
  7446. }
  7447. private trimIsoOutputTrailingSeparator(path: string): string {
  7448. if (path.endsWith('/')) {
  7449. return path.substring(0, path.length - 1)
  7450. }
  7451. return path
  7452. }
  7453. private cancelIsoExtraction(reason?: string): void {
  7454. const currentTask = this.isoExtractTask
  7455. Logger.info(TAG,
  7456. `heanup ISO cancel request reason=${reason || ''}, hasTask=${currentTask ? 'true' : 'false'}`)
  7457. this.isoExtractCanceled = true
  7458. this.isoExtractCancelMessage = reason ? reason : ''
  7459. this.isoExtractTask = undefined
  7460. this.updateIsoExtractProgressState(this.isoExtractProgress, '正在停止提取...', this.isoExtractCurrentEntryName, true)
  7461. if (currentTask) {
  7462. try {
  7463. taskpool.terminateTask(currentTask)
  7464. } catch (error) {
  7465. Logger.error(TAG, `heanup 终止 ISO 提取任务失败: ${(error as Error).message}`)
  7466. }
  7467. }
  7468. }
  7469. private moveIsoExtractionToBackground(): void {
  7470. this.closeIsoDialog(false)
  7471. ToastUtil.showToast('ISO 提取已转入后台')
  7472. }
  7473. private async extractSelectedIsoAudioFiles(): Promise<void> {
  7474. if (this.isIsoExtracting) {
  7475. return
  7476. }
  7477. if (ArrayUtil.isEmpty(this.selectedIsoAudioPaths)) {
  7478. ToastUtil.showToast('请先选择要提取的文件')
  7479. return
  7480. }
  7481. const selectedPathSet: Set<string> = new Set<string>(this.selectedIsoAudioPaths)
  7482. const selectedEntries = this.isoAudioEntries
  7483. .filter((entry: IsoArchiveAudioEntry) => selectedPathSet.has(entry.path))
  7484. if (ArrayUtil.isEmpty(selectedEntries)) {
  7485. ToastUtil.showToast('未找到要提取的文件')
  7486. return
  7487. }
  7488. const hasSacdTrack: boolean = selectedEntries.some((entry: IsoArchiveAudioEntry) => entry.entryType === 'sacd_track')
  7489. const destinationDir: string = this.currentPath
  7490. this.isIsoExtracting = true
  7491. this.isoExtractCanceled = false
  7492. this.isoExtractCancelMessage = ''
  7493. this.isoExtractDestinationDir = destinationDir
  7494. Logger.info(TAG,
  7495. `heanup ISO extract start file=${this.isoSourceFilePath}, selected=${selectedEntries.length}, ` +
  7496. `hasSacd=${hasSacdTrack}, destinationDir=${destinationDir}`)
  7497. Logger.info(TAG,
  7498. `heanup ISO selected entries: ${selectedEntries.map((entry: IsoArchiveAudioEntry) => entry.path).join(', ')}`)
  7499. this.resetIsoExtractProgressState()
  7500. this.updateIsoExtractProgressState(1, '准备提取 1%', '', true)
  7501. this.startIsoExtractProgressWatcher(selectedEntries, destinationDir)
  7502. try {
  7503. const extractStartedAt = Date.now()
  7504. const outputPaths: string[] = this.buildIsoExtractExpectedOutputPaths(selectedEntries, destinationDir)
  7505. const payloadJson = JSON.stringify({
  7506. isoPath: this.isoSourceFilePath,
  7507. destinationDir,
  7508. entries: selectedEntries,
  7509. outputPaths
  7510. })
  7511. const task = new taskpool.Task(extractIsoAudioEntriesTask, payloadJson)
  7512. this.isoExtractTask = task
  7513. task.onReceiveData((progressData: IsoExtractProgressMessage) => {
  7514. this.markIsoExtractActivity()
  7515. const progress = typeof progressData.progress === 'number' ? Math.floor(progressData.progress) : 0
  7516. Logger.info(TAG,
  7517. `heanup ISO task receive stage=${progressData.stage || ''}, progress=${progress}, name=${progressData.name || ''}`)
  7518. if (progress > 1 && !this.isoExtractReceivedTaskProgress) {
  7519. this.isoExtractReceivedTaskProgress = true
  7520. if (this.isoExtractProgressTimer) {
  7521. clearInterval(this.isoExtractProgressTimer)
  7522. this.isoExtractProgressTimer = 0
  7523. }
  7524. Logger.info(TAG, `heanup ISO 提取切换为任务进度: progress=${progress}, stage=${progressData.stage || ''}`)
  7525. }
  7526. const stageText = progressData.stage === 'prepare' ? '准备提取' :
  7527. (progressData.stage === 'done' ? '提取完成' : (progressData.stage === 'error' ? '提取异常' : '正在提取'))
  7528. if (progress > this.isoExtractDisplayedProgress || progressData.stage !== 'extract') {
  7529. Logger.info(TAG,
  7530. `heanup ISO 提取任务进度: stage=${progressData.stage || ''}, progress=${progress}, ` +
  7531. `name=${progressData.name || ''}`)
  7532. }
  7533. this.updateIsoExtractProgressState(progress, `${stageText} ${progress}%`, progressData.name || '')
  7534. })
  7535. const result = await taskpool.execute(task, taskpool.Priority.HIGH) as IsoExtractTaskResult
  7536. const extractElapsedMs = Date.now() - extractStartedAt
  7537. this.isoExtractTask = undefined
  7538. Logger.info(TAG, `heanup ISO extract task completed canceled=${this.isoExtractCanceled}, elapsedMs=${extractElapsedMs}`)
  7539. if (this.isoExtractCanceled) {
  7540. return
  7541. }
  7542. const extractedPaths = result?.extractedPaths || []
  7543. const failedEntries = result?.failedEntries || []
  7544. const failureDetails = result?.failureDetails || []
  7545. Logger.info(TAG,
  7546. `heanup ISO extract result extracted=${extractedPaths.length}, failed=${failedEntries.length}, details=${failureDetails.length}`)
  7547. let importErrorMessage: string = ''
  7548. let importedCount: number = 0
  7549. if (ArrayUtil.isNotEmpty(extractedPaths)) {
  7550. const importStartedAt = Date.now()
  7551. try {
  7552. await this.postProcessExtractedIsoFiles(extractedPaths, selectedEntries, outputPaths)
  7553. importedCount = await this.importExtractedFilesToDirectory(extractedPaths, destinationDir)
  7554. Logger.info(TAG,
  7555. `heanup ISO import extracted files success elapsedMs=${Date.now() - importStartedAt}, ` +
  7556. `importedCount=${importedCount}`)
  7557. } catch (importError) {
  7558. importErrorMessage = (importError as Error).message || '导入媒体库失败'
  7559. Logger.error(TAG,
  7560. `heanup ISO import extracted files failed elapsedMs=${Date.now() - importStartedAt}, ` +
  7561. `message=${importErrorMessage}`)
  7562. }
  7563. }
  7564. if (extractedPaths.length > 0 && failedEntries.length > 0) {
  7565. if (StrUtil.isNotEmpty(importErrorMessage)) {
  7566. ToastUtil.showToast(`提取完成,成功 ${extractedPaths.length} 个,失败 ${failedEntries.length} 个,导入失败`)
  7567. } else if (importedCount > 0) {
  7568. ToastUtil.showToast(`提取完成,成功 ${extractedPaths.length} 个,失败 ${failedEntries.length} 个,已入库 ${importedCount} 个音频文件`)
  7569. } else {
  7570. ToastUtil.showToast(`提取完成,成功 ${extractedPaths.length} 个,失败 ${failedEntries.length} 个`)
  7571. }
  7572. } else if (extractedPaths.length > 0) {
  7573. if (StrUtil.isNotEmpty(importErrorMessage)) {
  7574. ToastUtil.showToast(`提取完成,但导入媒体库失败: ${importErrorMessage}`)
  7575. } else if (importedCount > 0) {
  7576. ToastUtil.showToast(`提取完成,已提取 ${extractedPaths.length} 个文件,入库 ${importedCount} 个音频文件`)
  7577. } else {
  7578. ToastUtil.showToast(`提取完成,已提取 ${extractedPaths.length} 个文件`)
  7579. }
  7580. } else if (ArrayUtil.isNotEmpty(failureDetails)) {
  7581. const firstFailure: IsoExtractFailureDetail = failureDetails[0]
  7582. const reasonText = firstFailure.reason && firstFailure.reason.length > 0 ? firstFailure.reason : '提取失败'
  7583. ToastUtil.showToast(reasonText)
  7584. } else if (hasSacdTrack) {
  7585. ToastUtil.showToast('SACD ISO 轨道提取失败')
  7586. } else {
  7587. ToastUtil.showToast('提取失败')
  7588. }
  7589. } catch (error) {
  7590. this.isoExtractTask = undefined
  7591. if (this.isoExtractCanceled) {
  7592. return
  7593. }
  7594. Logger.error(TAG, `heanup 提取 ISO 文件失败: ${(error as Error).message}`)
  7595. ToastUtil.showToast('提取 ISO 文件失败')
  7596. } finally {
  7597. const shouldResetDialogState: boolean = this.isoComponentId <= 0
  7598. this.stopIsoExtractProgressWatcher()
  7599. this.isoExtractTask = undefined
  7600. this.isIsoExtracting = false
  7601. Logger.info(TAG,
  7602. `heanup ISO extract finally canceled=${this.isoExtractCanceled}, cancelMessage=${this.isoExtractCancelMessage}`)
  7603. if (this.isoExtractCanceled && this.isoExtractCancelMessage.length > 0) {
  7604. ToastUtil.showToast(this.isoExtractCancelMessage)
  7605. }
  7606. this.isoExtractCanceled = false
  7607. this.isoExtractCancelMessage = ''
  7608. if (shouldResetDialogState) {
  7609. this.resetIsoDialogState()
  7610. } else {
  7611. this.selectedIsoAudioPaths = []
  7612. this.resetIsoExtractProgressState()
  7613. }
  7614. }
  7615. }
  7616. private async postProcessExtractedIsoFiles(extractedPaths: Array<string>, selectedEntries: Array<IsoArchiveAudioEntry>,
  7617. outputPaths: Array<string>): Promise<void> {
  7618. if (ArrayUtil.isEmpty(extractedPaths) || ArrayUtil.isEmpty(selectedEntries) || ArrayUtil.isEmpty(outputPaths)) {
  7619. return
  7620. }
  7621. const entryByOutputPath: Map<string, IsoArchiveAudioEntry> = new Map<string, IsoArchiveAudioEntry>()
  7622. for (let i = 0; i < outputPaths.length && i < selectedEntries.length; i++) {
  7623. entryByOutputPath.set(outputPaths[i], selectedEntries[i])
  7624. }
  7625. for (let i = 0; i < extractedPaths.length; i++) {
  7626. const extractedPath = extractedPaths[i]
  7627. const entry = entryByOutputPath.get(extractedPath)
  7628. if (!entry) {
  7629. continue
  7630. }
  7631. await this.postProcessExtractedIsoEntry(extractedPath, entry)
  7632. }
  7633. }
  7634. private async postProcessExtractedIsoEntry(filePath: string, entry: IsoArchiveAudioEntry): Promise<void> {
  7635. if (!Utility.isMusicByExtension(filePath)) {
  7636. return
  7637. }
  7638. const hasEmbeddedMetadata: boolean = StrUtil.isNotEmpty(entry.title) || StrUtil.isNotEmpty(entry.album) ||
  7639. StrUtil.isNotEmpty(entry.artist) || StrUtil.isNotEmpty(entry.albumArtist) || StrUtil.isNotEmpty(entry.comment) ||
  7640. !!(entry.trackNumber && entry.trackNumber > 0)
  7641. if (entry.entryType !== 'sacd_track' && !hasEmbeddedMetadata) {
  7642. return
  7643. }
  7644. const tags: FFMpegTags = this.buildIsoExtractedMetadata(entry)
  7645. if (Object.keys(tags).length > 0) {
  7646. try {
  7647. const metadataResult = await repairAudioMetadata(filePath, '', tags, true, '')
  7648. Logger.info(TAG,
  7649. `heanup ISO metadata post-process path=${filePath}, success=${metadataResult}, type=${entry.entryType || ''}`)
  7650. } catch (error) {
  7651. Logger.error(TAG, `heanup ISO metadata post-process failed path=${filePath}, message=${(error as Error).message}`)
  7652. }
  7653. }
  7654. if (!filePath.toLowerCase().endsWith('.dsf')) {
  7655. return
  7656. }
  7657. const coverUrl = await this.resolveIsoExtractCoverUrl(entry)
  7658. if (StrUtil.isEmpty(coverUrl)) {
  7659. return
  7660. }
  7661. try {
  7662. const coverResult = await changeMusicCover(this.context, filePath, coverUrl, true, '')
  7663. Logger.info(TAG, `heanup ISO cover post-process path=${filePath}, success=${coverResult}`)
  7664. } catch (error) {
  7665. Logger.error(TAG, `heanup ISO cover post-process failed path=${filePath}, message=${(error as Error).message}`)
  7666. }
  7667. }
  7668. private buildIsoExtractedMetadata(entry: IsoArchiveAudioEntry): FFMpegTags {
  7669. const metadata: FFMpegTags = {}
  7670. const title = entry.title || this.getIsoEntryBaseName(entry.name || entry.path)
  7671. if (StrUtil.isNotEmpty(title)) {
  7672. metadata.title = title
  7673. metadata.TITLE = title
  7674. }
  7675. if (StrUtil.isNotEmpty(entry.artist)) {
  7676. metadata.artist = entry.artist
  7677. metadata.ARTIST = entry.artist
  7678. }
  7679. if (StrUtil.isNotEmpty(entry.album)) {
  7680. metadata.album = entry.album
  7681. metadata.ALBUM = entry.album
  7682. }
  7683. if (entry.trackNumber && entry.trackNumber > 0) {
  7684. metadata.track = `${entry.trackNumber}`
  7685. metadata.TRACK = `${entry.trackNumber}`
  7686. }
  7687. if (StrUtil.isNotEmpty(entry.albumArtist)) {
  7688. metadata.ALBUMARTIST = entry.albumArtist
  7689. metadata.album_artist = entry.albumArtist
  7690. metadata.TPE2 = entry.albumArtist
  7691. }
  7692. if (StrUtil.isNotEmpty(entry.comment)) {
  7693. metadata.comment = entry.comment
  7694. metadata.COMMENT = entry.comment
  7695. metadata.COMM = entry.comment
  7696. }
  7697. return metadata
  7698. }
  7699. private getIsoEntryBaseName(fileName: string): string {
  7700. const lastSegment = this.getIsoLastPathSegment(fileName)
  7701. const lastDot = lastSegment.lastIndexOf('.')
  7702. if (lastDot <= 0) {
  7703. return lastSegment
  7704. }
  7705. return lastSegment.substring(0, lastDot)
  7706. }
  7707. private async resolveIsoExtractCoverUrl(entry: IsoArchiveAudioEntry): Promise<string> {
  7708. const title = entry.title || this.getIsoEntryBaseName(entry.name || entry.path)
  7709. const artist = entry.artist || entry.albumArtist || ''
  7710. if (StrUtil.isEmpty(title) || PreferencesUtil.getStringSync('COVER_API', '') === '') {
  7711. return ''
  7712. }
  7713. try {
  7714. const coverUrl = await NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', ''))
  7715. if (StrUtil.isNotEmpty(coverUrl) && coverUrl !== 'unknown') {
  7716. return coverUrl
  7717. }
  7718. } catch (error) {
  7719. Logger.error(TAG,
  7720. `heanup ISO resolve cover failed title=${title}, artist=${artist}, message=${(error as Error).message}`)
  7721. }
  7722. return ''
  7723. }
  7724. private async importExtractedFilesToDirectory(paths: Array<string>, destinationDir: string): Promise<number> {
  7725. if (ArrayUtil.isEmpty(paths)) {
  7726. return 0
  7727. }
  7728. let importedCount: number = 0
  7729. for (let i = 0; i < paths.length; i++) {
  7730. const filePath = paths[i]
  7731. if (destinationDir === this.lockPath || !Utility.isMeidaByExtension(filePath) ||
  7732. filePath.endsWith('.lrc') || filePath.endsWith('.srt') || Utility.isIsoByExtension(filePath)) {
  7733. continue
  7734. }
  7735. const mediaItem = await Utility.uriGetMusicAssetsFromFile(this.context, filePath,
  7736. CommonConstants.TYPE_LOCAL, this.autoParseMusicName)
  7737. await new Promise<void>((resolve) => {
  7738. this.table.insert(mediaItem, (_id: number) => resolve())
  7739. })
  7740. importedCount++
  7741. }
  7742. this.cache.delete(destinationDir)
  7743. if (this.currentPath === destinationDir) {
  7744. this.pageCache.clear()
  7745. this.pageHasMoreCache.clear()
  7746. this.pageTotalCountCache.clear()
  7747. if (destinationDir === this.lockPath) {
  7748. this.getSortedFiles(destinationDir, true)
  7749. } else {
  7750. await this.resetAndLoadFirstPage()
  7751. }
  7752. }
  7753. return importedCount
  7754. }
  7755. private resetIsoDialogState(): void {
  7756. this.isoAudioEntries = []
  7757. this.selectedIsoAudioPaths = []
  7758. this.isoSourceFileName = ''
  7759. this.isoSourceFilePath = ''
  7760. this.isoExtractDestinationDir = ''
  7761. this.isIsoExtracting = false
  7762. this.stopIsoExtractProgressWatcher()
  7763. this.isoExtractTask = undefined
  7764. this.resetIsoExtractProgressState()
  7765. }
  7766. private closeIsoDialog(reset: boolean = true): void {
  7767. if (this.isoComponentId > 0) {
  7768. try {
  7769. this.getUIContext().getPromptAction().closeCustomDialog(this.isoComponentId)
  7770. } catch (_error) {
  7771. }
  7772. this.isoComponentId = 0
  7773. }
  7774. if (!reset) {
  7775. return
  7776. }
  7777. this.resetIsoDialogState()
  7778. }
  7779. @Builder
  7780. isoComptentBuilder() {
  7781. IsoExtractComptent({
  7782. isoFileName: this.isoSourceFileName,
  7783. entries: this.isoAudioEntries,
  7784. selectedPaths: this.selectedIsoAudioPaths,
  7785. isLongNameRoLL: this.isLongNameRoLL,
  7786. isExtracting: this.isIsoExtracting,
  7787. extractProgress: this.isoExtractProgress,
  7788. extractProgressText: this.isoExtractProgressText,
  7789. extractCurrentName: this.isoExtractCurrentEntryName,
  7790. onToggleSelection: (path: string, checked: boolean) => {
  7791. this.toggleIsoEntrySelection(path, checked)
  7792. },
  7793. onToggleSelectAll: () => {
  7794. this.toggleIsoEntrySelectAll()
  7795. },
  7796. onExtract: async () => {
  7797. await this.extractSelectedIsoAudioFiles()
  7798. },
  7799. onRunInBackground: () => {
  7800. this.moveIsoExtractionToBackground()
  7801. },
  7802. onStopExtract: () => {
  7803. this.cancelIsoExtraction('已取消 ISO 提取')
  7804. },
  7805. onCancel: () => {
  7806. if (this.isIsoExtracting) {
  7807. this.moveIsoExtractionToBackground()
  7808. return
  7809. }
  7810. this.closeIsoDialog()
  7811. }
  7812. })
  7813. }
  7814. private cueComponentId: number = 0
  7815. private async handleCueTrackImport(cueinfo: CueInfo): Promise<void> {
  7816. try {
  7817. let sourceItem = Utility.getItemByFilePath(this.videoLocalList, cueinfo.filePath);
  7818. if (!sourceItem) {
  7819. sourceItem = await this.table.queryVideoByFilePath(cueinfo.filePath) || undefined;
  7820. }
  7821. const importedItems = await importCueTracks(this.context, this.table, cueinfo, sourceItem);
  7822. if (ArrayUtil.isEmpty(importedItems)) {
  7823. ToastUtil.showToast('未导入到任何分轨');
  7824. return;
  7825. }
  7826. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId);
  7827. await this.resetAndLoadFirstPage();
  7828. ToastUtil.showToast(`分轨完成,已入库 ${importedItems.length} 首`);
  7829. } catch (error) {
  7830. Logger.error(TAG, `CUE 分轨入库失败: ${(error as Error).message}`);
  7831. ToastUtil.showToast('分轨失败');
  7832. }
  7833. }
  7834. //显示cue分轨列表对话框
  7835. showCueDialog(cueTracks:CueTrack[],cueinfo:CueInfo){
  7836. this.getUIContext().getPromptAction().openCustomDialog({
  7837. builder: () => {
  7838. this.cueComptentBuilder(cueTracks,cueinfo)
  7839. },
  7840. isModal:true,
  7841. showInSubWindow:false,
  7842. maskColor: Color.Transparent,
  7843. dialogTransition: // 设置弹窗内容显示的过渡效果
  7844. TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  7845. .animation({ duration: 600, curve: Curve.Smooth }),
  7846. maskTransition: // 设置蒙层显示的过渡效果
  7847. TransitionEffect.opacity(0.5)
  7848. .animation({ duration: 600, curve: Curve.Smooth })
  7849. }).then((dialogId: number) => {
  7850. this.cueComponentId = dialogId
  7851. })
  7852. .catch((error: BusinessError) => {
  7853. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  7854. })
  7855. }
  7856. @Builder
  7857. cueComptentBuilder(cueTracks:CueTrack[]=[],cueinfo:CueInfo){
  7858. CueComptent({
  7859. title:cueinfo.title,
  7860. cueTracks:cueTracks,
  7861. isLongNameRoLL:this.isLongNameRoLL,
  7862. onCancel:()=>{
  7863. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId)
  7864. },
  7865. onSplitTracks: async ()=>{
  7866. await this.handleCueTrackImport(cueinfo)
  7867. },
  7868. onDoItemClick: async (item: CueTrack, index: number)=>{
  7869. //获取cueinfo对应的filePath
  7870. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  7871. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, cueinfo.filePath)
  7872. this.currentSong = Utility.getItemByFilePath(globalVideoList, cueinfo.filePath)
  7873. console.info('onecold cueinfo.filePath=', cueinfo.filePath)
  7874. console.info('onecold this.currentSong =', JSON.stringify(this.currentSong))
  7875. if (this.currentSong){
  7876. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  7877. this.stop();//播放之前先停止之前播放。
  7878. }
  7879. this.songList = globalVideoList
  7880. this.sonDataSource.pushArrayData(this.songList)
  7881. if (this.currentSong) {
  7882. try {
  7883. const cueUrl = await this.resolvePlaybackUrlForCurrentSong('cue-track-play');
  7884. if (!cueUrl) {
  7885. return;
  7886. }
  7887. this.videoUrl = cueUrl;
  7888. } catch (error) {
  7889. Logger.error(TAG, `CUE 点播构建播放地址失败: ${(error as Error).message}`);
  7890. this.videoUrl = this.currentSong.filePath;
  7891. }
  7892. }
  7893. this.name = item.title||this.currentSong.name
  7894. this.cover = this.currentSong.pixelMapPath
  7895. this.artist = item.performer||this.currentSong.artist
  7896. this.currentSong.name = this.name
  7897. this.currentSong.artist = this.artist
  7898. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  7899. this.startPlayOrResumePlay(item.startOffset)//从cue的某个位置开始播放
  7900. }
  7901. }
  7902. })
  7903. }
  7904. @State isFrontWhite: boolean = false
  7905. private showCoverScaleGuideIfNeeded(): void {
  7906. const hasShown = PreferencesUtil.getBooleanSync(PREF_PLAY_COVER_SCALE_GUIDE_SHOWN, false)
  7907. if (hasShown) {
  7908. return
  7909. }
  7910. this.isShowCoverScaleGuide = true
  7911. setTimeout(() => {
  7912. if (this.isShowCoverScaleGuide) {
  7913. this.dismissCoverScaleGuide()
  7914. }
  7915. }, 9000)
  7916. }
  7917. private dismissCoverScaleGuide(): void {
  7918. this.isShowCoverScaleGuide = false
  7919. PreferencesUtil.put(PREF_PLAY_COVER_SCALE_GUIDE_SHOWN, true)
  7920. }
  7921. setShowPlayTrue(){
  7922. this.getUIContext()?.animateTo({
  7923. duration: 500,
  7924. curve: Curve.Friction
  7925. }, () => {
  7926. this.isShowPlay = true;
  7927. this.showCoverScaleGuideIfNeeded()
  7928. });
  7929. }
  7930. setShowPlayFalse(){
  7931. this.getUIContext()?.animateTo({
  7932. duration: 500,
  7933. curve: Curve.Friction
  7934. }, () => {
  7935. this.isShowPlay = false;
  7936. });
  7937. this.isShowCoverScaleGuide = false
  7938. }
  7939. //打开播放页
  7940. showPlayerView() {
  7941. this.showCoverScaleGuideIfNeeded()
  7942. console.info('onecold showPlayerView this.songList'+ JSON.stringify(this.songList))
  7943. if (ArrayUtil.isNotEmpty(this.songList)) {
  7944. // this.setShowPlayTrue()
  7945. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
  7946. this.initLyric(lyricPath);
  7947. this.startAutoHide();
  7948. } else {
  7949. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  7950. }
  7951. }
  7952. //打开播放列表
  7953. openPlayList(){
  7954. if (ArrayUtil.isNotEmpty(this.songList)) {
  7955. this.isShowSheet = !this.isShowSheet;
  7956. this.isFrontWhite = false
  7957. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  7958. this.scrollIndex()
  7959. // 只有在播放本地音乐时才自动加载完整列表
  7960. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_LOCAL) {
  7961. void this.hydrateFullMediaPlayListIfNeeded();
  7962. }
  7963. } else {
  7964. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  7965. }
  7966. }
  7967. scrollIndex(){
  7968. try {
  7969. setTimeout(() => {
  7970. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  7971. if(this.curIndex>60){
  7972. this.playListScroller.scrollToIndex(this.curIndex,false, ScrollAlign.CENTER)
  7973. }else{
  7974. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  7975. }
  7976. })
  7977. }, 123)
  7978. }catch (error) {
  7979. console.error(`onecold scrollIndex出错: ${error}`);
  7980. }
  7981. }
  7982. scrollIndexMain(dialogId?:string){
  7983. try {
  7984. setTimeout(() => {
  7985. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  7986. console.info('heanup scrollIndexMain this.curIndex='+this.curIndex)
  7987. if(dialogId)
  7988. DialogHelper.closeDialog(dialogId)
  7989. let isAni:boolean = false
  7990. if(this.curIndex<50){
  7991. isAni = true
  7992. }
  7993. if(this.twoFingerType==4){
  7994. this.waterScroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  7995. }else{
  7996. if(this.isGridMusic){
  7997. this.scroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  7998. }else{
  7999. this.listScroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  8000. }
  8001. }
  8002. })
  8003. }, 123)
  8004. }catch (error) {
  8005. console.error(`onecold scrollIndexMain出错: ${error}`);
  8006. }
  8007. }
  8008. // 智能定位当前播放歌曲,如果当前页没有则加载完整列表
  8009. async locateCurrentSong(): Promise<void> {
  8010. if (!this.currentSong) {
  8011. console.warn("heanup locateCurrentSong: 当前没有播放的歌曲");
  8012. return;
  8013. }
  8014. // 检查当前播放歌曲是否在已加载的列表中
  8015. const targetIndex = Utility.getIndexFromList(this.videoLocalList, this.currentSong.filePath);
  8016. if (targetIndex > 0) {
  8017. // 歌曲在当前列表中,直接滚动
  8018. console.info("heanup locateCurrentSong: 找到歌曲,索引=" + targetIndex);
  8019. this.curIndex = targetIndex;
  8020. this.scrollIndexMain();
  8021. } else {
  8022. // 歌曲不在当前列表中,加载当前歌曲再第几页完整列表后再定位
  8023. console.info("heanup locateCurrentSong: 歌曲不在当前列表,开始加载完整列表");
  8024. const dialogID = DialogHelper.showLoadingDialog()
  8025. await this.hydrateFullMediaPlayListIfNeeded(false);
  8026. this.curIndex = Utility.getIndexFromList(this.videoLocalList, this.currentSong.filePath);
  8027. this.scrollIndexMain(dialogID);
  8028. }
  8029. }
  8030. //播放列表布局
  8031. @Builder
  8032. PlayListSheet() {
  8033. Column() {
  8034. this.PlayList()
  8035. }
  8036. .width('100%')
  8037. .height('100%')
  8038. }
  8039. @State titleStr: string = ''
  8040. @State ablumStr: string = ''
  8041. @State artistStr: string = ''
  8042. @State lyricConStr: string = ''
  8043. @State currentEditItem: string = ''
  8044. @State yearStr: string = ''
  8045. @State trackStr: string = ''
  8046. @State genreStr: string = ''
  8047. @State imagePathStr: string = ''
  8048. @State albumArtistStr: string = ''
  8049. @State composerStr: string = ''
  8050. @State lyricistStr: string = ''
  8051. @State commentStr: string = ''
  8052. @State discStr: string = ''
  8053. doUpdateData() {
  8054. setTimeout(async () => {
  8055. if (this.modeType === 0) {
  8056. this.deleteCache(this.currentPath)
  8057. await this.resetAndLoadFirstPage();
  8058. }else if (this.modeType === 1){
  8059. await this.resetAndLoadFirstPage();
  8060. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  8061. }
  8062. }, 500)
  8063. }
  8064. doAllUpdateData() {
  8065. setTimeout(async () => {
  8066. if (this.modeType === 0) {
  8067. this.deleteCache(this.currentPath)
  8068. await this.resetAndLoadFirstPage();
  8069. }else{
  8070. await this.resetAndLoadFirstPage();
  8071. }
  8072. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  8073. workerInstance.postMessage({ code: 3, data: this.context });
  8074. workerInstance.postMessage({ code: 4, data: this.context });
  8075. }, 999)
  8076. }
  8077. private delayMs(ms: number): Promise<void> {
  8078. return new Promise(resolve => {
  8079. setTimeout(() => resolve(), ms);
  8080. });
  8081. }
  8082. private async appendItemsSmoothly(items: VideoItem[]): Promise<void> {
  8083. if (!items || items.length === 0) {
  8084. return;
  8085. }
  8086. const isMediaLibraryListMode = this.isMediaLibraryListMode();
  8087. const isHeavyGridWaterMode = this.isGridMusic || this.twoFingerType == 4;
  8088. const directAppendThreshold = isHeavyGridWaterMode ? 8 : (isMediaLibraryListMode ? 6 : 12);
  8089. if (!this.isScrolling || items.length <= directAppendThreshold) {
  8090. this.videoLocalList.push(...items);
  8091. this.dataSource.appendArrayData(items);
  8092. return;
  8093. }
  8094. const chunkSize = isHeavyGridWaterMode
  8095. ? Math.max(3, Math.min(6, Math.floor(this.pageSize * 0.15)))
  8096. : (isMediaLibraryListMode
  8097. ? Math.max(2, Math.min(4, Math.floor(this.pageSize * 0.08)))
  8098. : Math.max(4, Math.min(8, Math.floor(this.pageSize * 0.18))));
  8099. const chunkDelay = isHeavyGridWaterMode ? 12 : (isMediaLibraryListMode ? 10 : 8);
  8100. for (let index = 0; index < items.length; index += chunkSize) {
  8101. const chunk = items.slice(index, Math.min(index + chunkSize, items.length));
  8102. this.videoLocalList.push(...chunk);
  8103. this.dataSource.appendArrayData(chunk);
  8104. if (index + chunkSize < items.length) {
  8105. await this.delayMs(chunkDelay);
  8106. }
  8107. }
  8108. }
  8109. /**
  8110. * 加载指定页的数据
  8111. */
  8112. private async loadPage(pageIndex: number, append: boolean = true): Promise<void> {
  8113. try {
  8114. // 1. 检查缓存
  8115. if (this.pageCache.has(pageIndex)) {
  8116. Logger.info('heanup LocalMusic', `loadPage: 从缓存加载 page=${pageIndex}`);
  8117. const inMediaLibraryWarmup = this.modeType === 1 && pageIndex === 0 && !append && this.isMediaLibraryWarmupWindow();
  8118. const cachedData = this.pageCache.get(pageIndex)!;
  8119. const cachedHasMore = this.pageHasMoreCache.get(pageIndex);
  8120. const cachedTotal = this.pageTotalCountCache.get(pageIndex);
  8121. if (cachedHasMore !== undefined) {
  8122. this.hasMoreData = cachedHasMore;
  8123. }
  8124. if (cachedTotal !== undefined) {
  8125. this.totalCount = cachedTotal;
  8126. if (this.modeType === 1) {
  8127. this.mediaKuCount = cachedTotal;
  8128. }
  8129. }
  8130. if (append) {
  8131. this.prefetchListThumbsFromItems(cachedData, 26);
  8132. this.prefetchGridWaterThumbsFromItems(cachedData, this.twoFingerType == 4 ? 56 : 42);
  8133. await this.appendItemsSmoothly(cachedData);
  8134. } else {
  8135. this.videoLocalList = cachedData;
  8136. this.dataSource.pushArrayData(this.videoLocalList);
  8137. if (inMediaLibraryWarmup) {
  8138. this.prefetchListThumbsFromItems(cachedData, 8);
  8139. } else {
  8140. this.prefetchListThumbsFromItems(cachedData, 30);
  8141. this.prefetchGridWaterThumbsFromItems(cachedData, this.twoFingerType == 4 ? 56 : 42);
  8142. }
  8143. }
  8144. this.setButtonStatus();
  8145. if (inMediaLibraryWarmup) {
  8146. this.scheduleAlphaBetRebuild(900);
  8147. } else {
  8148. this.markAlphaBetDirty();
  8149. }
  8150. if (this.hasMoreData) {
  8151. if (inMediaLibraryWarmup) {
  8152. if (this.mediaLibraryWarmupPrefetchTimer) {
  8153. clearTimeout(this.mediaLibraryWarmupPrefetchTimer);
  8154. }
  8155. this.mediaLibraryWarmupPrefetchTimer = setTimeout(() => {
  8156. this.mediaLibraryWarmupPrefetchTimer = 0;
  8157. if (this.modeType === 1 && !this.isCanBack) {
  8158. this.prefetchFollowingPages(pageIndex + 1);
  8159. }
  8160. }, 900) as number;
  8161. } else {
  8162. this.prefetchFollowingPages(pageIndex + 1);
  8163. }
  8164. }
  8165. return;
  8166. }
  8167. this.isLoadingPage = true;
  8168. Logger.info('heanup LocalMusic', `loadPage: 开始加载 page=${pageIndex}, size=${this.pageSize}, mode=${this.modeType}`);
  8169. // 2. 构造查询参数
  8170. const options: PageQueryOptions = {
  8171. pageIndex: pageIndex,
  8172. pageSize: this.pageSize,
  8173. sortType: this.sortType,
  8174. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  8175. isShowFileName: this.isShowFileName
  8176. };
  8177. // 根据 modeType 补充查询条件
  8178. if (this.modeType === 0) {
  8179. options.parentPath = this.currentPath;
  8180. }
  8181. // 3. 执行查询
  8182. let result: PageQueryResult = { items: [], totalCount: 0, hasMore: false };
  8183. switch (this.modeType) {
  8184. case 0:
  8185. result = await this.table.queryByParentPathPaged(options);
  8186. result.items = this.filterOutLocalIsoItems(result.items);
  8187. // modeType=0时,第一页需要添加文件夹列表
  8188. if (pageIndex === 0 && !this.isSearchMode) {
  8189. const directories: VideoItem[] = await this.loadDirectories(this.currentPath);
  8190. const isoItems: VideoItem[] = this.getLocalIsoItems(this.currentPath);
  8191. result.items = [...directories, ...isoItems, ...result.items];
  8192. result.totalCount += directories.length + isoItems.length;
  8193. }
  8194. break;
  8195. case 1:
  8196. result = await this.table.queryMediaLibraryPaged(options);
  8197. break;
  8198. case 2:
  8199. result = await this.table.queryArtistsPaged(options);
  8200. break;
  8201. case 3:
  8202. result = await this.table.queryAlbumsPaged(options);
  8203. break;
  8204. default:
  8205. result = await this.table.queryMediaLibraryPaged(options);
  8206. break;
  8207. }
  8208. if (!result || result.items.length === 0) {
  8209. Logger.info('heanup LocalMusic', 'loadPage: 查询结果为空');
  8210. this.isLoadingPage = false;
  8211. this.hasMoreData = false;
  8212. // 仅首页为空时清空,后续页为空只终止继续分页
  8213. if (pageIndex === 0) {
  8214. this.totalCount = 0;
  8215. this.videoLocalList = [];
  8216. this.dataSource.pushArrayData(this.videoLocalList);
  8217. this.setButtonStatus();
  8218. this.markAlphaBetDirty();
  8219. }
  8220. return;
  8221. }
  8222. // 4. 更新状态和缓存
  8223. this.totalCount = result.totalCount;
  8224. this.hasMoreData = result.hasMore;
  8225. if (this.modeType === 1) {
  8226. this.mediaKuCount = result.totalCount;
  8227. }
  8228. if (this.modeType === 2 && result.countMap) {
  8229. this.mergeArtistCountMap(result.countMap);
  8230. } else if (this.modeType === 3 && result.countMap) {
  8231. this.mergeAlbumCountMap(result.countMap);
  8232. }
  8233. Logger.info('heanup LocalMusic', `loadPage: 查询完成 items=${result.items.length}, total=${result.totalCount}, hasMore=${result.hasMore}`);
  8234. // 缓存管理 - 只保留最近3页
  8235. this.pageCache.set(pageIndex, result.items);
  8236. this.pageHasMoreCache.set(pageIndex, result.hasMore);
  8237. this.pageTotalCountCache.set(pageIndex, result.totalCount);
  8238. this.cleanOldCache(pageIndex);
  8239. // 5. 更新显示列表
  8240. const inMediaLibraryWarmup = this.modeType === 1 && pageIndex === 0 && !append && this.isMediaLibraryWarmupWindow();
  8241. if (append) {
  8242. this.prefetchListThumbsFromItems(result.items, 26);
  8243. this.prefetchGridWaterThumbsFromItems(result.items, this.twoFingerType == 4 ? 56 : 42);
  8244. await this.appendItemsSmoothly(result.items);
  8245. } else {
  8246. this.videoLocalList = result.items;
  8247. this.dataSource.pushArrayData(this.videoLocalList);
  8248. if (inMediaLibraryWarmup) {
  8249. this.prefetchListThumbsFromItems(result.items, 8);
  8250. } else {
  8251. this.prefetchListThumbsFromItems(result.items, 30);
  8252. this.prefetchGridWaterThumbsFromItems(result.items, this.twoFingerType == 4 ? 56 : 42);
  8253. }
  8254. }
  8255. this.setButtonStatus();
  8256. if (inMediaLibraryWarmup) {
  8257. this.scheduleAlphaBetRebuild(900);
  8258. } else {
  8259. this.markAlphaBetDirty();
  8260. }
  8261. if (inMediaLibraryWarmup) {
  8262. if (this.mediaLibraryWarmupPrefetchTimer) {
  8263. clearTimeout(this.mediaLibraryWarmupPrefetchTimer);
  8264. }
  8265. this.mediaLibraryWarmupPrefetchTimer = setTimeout(() => {
  8266. this.mediaLibraryWarmupPrefetchTimer = 0;
  8267. if (this.modeType === 1 && !this.isCanBack) {
  8268. this.prefetchFollowingPages(pageIndex + 1);
  8269. }
  8270. }, 900) as number;
  8271. } else {
  8272. this.prefetchFollowingPages(pageIndex + 1);
  8273. }
  8274. this.isLoadingPage = false;
  8275. } catch (err) {
  8276. const error = err as Error;
  8277. Logger.error('heanup LocalMusic', `loadPage error: ${error.message}`);
  8278. ToastUtil.showToast('加载数据失败');
  8279. this.isLoadingPage = false;
  8280. this.hasMoreData = false;
  8281. }
  8282. }
  8283. /**
  8284. * 清理旧缓存 - 只保留当前页前后各1页
  8285. */
  8286. private cleanOldCache(currentPage: number): void {
  8287. const pagesToKeep = new Set([currentPage - 1, currentPage, currentPage + 1]);
  8288. const keysToDelete: number[] = [];
  8289. this.pageCache.forEach((_, page) => {
  8290. if (!pagesToKeep.has(page)) {
  8291. keysToDelete.push(page);
  8292. }
  8293. });
  8294. keysToDelete.forEach(page => {
  8295. this.pageCache.delete(page);
  8296. this.pageHasMoreCache.delete(page);
  8297. this.pageTotalCountCache.delete(page);
  8298. });
  8299. if (keysToDelete.length > 0) {
  8300. Logger.info('heanup LocalMusic', `cleanOldCache: 清理了 ${keysToDelete.length} 页缓存`);
  8301. }
  8302. }
  8303. private async prefetchNextPage(nextPage: number): Promise<void> {
  8304. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  8305. return;
  8306. }
  8307. if (!this.hasMoreData || this.pageCache.has(nextPage) || this.prefetchingPages.has(nextPage)) {
  8308. return;
  8309. }
  8310. const expectedModeType = this.modeType;
  8311. const expectedSortType = this.sortType;
  8312. const expectedIsShowFileName = this.isShowFileName;
  8313. const expectedSearchKeyword = this.isSearchMode ? this.searchText : '';
  8314. const expectedParentPath = this.currentPath;
  8315. this.prefetchingPages.add(nextPage);
  8316. try {
  8317. const options: PageQueryOptions = {
  8318. pageIndex: nextPage,
  8319. pageSize: this.pageSize,
  8320. sortType: this.sortType,
  8321. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  8322. isShowFileName: this.isShowFileName
  8323. };
  8324. if (this.modeType === 0) {
  8325. options.parentPath = this.currentPath;
  8326. }
  8327. let result: PageQueryResult = { items: [], totalCount: 0, hasMore: false };
  8328. switch (this.modeType) {
  8329. case 0:
  8330. result = await this.table.queryByParentPathPaged(options);
  8331. result.items = this.filterOutLocalIsoItems(result.items);
  8332. break;
  8333. case 1:
  8334. result = await this.table.queryMediaLibraryPaged(options);
  8335. break;
  8336. case 2:
  8337. result = await this.table.queryArtistsPaged(options);
  8338. if (result.countMap) {
  8339. this.mergeArtistCountMap(result.countMap);
  8340. }
  8341. break;
  8342. case 3:
  8343. result = await this.table.queryAlbumsPaged(options);
  8344. if (result.countMap) {
  8345. this.mergeAlbumCountMap(result.countMap);
  8346. }
  8347. break;
  8348. default:
  8349. result = await this.table.queryMediaLibraryPaged(options);
  8350. break;
  8351. }
  8352. const currentSearchKeyword = this.isSearchMode ? this.searchText : '';
  8353. if (expectedModeType !== this.modeType ||
  8354. expectedSortType !== this.sortType ||
  8355. expectedIsShowFileName !== this.isShowFileName ||
  8356. expectedSearchKeyword !== currentSearchKeyword ||
  8357. (expectedModeType === 0 && expectedParentPath !== this.currentPath)) {
  8358. Logger.info('heanup LocalMusic', `prefetchNextPage: 上下文已变化,放弃写入 page=${nextPage}`);
  8359. return;
  8360. }
  8361. this.pageHasMoreCache.set(nextPage, result.hasMore);
  8362. this.pageTotalCountCache.set(nextPage, result.totalCount);
  8363. if (result.items.length > 0) {
  8364. this.pageCache.set(nextPage, result.items);
  8365. this.prefetchGridWaterThumbsFromItems(result.items, this.twoFingerType == 4 ? 48 : 36);
  8366. this.cleanOldCache(nextPage);
  8367. if (nextPage === this.currentPage + 1 && !this.isLoadingPage && !this.isPagingTransition
  8368. && this.lastVisibleEndIndex >= 0 && this.videoLocalList.length > 0) {
  8369. const seenRatio = (this.lastVisibleEndIndex + 1) / Math.max(this.videoLocalList.length, 1);
  8370. if (seenRatio >= Math.max(0.14, this.getDynamicAppendStartRatio() - 0.12)) {
  8371. Logger.info('heanup LocalMusic',
  8372. `prefetchNextPage: 下一页缓存已就绪,提前衔接 page=${nextPage}, ratio=${seenRatio}`);
  8373. this.scheduleLoadNextPage(8);
  8374. }
  8375. }
  8376. }
  8377. } catch (err) {
  8378. const error = err as Error;
  8379. Logger.warn('heanup LocalMusic', `prefetchNextPage error: ${error.message}`);
  8380. } finally {
  8381. this.prefetchingPages.delete(nextPage);
  8382. }
  8383. }
  8384. private mergeArtistCountMap(countMap: Map<string, number>): void {
  8385. const nextMap = new Map(this.artistSongCountMap);
  8386. countMap.forEach((count, artist) => {
  8387. nextMap.set(artist, count);
  8388. });
  8389. this.artistSongCountMap = nextMap;
  8390. }
  8391. private mergeAlbumCountMap(countMap: Map<string, number>): void {
  8392. const nextMap = new Map(this.albumSongCountMap);
  8393. countMap.forEach((count, album) => {
  8394. nextMap.set(album, count);
  8395. });
  8396. this.albumSongCountMap = nextMap;
  8397. }
  8398. private getArtistSongCount(artist: string): number {
  8399. return this.artistSongCountMap.get(artist) ?? this.artistMap.get(artist)?.length ?? 0;
  8400. }
  8401. private getAlbumSongCount(album: string): number {
  8402. return this.albumSongCountMap.get(album) ?? this.albumMap.get(album)?.length ?? 0;
  8403. }
  8404. /**
  8405. * 加载文件夹列表(仅用于modeType=0的首页模式)
  8406. */
  8407. private async loadDirectories(curPath: string): Promise<VideoItem[]> {
  8408. try {
  8409. Logger.info('heanup LocalMusic', `loadDirectories: 开始加载文件夹 path=${curPath}`);
  8410. // 检查缓存
  8411. const cacheKey = curPath + "_dirList";
  8412. const cachedDirList = this.findCache(cacheKey);
  8413. if (cachedDirList !== undefined && Array.isArray(cachedDirList)) {
  8414. Logger.info('heanup LocalMusic', `loadDirectories: 从缓存加载 count=${cachedDirList.length}`);
  8415. return cachedDirList as VideoItem[];
  8416. }
  8417. // 从文件系统读取
  8418. const fileList = FileUtil.listFileSync(curPath);
  8419. const directories: VideoItem[] = [];
  8420. for (let i = 0; i < fileList.length; i++) {
  8421. const path = curPath + '/' + fileList[i];
  8422. if (FileUtil.isDirectory(path)) {
  8423. const item: VideoItem = new VideoItem(
  8424. fileList[i].toString(),
  8425. fileList[i].toString(),
  8426. path,
  8427. CommonConstants.TYPE_IS_DIR,
  8428. 0,
  8429. ''
  8430. );
  8431. if (this.isShowDir(item.name)) {
  8432. directories.push(item);
  8433. }
  8434. }
  8435. }
  8436. // 排序
  8437. Utility.doSortListAscending(directories);
  8438. // 缓存文件夹列表
  8439. if (curPath === this.rootPath) {
  8440. this.dirList = directories;
  8441. this.addCache(cacheKey, directories);
  8442. }
  8443. Logger.info('heanup LocalMusic', `loadDirectories: 加载完成 count=${directories.length}`);
  8444. return directories;
  8445. } catch (err) {
  8446. const error = err as Error;
  8447. Logger.error('heanup LocalMusic', `loadDirectories error: ${error.message}`);
  8448. return [];
  8449. }
  8450. }
  8451. /**
  8452. * 构建播放队列(避免一次性加载全量)
  8453. */
  8454. private buildPlayQueueFromView(): Array<VideoItem> {
  8455. if (this.modeType === 4) {
  8456. this.playQueueScope = 'playlist';
  8457. return this.currentSongList;
  8458. }
  8459. if (this.isHistory) {
  8460. this.playQueueScope = 'history';
  8461. return this.historyList;
  8462. }
  8463. if (this.isFavMusic) {
  8464. this.playQueueScope = 'fav';
  8465. return this.favList;
  8466. }
  8467. this.playQueueScope = 'view';
  8468. return Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL);
  8469. }
  8470. private async tryLoadNextPageForPlayback(): Promise<void> {
  8471. if (this.playQueueScope !== 'view') {
  8472. return;
  8473. }
  8474. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  8475. return;
  8476. }
  8477. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  8478. return;
  8479. }
  8480. await this.loadNextPage();
  8481. const nextList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL);
  8482. if (nextList.length > this.songList.length) {
  8483. this.songList = nextList;
  8484. this.sonDataSource.pushArrayData(this.songList);
  8485. }
  8486. }
  8487. /**
  8488. * 加载更多流媒体歌曲(Navidrome/Jellyfin/Emby/AudioStation/Plex)
  8489. * 当播放列表弹窗滚动到底部时调用
  8490. */
  8491. private async loadMoreNavidromeSongs(): Promise<void> {
  8492. const beforeCount = this.songList.length;
  8493. const hasMore = hasMoreData();
  8494. Logger.info('heanup', `开始加载更多流媒体歌曲, 当前数量=${beforeCount}, hasMoreData=${hasMore}`);
  8495. if (!hasMore) {
  8496. Logger.info('heanup', '没有更多数据可加载(hasMoreData=false)');
  8497. return;
  8498. }
  8499. // 触发加载更多(会更新NavidromePlaylistStore中的数据)
  8500. const success = await triggerLoadMoreSongs(1);
  8501. Logger.info('heanup', `triggerLoadMoreSongs返回: ${success}`);
  8502. if (success) {
  8503. // 获取更新后的完整列表
  8504. const updatedList = getNavidromeVideoItems();
  8505. Logger.info('heanup', `更新后列表长度: ${updatedList.length}`);
  8506. if (updatedList.length > beforeCount) {
  8507. Logger.info('heanup', `流媒体歌曲加载成功: ${beforeCount} -> ${updatedList.length}`);
  8508. this.songList = updatedList;
  8509. this.sonDataSource.pushArrayData(this.songList);
  8510. } else {
  8511. Logger.info('heanup', '列表长度未增加');
  8512. }
  8513. } else {
  8514. Logger.info('heanup', '流媒体歌曲加载未返回新数据(triggerLoadMoreSongs=false)');
  8515. }
  8516. }
  8517. /**
  8518. * 重置分页状态并加载首页
  8519. */
  8520. private async resetAndLoadFirstPage(clearExistingList: boolean = true): Promise<void> {
  8521. Logger.info('heanup LocalMusic', 'resetAndLoadFirstPage: 重置分页状态');
  8522. this.currentPage = 0;
  8523. if (clearExistingList) {
  8524. this.videoLocalList = [];
  8525. }
  8526. this.pageCache.clear();
  8527. this.pageHasMoreCache.clear();
  8528. this.pageTotalCountCache.clear();
  8529. this.prefetchingPages.clear();
  8530. this.hasMoreData = true;
  8531. this.totalCount = 0;
  8532. this.lastScrollTriggerPage = -1;
  8533. this.lastVisibleEndIndex = -1;
  8534. this.listScrollAlphaCheckAt = 0;
  8535. this.listScrollPagingCheckAt = 0;
  8536. this.listScrollLastAlphaStart = -1;
  8537. this.listScrollLastPagingEnd = -1;
  8538. this.gridScrollPagingCheckAt = 0;
  8539. this.gridScrollLastPagingEnd = -1;
  8540. this.waterScrollPagingCheckAt = 0;
  8541. this.waterScrollLastPagingEnd = -1;
  8542. this.listVisibleStart = -1;
  8543. this.listVisibleEnd = -1;
  8544. this.listThumbWarmupCheckAt = 0;
  8545. this.listThumbWarmupStart = -1;
  8546. this.listThumbWarmupEnd = -1;
  8547. this.gridThumbWarmupCheckAt = 0;
  8548. this.gridThumbWarmupStart = -1;
  8549. this.gridThumbWarmupEnd = -1;
  8550. this.waterThumbWarmupCheckAt = 0;
  8551. this.waterThumbWarmupStart = -1;
  8552. this.waterThumbWarmupEnd = -1;
  8553. this.gridVisibleStart = -1;
  8554. this.gridVisibleEnd = -1;
  8555. this.waterVisibleStart = -1;
  8556. this.waterVisibleEnd = -1;
  8557. this.gridWaterLastActiveTs = 0;
  8558. this.isPagingTransition = false;
  8559. if (this.pagingScheduleTimer) {
  8560. clearTimeout(this.pagingScheduleTimer);
  8561. this.pagingScheduleTimer = 0;
  8562. }
  8563. if (this.gridWaterScrollIdleTimer) {
  8564. clearTimeout(this.gridWaterScrollIdleTimer);
  8565. this.gridWaterScrollIdleTimer = 0;
  8566. }
  8567. this.coverThumbCache.clearPending();
  8568. this.pendingCoverThumbRefresh = false;
  8569. if (this.modeType === 2) {
  8570. this.artistSongCountMap = new Map();
  8571. } else if (this.modeType === 3) {
  8572. this.albumSongCountMap = new Map();
  8573. }
  8574. await this.loadPage(0, false);
  8575. }
  8576. private markGridWaterScrollingActive(): void {
  8577. if (!this.isScrolling) {
  8578. this.isScrolling = true;
  8579. }
  8580. const now = Date.now();
  8581. if (now - this.gridWaterLastActiveTs < 80) {
  8582. return;
  8583. }
  8584. this.gridWaterLastActiveTs = now;
  8585. if (this.gridWaterScrollIdleTimer) {
  8586. clearTimeout(this.gridWaterScrollIdleTimer);
  8587. }
  8588. this.gridWaterScrollIdleTimer = setTimeout(() => {
  8589. this.gridWaterScrollIdleTimer = 0;
  8590. if (this.isScrolling) {
  8591. this.isScrolling = false;
  8592. }
  8593. this.flushPendingCoverThumbRefresh();
  8594. }, 120);
  8595. }
  8596. private updateTitleBarByScrollOffset(currentOffsetY: number): void {
  8597. if (!this.autoHideTitle) {
  8598. return;
  8599. }
  8600. const now = Date.now();
  8601. if (now - this.titleBarLastCheckTs < 36) {
  8602. return;
  8603. }
  8604. this.titleBarLastCheckTs = now;
  8605. const delta = currentOffsetY - this.prevOffsetY;
  8606. if (Math.abs(delta) < this.titleBarToggleMinDelta) {
  8607. return;
  8608. }
  8609. if (delta > 0) {
  8610. if (this.isShowTitleBar) {
  8611. this.isShowTitleBar = false;
  8612. }
  8613. } else {
  8614. if (!this.isShowTitleBar) {
  8615. this.isShowTitleBar = true;
  8616. }
  8617. }
  8618. this.prevOffsetY = currentOffsetY;
  8619. }
  8620. private shouldPrefetchSecondPage(): boolean {
  8621. if (this.isMediaLibraryListMode()) {
  8622. return this.pageSize <= 120;
  8623. }
  8624. if (this.pageSize > 60) {
  8625. return false;
  8626. }
  8627. return this.isGridMusic || this.twoFingerType == 4;
  8628. }
  8629. private isMediaLibraryListMode(): boolean {
  8630. return this.modeType === 1 && !this.isGridMusic && this.twoFingerType != 4;
  8631. }
  8632. private isMediaLibraryWarmupWindow(): boolean {
  8633. if (this.modeType !== 1 || this.isCanBack) {
  8634. return false;
  8635. }
  8636. if (this.mediaLibraryEnterTs <= 0) {
  8637. return false;
  8638. }
  8639. return Date.now() - this.mediaLibraryEnterTs < 1800;
  8640. }
  8641. private getDynamicPreloadStartRatio(): number {
  8642. if (this.twoFingerType == 4) {
  8643. return 0.10;
  8644. }
  8645. if (this.isGridMusic) {
  8646. return 0.14;
  8647. }
  8648. if (this.isMediaLibraryListMode()) {
  8649. return 0.12;
  8650. }
  8651. return this.preloadStartRatio;
  8652. }
  8653. private getDynamicAppendStartRatio(): number {
  8654. if (this.twoFingerType == 4) {
  8655. return 0.18;
  8656. }
  8657. if (this.isGridMusic) {
  8658. return 0.22;
  8659. }
  8660. if (this.isMediaLibraryListMode()) {
  8661. return 0.22;
  8662. }
  8663. return this.appendStartRatio;
  8664. }
  8665. private getDynamicEarlyAppendReserveCount(): number {
  8666. if (this.twoFingerType == 4) {
  8667. return Math.max(this.earlyAppendReserveCount, Math.floor(this.pageSize * 0.9));
  8668. }
  8669. if (this.isGridMusic) {
  8670. return Math.max(this.earlyAppendReserveCount, Math.floor(this.pageSize * 0.82));
  8671. }
  8672. if (this.isMediaLibraryListMode()) {
  8673. return Math.max(this.earlyAppendReserveCount, Math.floor(this.pageSize * 0.75));
  8674. }
  8675. return this.earlyAppendReserveCount;
  8676. }
  8677. private prefetchFollowingPages(nextPage: number): void {
  8678. void this.prefetchNextPage(nextPage);
  8679. if (this.shouldPrefetchSecondPage()) {
  8680. void this.prefetchNextPage(nextPage + 1);
  8681. }
  8682. }
  8683. private scrollToTopForCurrentLayout(): void {
  8684. if (this.twoFingerType == 4) {
  8685. this.waterScroller.scrollEdge(Edge.Top);
  8686. this.scroller.scrollEdge(Edge.Top);
  8687. return;
  8688. }
  8689. if (this.isGridMusic) {
  8690. this.scroller.scrollEdge(Edge.Top);
  8691. return;
  8692. }
  8693. this.listScroller.scrollEdge(Edge.Top);
  8694. }
  8695. private getListImageSource(item: VideoItem, index: number, coverVersion: number = 0): ResourceStr {
  8696. const fallback = item.type == CommonConstants.TYPE_IS_DIR ? $r('app.media.dir_alt') : $r('app.media.alt');
  8697. if (coverVersion < -1) {
  8698. return fallback;
  8699. }
  8700. if (StrUtil.isEmpty(item.pixelMapPath)) {
  8701. return fallback;
  8702. }
  8703. const sourceUri = item.pixelMapPath as string;
  8704. this.initCoverThumbCacheIfNeeded();
  8705. const targetSize = this.getListThumbTargetSize();
  8706. const cachedThumb = this.coverThumbCache.getThumbUri(sourceUri, targetSize);
  8707. if (cachedThumb) {
  8708. return cachedThumb;
  8709. }
  8710. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  8711. const preloadBuffer = Math.max(8, Math.floor(this.pageSize * 0.2));
  8712. const hasRange = this.listVisibleStart >= 0 && this.listVisibleEnd >= 0;
  8713. const isNearVisible = !hasRange ||
  8714. (index >= this.listVisibleStart - preloadBuffer && index <= this.listVisibleEnd + preloadBuffer);
  8715. if (isNearVisible) {
  8716. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  8717. }
  8718. }
  8719. return sourceUri;
  8720. }
  8721. private getListThumbTargetSize(): number {
  8722. if (this.twoFingerType == 1) {
  8723. return 96;
  8724. }
  8725. if (this.twoFingerType == 2) {
  8726. return 112;
  8727. }
  8728. return 128;
  8729. }
  8730. private prefetchListThumbsFromItems(items: VideoItem[], limit: number = 24): void {
  8731. if (!this.isMediaLibraryListMode() || !items || items.length === 0) {
  8732. return;
  8733. }
  8734. this.initCoverThumbCacheIfNeeded();
  8735. const targetSize = this.getListThumbTargetSize();
  8736. const maxCount = Math.min(limit, items.length);
  8737. for (let i = 0; i < maxCount; i++) {
  8738. const item = items[i];
  8739. if (StrUtil.isEmpty(item.pixelMapPath)) {
  8740. continue;
  8741. }
  8742. const sourceUri = item.pixelMapPath as string;
  8743. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  8744. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  8745. }
  8746. }
  8747. }
  8748. private warmupListVisibleThumbs(start: number, end: number): void {
  8749. if (!this.isMediaLibraryListMode()) {
  8750. return;
  8751. }
  8752. if (start < 0 || end < 0 || this.videoLocalList.length <= 0) {
  8753. return;
  8754. }
  8755. const now = Date.now();
  8756. const startDelta = this.listThumbWarmupStart >= 0 ? Math.abs(start - this.listThumbWarmupStart) : 999;
  8757. const endDelta = this.listThumbWarmupEnd >= 0 ? Math.abs(end - this.listThumbWarmupEnd) : 999;
  8758. if (startDelta < 2 && endDelta < 2 && now - this.listThumbWarmupCheckAt < 90) {
  8759. return;
  8760. }
  8761. this.listThumbWarmupCheckAt = now;
  8762. this.listThumbWarmupStart = start;
  8763. this.listThumbWarmupEnd = end;
  8764. this.initCoverThumbCacheIfNeeded();
  8765. const targetSize = this.getListThumbTargetSize();
  8766. const preloadAhead = Math.max(14, Math.floor(this.pageSize * 0.4));
  8767. const begin = Math.max(0, start - 4);
  8768. const last = Math.min(this.videoLocalList.length - 1, end + preloadAhead);
  8769. for (let index = begin; index <= last; index++) {
  8770. const item = this.videoLocalList[index];
  8771. if (!item || StrUtil.isEmpty(item.pixelMapPath)) {
  8772. continue;
  8773. }
  8774. const sourceUri = item.pixelMapPath as string;
  8775. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  8776. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  8777. }
  8778. }
  8779. }
  8780. private prefetchGridWaterThumbsFromItems(items: VideoItem[], limit: number = 42): void {
  8781. if (!(this.isGridMusic || this.twoFingerType == 4) || !items || items.length === 0) {
  8782. return;
  8783. }
  8784. this.initCoverThumbCacheIfNeeded();
  8785. const isWater = this.twoFingerType == 4;
  8786. const targetSize = this.getCoverThumbTargetSize(isWater);
  8787. const maxCount = Math.min(limit, items.length);
  8788. for (let i = 0; i < maxCount; i++) {
  8789. const item = items[i];
  8790. if (!item || StrUtil.isEmpty(item.pixelMapPath)) {
  8791. continue;
  8792. }
  8793. const sourceUri = item.pixelMapPath as string;
  8794. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  8795. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  8796. }
  8797. }
  8798. }
  8799. private warmupGridWaterVisibleThumbs(start: number, end: number, isWater: boolean): void {
  8800. if (!(this.isGridMusic || this.twoFingerType == 4)) {
  8801. return;
  8802. }
  8803. if (start < 0 || end < 0 || this.videoLocalList.length <= 0) {
  8804. return;
  8805. }
  8806. const now = Date.now();
  8807. let lastStart = -1;
  8808. let lastEnd = -1;
  8809. let lastCheckAt = 0;
  8810. if (isWater) {
  8811. lastStart = this.waterThumbWarmupStart;
  8812. lastEnd = this.waterThumbWarmupEnd;
  8813. lastCheckAt = this.waterThumbWarmupCheckAt;
  8814. } else {
  8815. lastStart = this.gridThumbWarmupStart;
  8816. lastEnd = this.gridThumbWarmupEnd;
  8817. lastCheckAt = this.gridThumbWarmupCheckAt;
  8818. }
  8819. const startDelta = lastStart >= 0 ? Math.abs(start - lastStart) : 999;
  8820. const endDelta = lastEnd >= 0 ? Math.abs(end - lastEnd) : 999;
  8821. if (startDelta < 2 && endDelta < 2 && now - lastCheckAt < 70) {
  8822. return;
  8823. }
  8824. if (isWater) {
  8825. this.waterThumbWarmupCheckAt = now;
  8826. this.waterThumbWarmupStart = start;
  8827. this.waterThumbWarmupEnd = end;
  8828. } else {
  8829. this.gridThumbWarmupCheckAt = now;
  8830. this.gridThumbWarmupStart = start;
  8831. this.gridThumbWarmupEnd = end;
  8832. }
  8833. this.initCoverThumbCacheIfNeeded();
  8834. const columns = isWater ? Math.max(this.columns, 1) :
  8835. (this.twoFingerType == 1 ? 4 : this.twoFingerType == 2 ? 3 : 2);
  8836. const preloadAhead = Math.max(columns * (isWater ? 8 : 6), isWater ? 24 : 18);
  8837. const begin = Math.max(0, start - Math.max(columns * 2, 4));
  8838. const last = Math.min(this.videoLocalList.length - 1, end + preloadAhead);
  8839. const targetSize = this.getCoverThumbTargetSize(isWater);
  8840. for (let index = begin; index <= last; index++) {
  8841. const item = this.videoLocalList[index];
  8842. if (!item || StrUtil.isEmpty(item.pixelMapPath)) {
  8843. continue;
  8844. }
  8845. const sourceUri = item.pixelMapPath as string;
  8846. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  8847. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  8848. }
  8849. }
  8850. }
  8851. private getGridWaterImageSource(item: VideoItem, index: number, isWater: boolean,
  8852. coverVersion: number = 0): ResourceStr {
  8853. const fallback = item.type == CommonConstants.TYPE_IS_DIR ? $r('app.media.dir_alt') : $r('app.media.alt');
  8854. if (coverVersion < -1) {
  8855. return fallback;
  8856. }
  8857. if (StrUtil.isEmpty(item.pixelMapPath)) {
  8858. return fallback;
  8859. }
  8860. const sourceUri = item.pixelMapPath as string;
  8861. this.initCoverThumbCacheIfNeeded();
  8862. const isRemoteCover = this.coverThumbCache.isRemoteImageSource(sourceUri);
  8863. const targetSize = this.getCoverThumbTargetSize(isWater);
  8864. const cachedThumb = this.coverThumbCache.getThumbUri(sourceUri, targetSize);
  8865. if (cachedThumb) {
  8866. return cachedThumb;
  8867. }
  8868. const visibleStart = isWater ? this.waterVisibleStart : this.gridVisibleStart;
  8869. const visibleEnd = isWater ? this.waterVisibleEnd : this.gridVisibleEnd;
  8870. const columns = isWater ? Math.max(this.columns, 1) :
  8871. (this.twoFingerType == 1 ? 4 : this.twoFingerType == 2 ? 3 : 2);
  8872. const preloadBuffer = Math.max(columns * 2, 8);
  8873. const isVisibleRangeReady = visibleStart >= 0 && visibleEnd >= 0;
  8874. const isNearVisible = !isVisibleRangeReady || (index >= visibleStart - preloadBuffer && index <= visibleEnd + preloadBuffer);
  8875. if (!isRemoteCover && isNearVisible) {
  8876. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  8877. }
  8878. if (!this.isScrolling) {
  8879. return sourceUri;
  8880. }
  8881. if (isNearVisible) {
  8882. return sourceUri;
  8883. }
  8884. return fallback;
  8885. }
  8886. private flushPendingCoverThumbRefresh(): void {
  8887. if (!this.pendingCoverThumbRefresh) {
  8888. return;
  8889. }
  8890. this.pendingCoverThumbRefresh = false;
  8891. this.coverThumbVersion++;
  8892. }
  8893. private initCoverThumbCacheIfNeeded(): void {
  8894. if (this.coverThumbCacheReady) {
  8895. return;
  8896. }
  8897. this.coverThumbCache.setContext(this.context);
  8898. this.coverThumbCache.setOnThumbReady(() => {
  8899. if (this.isScrolling) {
  8900. this.pendingCoverThumbRefresh = true;
  8901. return;
  8902. }
  8903. this.coverThumbVersion++;
  8904. });
  8905. this.coverThumbCacheReady = true;
  8906. }
  8907. private getCoverThumbTargetSize(isWater: boolean): number {
  8908. if (isWater) {
  8909. if (this.columns >= 4) {
  8910. return 160;
  8911. }
  8912. if (this.columns == 3) {
  8913. return 200;
  8914. }
  8915. return 260;
  8916. }
  8917. const baseSize = Math.max(this.getGridWight(), this.getGridHeight());
  8918. if (this.twoFingerType == 1) {
  8919. return baseSize;
  8920. }
  8921. if (this.twoFingerType == 2) {
  8922. return Math.floor(baseSize * 1.1);
  8923. }
  8924. return Math.floor(baseSize * 1.15);
  8925. }
  8926. private tryTriggerLoadForWaterByOffset(currentOffsetY: number): void {
  8927. if (this.videoLocalList.length <= 0) {
  8928. return;
  8929. }
  8930. const columns = Math.max(this.columns, 1);
  8931. const viewportHeight = this.windowHeight > 0 ? this.windowHeight : 900;
  8932. const estimatedCardHeight = this.columns >= 3 ? 196 : 228;
  8933. const startRow = Math.max(0, Math.floor(Math.max(currentOffsetY, 0) / estimatedCardHeight) - 1);
  8934. const estimatedRows = Math.ceil((Math.max(currentOffsetY, 0) + viewportHeight) / estimatedCardHeight);
  8935. const startIndex = Math.min(this.videoLocalList.length - 1, startRow * columns);
  8936. const estimatedEnd = Math.min(this.videoLocalList.length - 1, estimatedRows * columns + columns);
  8937. this.waterVisibleStart = startIndex;
  8938. this.waterVisibleEnd = estimatedEnd;
  8939. this.lastVisibleEndIndex = estimatedEnd;
  8940. this.warmupGridWaterVisibleThumbs(startIndex, estimatedEnd, true);
  8941. const now = Date.now();
  8942. const pagingDelta = this.waterScrollLastPagingEnd >= 0 ? Math.abs(estimatedEnd - this.waterScrollLastPagingEnd) : 999;
  8943. if (pagingDelta >= 3 || now - this.waterScrollPagingCheckAt >= 80) {
  8944. this.waterScrollPagingCheckAt = now;
  8945. this.waterScrollLastPagingEnd = estimatedEnd;
  8946. this.tryTriggerLoadNextPageByScroll(estimatedEnd);
  8947. }
  8948. }
  8949. private tryTriggerLoadNextPageByScroll(endIndex: number): void {
  8950. if (this.modeType === 4) {
  8951. return;
  8952. }
  8953. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  8954. return;
  8955. }
  8956. if (this.isHistory || this.isFavMusic) {
  8957. return;
  8958. }
  8959. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  8960. return;
  8961. }
  8962. if (endIndex < 0 || endIndex >= this.videoLocalList.length) {
  8963. return;
  8964. }
  8965. const nextPage = this.currentPage + 1;
  8966. const next2Page = this.currentPage + 2;
  8967. const totalLoaded = this.videoLocalList.length;
  8968. const seenRatio = (endIndex + 1) / Math.max(totalLoaded, 1);
  8969. const remainCount = this.videoLocalList.length - endIndex - 1;
  8970. const preloadStartRatio = this.getDynamicPreloadStartRatio();
  8971. const appendStartRatio = this.getDynamicAppendStartRatio();
  8972. const earlyAppendReserveCount = this.getDynamicEarlyAppendReserveCount();
  8973. const emergencyDistance = Math.max(12, Math.floor(this.pageSize * 0.5));
  8974. if (seenRatio >= preloadStartRatio) {
  8975. if (!this.pageCache.has(nextPage)) {
  8976. void this.prefetchNextPage(nextPage);
  8977. }
  8978. if (this.shouldPrefetchSecondPage() && !this.pageCache.has(next2Page)) {
  8979. void this.prefetchNextPage(next2Page);
  8980. }
  8981. }
  8982. const shouldAppendEarly = this.pageCache.has(nextPage) &&
  8983. (seenRatio >= appendStartRatio || remainCount <= earlyAppendReserveCount);
  8984. const shouldGapAppend = this.pageCache.has(nextPage) &&
  8985. seenRatio >= (appendStartRatio - 0.08) &&
  8986. remainCount <= Math.max(earlyAppendReserveCount, Math.floor(this.pageSize * 0.9));
  8987. const shouldEmergencyLoad = remainCount <= emergencyDistance;
  8988. if (!shouldAppendEarly && !shouldGapAppend && !shouldEmergencyLoad) {
  8989. return;
  8990. }
  8991. if (this.lastScrollTriggerPage === this.currentPage) {
  8992. return;
  8993. }
  8994. this.lastScrollTriggerPage = this.currentPage;
  8995. Logger.info('heanup LocalMusic',
  8996. `tryTriggerLoadNextPageByScroll: end=${endIndex}, remain=${remainCount}, ratio=${seenRatio}, page=${this.currentPage}`);
  8997. this.scheduleLoadNextPage(8);
  8998. }
  8999. private scheduleLoadNextPage(delayMs: number = 0): void {
  9000. if (this.pagingScheduleTimer) {
  9001. return;
  9002. }
  9003. this.pagingScheduleTimer = setTimeout(() => {
  9004. this.pagingScheduleTimer = 0;
  9005. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  9006. return;
  9007. }
  9008. void this.loadNextPage();
  9009. }, delayMs);
  9010. }
  9011. /**
  9012. * 加载下一页
  9013. */
  9014. private async loadNextPage(): Promise<void> {
  9015. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  9016. return;
  9017. }
  9018. this.isPagingTransition = true;
  9019. this.currentPage++;
  9020. Logger.info('heanup LocalMusic', `loadNextPage: 加载第 ${this.currentPage} 页`);
  9021. try {
  9022. await this.loadPage(this.currentPage, true);
  9023. } finally {
  9024. this.isPagingTransition = false;
  9025. }
  9026. }
  9027. //编辑信息
  9028. async doEdit(item: VideoItem) {
  9029. if (!item) {
  9030. return
  9031. }
  9032. if (StrUtil.isEmpty(this.titleStr)) {
  9033. ToastUtil.showToast('标题不能为空')
  9034. return
  9035. }
  9036. //内嵌音乐标签不能开启监听
  9037. // this.deletionWatcher?.stop();
  9038. this.loadingDialogId = DialogHelper.showLoadingDialog()
  9039. if (isRemoteCloudType(item.type)) {
  9040. await this.saveRemoteSongEdit(item);
  9041. return;
  9042. }
  9043. await PermissionUtil.activatePermission(item.filePath)
  9044. let tempOutPath = ''
  9045. // 如果不是 packName 包下的文件,则直接路径用this.currentPath
  9046. if(!item.filePath.toLowerCase().includes(this.packName)){
  9047. tempOutPath = this.currentPath + '/' + item.fileName
  9048. }
  9049. console.info('onecold tempOutPath ='+tempOutPath)
  9050. //用户更改了封面,那就内嵌下封面
  9051. if(StrUtil.isNotEmpty(this.imagePathStr)){
  9052. const resultCover:boolean = await changeMusicCover(this.context,
  9053. item.filePath,this.imagePathStr,true,tempOutPath);
  9054. this.imagePathStr = ''
  9055. if(resultCover){
  9056. ToastUtil.showToast('内嵌封面成功')
  9057. }
  9058. }
  9059. const metadata:FFMpegTags = {
  9060. title: this.titleStr,
  9061. artist: this.artistStr,
  9062. album: this.ablumStr,
  9063. TYER:this.yearStr,
  9064. genre:this.genreStr,
  9065. track:this.trackStr,
  9066. album_artist:this.albumArtistStr,
  9067. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  9068. COMPOSER:this.composerStr,
  9069. lyricist:this.lyricistStr,
  9070. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  9071. comment:this.commentStr,
  9072. disc:this.discStr,
  9073. };
  9074. let newInput = item.filePath
  9075. //内嵌标签歌路径如果不是包含包名,输入newInput要赋值tempOutPath,然后tempOutPath为空
  9076. if(!item.filePath.toLowerCase().includes(this.packName)&&FileUtil.accessSync(tempOutPath)){
  9077. newInput = tempOutPath
  9078. tempOutPath = ''
  9079. }
  9080. const isWav:boolean = newInput.toLowerCase().endsWith('.wav')
  9081. ||newInput.toLowerCase().endsWith('.ape')
  9082. ||newInput.toLowerCase().endsWith('.dsf')
  9083. ||newInput.toLowerCase().endsWith('.dff');
  9084. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  9085. const result:boolean = await repairAudioMetadata(
  9086. newInput,
  9087. this.lyricConStr,
  9088. metadata,
  9089. true,
  9090. tempOutPath
  9091. );
  9092. // ToastUtil.showToast('result ='+ result)
  9093. if (result||isWav) {
  9094. if(!item.filePath.includes(this.packName)){
  9095. //内嵌成功的歌路径如果不是包含包名,则要入库
  9096. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newInput,
  9097. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  9098. this.table.insert(newItem, (id: number) => {
  9099. //加入数据库
  9100. if(this.modeType==0){
  9101. this.deleteCache(this.currentPath)
  9102. this.getSortedFiles(this.currentPath)
  9103. }
  9104. });
  9105. }
  9106. const task = new taskpool.Task(
  9107. updateInfoDb,
  9108. this.context,
  9109. item.filePath,
  9110. this.titleStr,
  9111. this.artistStr,
  9112. this.ablumStr,
  9113. this.lyricConStr,
  9114. this.yearStr,this.genreStr,
  9115. this.trackStr,this.albumArtistStr,
  9116. this.composerStr, this.lyricistStr,
  9117. this.commentStr,this.discStr
  9118. );
  9119. taskpool.execute(task, taskpool.Priority.HIGH).then((result) => {
  9120. if (result) {
  9121. console.log(" onecold 编辑信息成功,数据库已同步");
  9122. if(isWav){
  9123. ToastUtil.showToast('dsf、wav、dff或者ape格式有可能内嵌失败,但是编辑信息成功')
  9124. }else{
  9125. ToastUtil.showToast('内嵌音乐标签成功')
  9126. }
  9127. this.isShowMoreView = false
  9128. this.name = this.titleStr
  9129. this.syncEditedFields(item)
  9130. if (item.filePath == this.currentSong?.filePath) {
  9131. this.currentSong.name = this.titleStr
  9132. this.artist = this.artistStr
  9133. this.currentSong.artist = this.artistStr
  9134. this.currentSong.album = this.ablumStr
  9135. this.currentSong.year = this.yearStr
  9136. this.currentSong.genre = this.genreStr
  9137. this.currentSong.track = this.trackStr
  9138. this.currentSong.lyricContent = this.lyricConStr
  9139. this.currentSong.ALBUMARTIST = this.albumArtistStr
  9140. this.currentSong.COMPOSER = this.composerStr
  9141. this.currentSong.LYRICIST = this.lyricistStr
  9142. this.currentSong.COMMENT = this.commentStr
  9143. }
  9144. this.syncListsAfterEdit(item.filePath)
  9145. this.doUpateEditedFields(item)
  9146. //this.doUpdateData()
  9147. } else {
  9148. // ToastUtil.showToast('保存失败' + error?.toString())
  9149. console.error(" onecold 编辑信息数据库失败 ");
  9150. }
  9151. // 关闭进度条
  9152. DialogHelper.closeDialog(this.loadingDialogId)
  9153. }).catch((error: Error) => {
  9154. // 关闭进度条
  9155. DialogHelper.closeDialog(this.loadingDialogId)
  9156. console.error('onecold Subtitle sync failed:', error);
  9157. });
  9158. console.log(' onecold 元数据标签更新成功,');
  9159. } else {
  9160. // 关闭进度条
  9161. DialogHelper.closeDialog(this.loadingDialogId)
  9162. ToastUtil.showToast('内嵌音乐标签失败')
  9163. console.log('onecold 内嵌音乐标签失败');
  9164. }
  9165. this.longItemFilePath = ''
  9166. this.tempLyricContent = ''
  9167. this.isShowEdit = false
  9168. }
  9169. private normalizeEditedCoverPath(path: string): string {
  9170. if (StrUtil.isEmpty(path)) {
  9171. return '';
  9172. }
  9173. const lowerPath = path.toLowerCase();
  9174. if (lowerPath.startsWith('http://') || lowerPath.startsWith('https://')
  9175. || lowerPath.startsWith('file://') || lowerPath.startsWith('data:')) {
  9176. return path;
  9177. }
  9178. return fileUri.getUriFromPath(path);
  9179. }
  9180. private emitRemoteMetadataUpdated(item: VideoItem): void {
  9181. if (!item || StrUtil.isEmpty(item.filePath)) {
  9182. return;
  9183. }
  9184. const payload: WebDavMetadataUpdatePayload = {
  9185. filePath: item.filePath,
  9186. pixelMapPath: item.pixelMapPath,
  9187. isCustomCover: item.isCustomCover,
  9188. md5Str: item.md5Str,
  9189. name: item.name,
  9190. artist: item.artist
  9191. };
  9192. const eventUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
  9193. emitter.emit(eventUpdate, { data: [payload] });
  9194. }
  9195. private syncRemoteManagerSong(item: VideoItem): void {
  9196. if (!item || StrUtil.isEmpty(item.filePath)) {
  9197. return;
  9198. }
  9199. const remoteManager = RemoteDriveManager.getInstance();
  9200. const target = Utility.getItemByFilePath(remoteManager.webDavSongs, item.filePath);
  9201. if (!target) {
  9202. return;
  9203. }
  9204. this.mergeVideoItemFromSource(target, item);
  9205. }
  9206. private async saveRemoteSongEdit(item: VideoItem): Promise<void> {
  9207. try {
  9208. this.syncEditedFields(item);
  9209. if (StrUtil.isNotEmpty(this.imagePathStr)) {
  9210. item.pixelMapPath = this.normalizeEditedCoverPath(this.imagePathStr);
  9211. item.isCustomCover = 1;
  9212. }
  9213. this.name = this.titleStr;
  9214. if (this.currentSong && item.filePath === this.currentSong.filePath) {
  9215. this.syncEditedFields(this.currentSong);
  9216. if (StrUtil.isNotEmpty(item.pixelMapPath)) {
  9217. mergeCoverWithPriority(this.currentSong, item.pixelMapPath, item.isCustomCover ?? 0);
  9218. this.cover = this.currentSong.pixelMapPath || item.pixelMapPath;
  9219. }
  9220. this.artist = this.currentSong.artist ?? '';
  9221. this.currentSong = cloneVideoItem(this.currentSong);
  9222. AppStorage.setOrCreate('currentSong', this.currentSong);
  9223. }
  9224. this.syncListsAfterEdit(item.filePath);
  9225. this.syncRemoteManagerSong(item);
  9226. await this.persistRemoteMetadataToDb(item);
  9227. this.emitRemoteMetadataUpdated(item);
  9228. ToastUtil.showToast(StrUtil.isNotEmpty(item.pixelMapPath) ? '网盘歌曲信息已保存' : '网盘歌曲标签已保存');
  9229. } catch (error) {
  9230. Logger.error(TAG, `saveRemoteSongEdit 失败: ${(error as Error).message}`);
  9231. ToastUtil.showToast('网盘歌曲编辑失败');
  9232. } finally {
  9233. DialogHelper.closeDialog(this.loadingDialogId);
  9234. this.longItemFilePath = '';
  9235. this.tempLyricContent = '';
  9236. this.isShowEdit = false;
  9237. this.imagePathStr = '';
  9238. this.isShowMoreView = false;
  9239. }
  9240. }
  9241. // 内嵌标签更新当前内嵌的Item
  9242. async doUpateEditedFields(item: VideoItem) {
  9243. // 找到当前项在 videoLocalList 中的索引
  9244. const index = this.videoLocalList.findIndex(video => video.filePath === item.filePath);
  9245. if (index !== -1) {
  9246. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  9247. const updatedItem = await this.table.queryVideoByFilePath(item.filePath)
  9248. // 只有当查询结果不为 null 时才更新列表
  9249. if (updatedItem !== null) {
  9250. // 更新 videoLocalList 中的项(通过创建新数组触发响应式更新)
  9251. this.videoLocalList = [
  9252. ...this.videoLocalList.slice(0, index),
  9253. updatedItem,
  9254. ...this.videoLocalList.slice(index + 1)
  9255. ];
  9256. // 同步更新 LazyDataSource
  9257. this.dataSource.pushArrayData(this.videoLocalList)
  9258. } else {
  9259. ToastUtil.showToast('未找到更新的数据');
  9260. }
  9261. }
  9262. DialogHelper.closeDialog(this.loadingDialogId)
  9263. }
  9264. @Builder
  9265. editSheet(item: VideoItem) {
  9266. Scroll() {
  9267. Column() {
  9268. this.editDetail(item)
  9269. }
  9270. }
  9271. .width('100%')
  9272. .height('100%')
  9273. }
  9274. @Builder
  9275. editDetail(item: VideoItem) {
  9276. Column() {
  9277. if (item) {
  9278. Row() {
  9279. Stack() {
  9280. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  9281. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  9282. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
  9283. item.pixelMapPath)
  9284. .fillColor(this.themeColor)
  9285. .height(88)
  9286. .width(88)
  9287. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  9288. .borderRadius(12)
  9289. .clip(true)
  9290. .opacity(this.opacityItem)// 绑定透明度
  9291. .margin({ left: 25 })
  9292. }
  9293. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  9294. .onClick(async () => {
  9295. const imagePath:string | undefined = await this.goSelectImage(item);
  9296. if (imagePath) {
  9297. //用户更改过图片
  9298. this.imagePathStr = imagePath
  9299. }
  9300. })
  9301. .width('28%')
  9302. Row() {
  9303. Column() {
  9304. Text(item.name)
  9305. .fontSize(17)
  9306. .maxLines(1)
  9307. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9308. .animation({
  9309. duration: 555,
  9310. curve: 'Linear',
  9311. })
  9312. .fontColor(this.themeColor)
  9313. .margin({ left: 8 })
  9314. Row() {
  9315. Text(item.artist)
  9316. .fontSize(14)
  9317. .maxLines(1)
  9318. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9319. .padding({ top: 8 })
  9320. .fontColor(this.themeColor)
  9321. .margin({ left: 8 })
  9322. }
  9323. }
  9324. .height('100%')
  9325. .width(100)
  9326. .layoutWeight(1)
  9327. .justifyContent(FlexAlign.Center)
  9328. .alignItems(HorizontalAlign.Start)
  9329. Column() {
  9330. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9331. Row(){
  9332. SymbolGlyph($r('sys.symbol.picture'))
  9333. .fontSize(18)
  9334. .fontColor([Color.White])
  9335. Text('获取封面')
  9336. .margin({ left: 4 })
  9337. .fontSize(11)
  9338. .fontColor(Color.White)
  9339. .fontWeight(480)
  9340. .textAlign(TextAlign.Center)
  9341. }
  9342. .justifyContent(FlexAlign.Center)
  9343. }
  9344. .height(38)
  9345. .width(100)
  9346. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9347. .backgroundColor(this.themeColor)
  9348. .stateEffect(true)
  9349. .margin({ right: 35 })
  9350. .onClick(async () => {
  9351. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  9352. this.showTipsDialog();
  9353. return; // Return empty string when no API is configured
  9354. }
  9355. const imagePath:string | undefined = await this.doSearchCover(item,
  9356. this.titleStr,this.artistStr);
  9357. console.info('onecold imagePath = '+imagePath)
  9358. if (StrUtil.isNotEmpty(imagePath)) {
  9359. //用户更改过图片
  9360. this.imagePathStr = imagePath
  9361. ToastUtil.showToast('获取封面成功')
  9362. }else{
  9363. ToastUtil.showToast('获取封面失败,请重试')
  9364. }
  9365. })
  9366. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9367. Row(){
  9368. SymbolGlyph($r('sys.symbol.input_mode'))
  9369. .fontSize(18)
  9370. .fontColor([Color.White])
  9371. Text('获取歌词')
  9372. .margin({ left: 4 })
  9373. .fontSize(11)
  9374. .fontColor(Color.White)
  9375. .fontWeight(480)
  9376. .textAlign(TextAlign.Center)
  9377. }
  9378. .justifyContent(FlexAlign.Center)
  9379. }
  9380. .height(38)
  9381. .width(100)
  9382. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9383. .backgroundColor(this.themeColor)
  9384. .stateEffect(true)
  9385. .margin({ top: 9, right: 35 })
  9386. .onClick(async () => {
  9387. //判断有没有设置api
  9388. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  9389. if (StrUtil.isEmpty(apiUrl)) {
  9390. this.isLyricSetting = false
  9391. this.showTipsDialog()
  9392. return
  9393. }
  9394. let res: string | undefined = await getApiLyric(apiUrl,
  9395. this.titleStr, this.artistStr, false);
  9396. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  9397. this.lyricConStr = res;
  9398. ToastUtil.showToast('获取歌词成功')
  9399. }else{
  9400. ToastUtil.showToast('获取歌词失败,请重试')
  9401. }
  9402. })
  9403. }
  9404. .justifyContent(FlexAlign.Start)
  9405. }
  9406. .height('100%')
  9407. .justifyContent(FlexAlign.Start)
  9408. .layoutWeight(1)
  9409. }
  9410. .width('100%')
  9411. .height(98)
  9412. Row() {
  9413. Text('标题:')
  9414. .fontSize(14)
  9415. .fontColor($r('app.color.text_color'))
  9416. .margin({ left: 22 })
  9417. TextInput({ text: this.titleStr })
  9418. .height(40)
  9419. .maxLines(1)
  9420. .fontSize(14)
  9421. .layoutWeight(1)
  9422. .fontColor($r('app.color.text_color'))
  9423. .margin({ right: 15, left: 10 })
  9424. .onChange((val: string) => {
  9425. this.titleStr = val
  9426. })
  9427. Button('修复乱码',{ type: ButtonType.Capsule, stateEffect: true})
  9428. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9429. .backgroundColor(this.themeColor)
  9430. .fontSize(10)
  9431. .margin({ right: 20})
  9432. .onClick(async () => {
  9433. let hwTags = await extractHwMediaMetadata(item.filePath)
  9434. let artist = hwTags?.artist|| '';
  9435. let title = hwTags?.title|| '';
  9436. let album = hwTags?.album|| '';
  9437. console.info('onecold 乱码修正 artist='+artist);
  9438. console.info('onecold 乱码修正 title='+title);
  9439. console.info('onecold 乱码修正 album='+album);
  9440. this.titleStr = title;
  9441. this.artistStr = artist;
  9442. this.ablumStr = album;
  9443. })
  9444. }
  9445. .width('100%')
  9446. .margin({ top: 10, bottom: 10 })
  9447. .justifyContent(FlexAlign.Start)
  9448. Row() {
  9449. Text('艺术家:')
  9450. .fontSize(14)
  9451. .fontColor($r('app.color.text_color'))
  9452. .margin({ left: 22 })
  9453. TextInput({ text: this.artistStr })
  9454. .height(40)
  9455. .maxLines(1)
  9456. .fontSize(14)
  9457. .layoutWeight(1)
  9458. .fontColor($r('app.color.text_color'))
  9459. .margin({ right: 20, left: 10 })
  9460. .onChange((val: string) => {
  9461. this.artistStr = val
  9462. })
  9463. }
  9464. .width('100%')
  9465. .margin({ top: 10, bottom: 10 })
  9466. .justifyContent(FlexAlign.Start)
  9467. Row() {
  9468. Text('专辑名:')
  9469. .fontSize(14)
  9470. .fontColor($r('app.color.text_color'))
  9471. .margin({ left: 22 })
  9472. TextInput({ text: this.ablumStr})
  9473. .height(40)
  9474. .maxLines(1)
  9475. .fontSize(14)
  9476. .layoutWeight(1)
  9477. .fontColor($r('app.color.text_color'))
  9478. .margin({ right: 20, left: 10 })
  9479. .onChange((val: string) => {
  9480. this.ablumStr = val
  9481. })
  9482. }
  9483. .width('100%')
  9484. .margin({ top: 10, bottom: 10 })
  9485. .justifyContent(FlexAlign.Start)
  9486. Row() {
  9487. Column(){
  9488. Column(){
  9489. Text('歌词:')
  9490. .fontSize(14)
  9491. .fontColor($r('app.color.text_color'))
  9492. .margin({ top:9,left: 22 })
  9493. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9494. SymbolGlyph($r('sys.symbol.trash_fill'))
  9495. .fontSize(25)
  9496. .alignSelf(ItemAlign.Center)
  9497. .margin({ left: 22,top:25})
  9498. }
  9499. .backgroundColor(Color.Transparent)
  9500. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  9501. Visibility.None:Visibility.Visible)
  9502. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9503. .onClick(()=>{
  9504. this.lyricConStr = ''
  9505. this.lyricContent = ''
  9506. this.tempLyricContent = ''
  9507. })
  9508. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9509. SymbolGlyph($r('sys.symbol.plus'))
  9510. .fontSize(25)
  9511. .alignSelf(ItemAlign.Center)
  9512. .margin({ left: 22,top:25})
  9513. }
  9514. .backgroundColor(Color.Transparent)
  9515. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9516. .onClick( ()=>{
  9517. this.callFilePickerSelectFileForLyric()
  9518. })
  9519. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9520. SymbolGlyph($r('sys.symbol.traditional_square'))
  9521. .fontSize(25)
  9522. .alignSelf(ItemAlign.Center)
  9523. .margin({ left: 22,top:25})
  9524. }
  9525. .backgroundColor(Color.Transparent)
  9526. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  9527. Visibility.None:Visibility.Visible)
  9528. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9529. .onClick( ()=>{
  9530. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  9531. this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
  9532. })
  9533. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9534. Image($r('app.media.jianti'))
  9535. .height(25)
  9536. .fillColor($r('app.color.text_color'))
  9537. .alignSelf(ItemAlign.Center)
  9538. .margin({ left: 22,top:25})
  9539. }
  9540. .backgroundColor(Color.Transparent)
  9541. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  9542. Visibility.None:Visibility.Visible)
  9543. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9544. .onClick( ()=>{
  9545. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  9546. this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
  9547. })
  9548. }
  9549. .layoutWeight(1)
  9550. }
  9551. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  9552. this.tempLyricContent })
  9553. .type(TextAreaType.NORMAL)
  9554. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
  9555. .fontSize(14)
  9556. .layoutWeight(1)
  9557. .fontColor($r('app.color.text_color'))
  9558. .margin({ right: 20, left: 10 })
  9559. .onChange((val: string) => {
  9560. this.lyricConStr = val
  9561. })
  9562. }
  9563. .width('100%')
  9564. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
  9565. .margin({ top: 10, bottom: 10 })
  9566. .justifyContent(FlexAlign.Start)
  9567. Row() {
  9568. Text('年份:')
  9569. .fontSize(14)
  9570. .fontColor($r('app.color.text_color'))
  9571. .margin({ left: 22 })
  9572. TextInput({ text: item.year })
  9573. .height(40)
  9574. .maxLines(1)
  9575. .fontSize(14)
  9576. .type(InputType.Number)
  9577. .layoutWeight(1)
  9578. .fontColor($r('app.color.text_color'))
  9579. .margin({ right: 20, left: 10 })
  9580. .onChange((val: string) => {
  9581. this.yearStr = val
  9582. })
  9583. }
  9584. .width('100%')
  9585. .margin({ top: 10, bottom: 10 })
  9586. .justifyContent(FlexAlign.Start)
  9587. Row() {
  9588. Text('音轨号:')
  9589. .fontSize(14)
  9590. .fontColor($r('app.color.text_color'))
  9591. .margin({ left: 22 })
  9592. TextInput({ text:item.track=='未知'?'': item.track })
  9593. .height(40)
  9594. .maxLines(1)
  9595. .fontSize(14)
  9596. .type(InputType.Number)
  9597. .layoutWeight(1)
  9598. .fontColor($r('app.color.text_color'))
  9599. .margin({ right: 20, left: 10 })
  9600. .onChange((val: string) => {
  9601. this.trackStr = val
  9602. })
  9603. }
  9604. .width('100%')
  9605. .margin({ top: 10, bottom: 10 })
  9606. .justifyContent(FlexAlign.Start)
  9607. Row() {
  9608. Text('碟号:')
  9609. .fontSize(14)
  9610. .fontColor($r('app.color.text_color'))
  9611. .margin({ left: 22 })
  9612. TextInput({ text:item.disc })
  9613. .height(40)
  9614. .maxLines(1)
  9615. .fontSize(14)
  9616. .type(InputType.Number)
  9617. .layoutWeight(1)
  9618. .fontColor($r('app.color.text_color'))
  9619. .margin({ right: 20, left: 10 })
  9620. .onChange((val: string) => {
  9621. this.discStr = val
  9622. })
  9623. }
  9624. .width('100%')
  9625. .margin({ top: 10, bottom: 10 })
  9626. .justifyContent(FlexAlign.Start)
  9627. Row() {
  9628. Text('风格:')
  9629. .fontSize(14)
  9630. .fontColor($r('app.color.text_color'))
  9631. .margin({ left: 22 })
  9632. TextInput({ text: item.genre })
  9633. .height(40)
  9634. .maxLines(1)
  9635. .fontSize(14)
  9636. .layoutWeight(1)
  9637. .fontColor($r('app.color.text_color'))
  9638. .margin({ right: 20, left: 10 })
  9639. .onChange((val: string) => {
  9640. this.genreStr = val
  9641. })
  9642. }
  9643. .width('100%')
  9644. .margin({ top: 10, bottom: 10 })
  9645. .justifyContent(FlexAlign.Start)
  9646. Row() {
  9647. Text('专辑艺术家:')
  9648. .fontSize(14)
  9649. .fontColor($r('app.color.text_color'))
  9650. .margin({ left: 22 })
  9651. TextInput({ text: item.ALBUMARTIST })
  9652. .height(40)
  9653. .maxLines(1)
  9654. .fontSize(14)
  9655. .layoutWeight(1)
  9656. .fontColor($r('app.color.text_color'))
  9657. .margin({ right: 20, left: 10 })
  9658. .onChange((val: string) => {
  9659. this.albumArtistStr = val
  9660. })
  9661. }
  9662. .width('100%')
  9663. .margin({ top: 10, bottom: 10 })
  9664. .justifyContent(FlexAlign.Start)
  9665. Row() {
  9666. Text('作曲:')
  9667. .fontSize(14)
  9668. .fontColor($r('app.color.text_color'))
  9669. .margin({ left: 22 })
  9670. TextInput({ text: item.COMPOSER })
  9671. .height(40)
  9672. .maxLines(1)
  9673. .fontSize(14)
  9674. .layoutWeight(1)
  9675. .fontColor($r('app.color.text_color'))
  9676. .margin({ right: 20, left: 10 })
  9677. .onChange((val: string) => {
  9678. this.composerStr = val
  9679. })
  9680. }
  9681. .width('100%')
  9682. .margin({ top: 10, bottom: 10 })
  9683. .justifyContent(FlexAlign.Start)
  9684. Row() {
  9685. Text('作词:')
  9686. .fontSize(14)
  9687. .fontColor($r('app.color.text_color'))
  9688. .margin({ left: 22 })
  9689. TextInput({ text: item.LYRICIST })
  9690. .height(40)
  9691. .maxLines(1)
  9692. .fontSize(14)
  9693. .layoutWeight(1)
  9694. .fontColor($r('app.color.text_color'))
  9695. .margin({ right: 20, left: 10 })
  9696. .onChange((val: string) => {
  9697. this.lyricistStr = val
  9698. })
  9699. }
  9700. .width('100%')
  9701. .margin({ top: 10, bottom: 10 })
  9702. .justifyContent(FlexAlign.Start)
  9703. Row() {
  9704. Text('注释:')
  9705. .fontSize(14)
  9706. .fontColor($r('app.color.text_color'))
  9707. .margin({ left: 22 })
  9708. TextInput({ text: item.COMMENT })
  9709. .height(40)
  9710. .maxLines(1)
  9711. .fontSize(14)
  9712. .layoutWeight(1)
  9713. .fontColor($r('app.color.text_color'))
  9714. .margin({ right: 20, left: 10 })
  9715. .onChange((val: string) => {
  9716. this.commentStr = val
  9717. })
  9718. }
  9719. .width('100%')
  9720. .margin({ top: 10, bottom: 10 })
  9721. .justifyContent(FlexAlign.Start)
  9722. Row() {
  9723. Button('保存')
  9724. .fontColor(Color.White)
  9725. .layoutWeight(1)
  9726. .height(50)
  9727. .width(100)
  9728. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9729. .backgroundColor(this.themeColor)
  9730. .stateEffect(true)
  9731. .margin({ right: 20, bottom: 20 })
  9732. .onClick(async () => {
  9733. this.doEdit(item)
  9734. })
  9735. Button('取消')
  9736. .fontColor(Color.White)
  9737. .layoutWeight(1)
  9738. .height(50)
  9739. .width(100)
  9740. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9741. .backgroundColor(this.themeColor)
  9742. .stateEffect(true)
  9743. .margin({ left: 20, bottom: 20 })
  9744. .onClick(async () => {
  9745. if(this.isGridMusic){
  9746. this.longItemFilePath =''
  9747. }else{
  9748. this.isShowEdit = false
  9749. }
  9750. this.setEditStrEmpty()
  9751. if(this.isShowPlay){
  9752. this.isShowEdit = false
  9753. }
  9754. })
  9755. }
  9756. .margin({
  9757. left: 38,
  9758. right: 38,
  9759. top: 10,
  9760. bottom: 10
  9761. })
  9762. .width(250)
  9763. .height(60)
  9764. }
  9765. }
  9766. .margin({ bottom: 20 })
  9767. }
  9768. setEditStrEmpty(){
  9769. this.imagePathStr = ''
  9770. this.lyricConStr = ''
  9771. this.artistStr = ''
  9772. this.titleStr = ''
  9773. this.ablumStr = ''
  9774. this.genreStr = ''
  9775. this.yearStr = ''
  9776. this.trackStr = ''
  9777. this.albumArtistStr = ''
  9778. this.composerStr = ''
  9779. this.lyricistStr = ''
  9780. this.commentStr = ''
  9781. this.discStr = ''
  9782. }
  9783. initEditFields(item?: VideoItem) {
  9784. if (!item) {
  9785. this.setEditStrEmpty()
  9786. return
  9787. }
  9788. this.imagePathStr = ''
  9789. this.titleStr = item.name ?? ''
  9790. this.artistStr = item.artist ?? ''
  9791. this.ablumStr = item.album ?? ''
  9792. this.genreStr = item.genre ?? ''
  9793. this.yearStr = item.year ?? ''
  9794. this.trackStr = item.track ?? ''
  9795. this.albumArtistStr = item.ALBUMARTIST ?? ''
  9796. this.composerStr = item.COMPOSER ?? ''
  9797. this.lyricistStr = item.LYRICIST ?? ''
  9798. this.commentStr = item.COMMENT ?? ''
  9799. this.discStr = item.disc ?? ''
  9800. this.lyricConStr = item.lyricContent ?? ''
  9801. }
  9802. private syncEditedFields(target?: VideoItem) {
  9803. if (!target) {
  9804. return
  9805. }
  9806. target.name = this.titleStr
  9807. target.artist = this.artistStr
  9808. target.album = this.ablumStr
  9809. target.lyricContent = this.lyricConStr
  9810. target.year = this.yearStr
  9811. target.genre = this.genreStr
  9812. target.track = this.trackStr
  9813. target.ALBUMARTIST = this.albumArtistStr
  9814. target.COMPOSER = this.composerStr
  9815. target.LYRICIST = this.lyricistStr
  9816. target.COMMENT = this.commentStr
  9817. target.disc = this.discStr
  9818. }
  9819. private replaceItemInList(list: Array<VideoItem> | undefined, filePath: string,
  9820. apply?: (next: Array<VideoItem>) => void) {
  9821. if (!list || ArrayUtil.isEmpty(list)) {
  9822. return
  9823. }
  9824. const index = list.findIndex((video: VideoItem) => video.filePath === filePath)
  9825. if (index < 0) {
  9826. return
  9827. }
  9828. const nextList = [...list]
  9829. this.syncEditedFields(nextList[index])
  9830. apply?.(nextList)
  9831. }
  9832. private syncListsAfterEdit(filePath: string) {
  9833. this.replaceItemInList(this.videoLocalList, filePath, (next: Array<VideoItem>) => {
  9834. this.videoLocalList = next
  9835. this.dataSource.pushArrayData(next)
  9836. })
  9837. this.replaceItemInList(this.songList, filePath, (next: Array<VideoItem>) => {
  9838. this.songList = next
  9839. this.sonDataSource.pushArrayData(next)
  9840. })
  9841. this.replaceItemInList(this.favList, filePath, (next: Array<VideoItem>) => {
  9842. this.favList = next
  9843. })
  9844. this.replaceItemInList(this.historyList, filePath, (next: Array<VideoItem>) => {
  9845. this.historyList = next
  9846. })
  9847. this.replaceItemInList(this.currentSongList, filePath, (next: Array<VideoItem>) => {
  9848. this.currentSongList = next
  9849. })
  9850. this.replaceItemInList(this.mediaKuList, filePath, (next: Array<VideoItem>) => {
  9851. this.mediaKuList = next
  9852. })
  9853. this.replaceItemInList(this.filteredList, filePath, (next: Array<VideoItem>) => {
  9854. this.filteredList = next
  9855. })
  9856. this.replaceItemInList(this.artistList, filePath, (next: Array<VideoItem>) => {
  9857. this.artistList = next
  9858. })
  9859. this.replaceItemInList(this.albumList, filePath, (next: Array<VideoItem>) => {
  9860. this.albumList = next
  9861. })
  9862. this.listRefreshKey++
  9863. }
  9864. private refreshLazyListViews(mainListUpdated: boolean, playlistUpdated: boolean): void {
  9865. if (!mainListUpdated && !playlistUpdated) {
  9866. return;
  9867. }
  9868. this.listRefreshKey++;
  9869. if (mainListUpdated) {
  9870. this.dataSource.notifyDataReload();
  9871. }
  9872. if (playlistUpdated) {
  9873. this.sonDataSource.notifyDataReload();
  9874. }
  9875. }
  9876. @Builder
  9877. detailSheet(item:VideoItem) {
  9878. Scroll() {
  9879. Column() {
  9880. this.songDetail(item)
  9881. }
  9882. }
  9883. .width('100%')
  9884. .height('100%')
  9885. }
  9886. @Builder
  9887. songDetail(currentItem:VideoItem) {
  9888. Column() {
  9889. if (currentItem) {
  9890. Row() {
  9891. Stack() {
  9892. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.alt') :
  9893. currentItem.pixelMapPath)
  9894. .fillColor(this.themeColor)
  9895. .height(80)
  9896. .width(80)
  9897. .borderRadius(10)
  9898. .opacity(this.opacityItem)// 绑定透明度
  9899. .margin({ left: 22 })
  9900. }
  9901. Column() {
  9902. Column() {
  9903. Text(currentItem.name)
  9904. .fontSize(16)
  9905. .maxLines(1)
  9906. .animation({
  9907. duration: 555,
  9908. curve: 'Linear',
  9909. })
  9910. .fontColor($r('app.color.text_color'))
  9911. .margin({ left: 15 })
  9912. }
  9913. .height('100%')
  9914. .width('100%')
  9915. .justifyContent(FlexAlign.Center)
  9916. .alignItems(HorizontalAlign.Start)
  9917. }
  9918. .height('100%')
  9919. }
  9920. .width('100%')
  9921. .height(90)
  9922. .justifyContent(FlexAlign.SpaceBetween)
  9923. Row() {
  9924. Text('艺术家:')
  9925. .fontSize(14)
  9926. .fontColor($r('app.color.text_color'))
  9927. .margin({ left: 22 })
  9928. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  9929. .fontSize(14)
  9930. .fontColor($r('app.color.text_color'))
  9931. .margin({ left: 10 })
  9932. .layoutWeight(1)
  9933. }
  9934. .width('100%')
  9935. .margin({ top: 10, bottom: 10 })
  9936. .justifyContent(FlexAlign.Start)
  9937. Row() {
  9938. Text('专辑名:')
  9939. .fontSize(14)
  9940. .fontColor($r('app.color.text_color'))
  9941. .margin({ left: 22 })
  9942. Text(currentItem?.album ?currentItem.album : '未知专辑')
  9943. .fontSize(14)
  9944. .margin({ left: 10 })
  9945. .fontColor($r('app.color.text_color'))
  9946. .layoutWeight(1)
  9947. }
  9948. .width('100%')
  9949. .margin({ top: 10, bottom: 10 })
  9950. .justifyContent(FlexAlign.Start)
  9951. Row() {
  9952. Text('时长:')
  9953. .fontSize(14)
  9954. .fontColor($r('app.color.text_color'))
  9955. .margin({ left: 22 })
  9956. Text(StrUtil.isEmpty(currentItem.duration)?
  9957. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  9958. .fontSize(14)
  9959. .margin({ left: 10 })
  9960. .fontColor($r('app.color.text_color'))
  9961. .layoutWeight(1)
  9962. }
  9963. .width('100%')
  9964. .margin({ top: 10, bottom: 10 })
  9965. .justifyContent(FlexAlign.Start)
  9966. Row() {
  9967. Text('采样率:')
  9968. .fontSize(14)
  9969. .fontColor($r('app.color.text_color'))
  9970. .margin({ left: 22 })
  9971. Text(Utility.convertToKHz(currentItem.sampleRate))
  9972. .fontSize(14)
  9973. .margin({ left: 10 })
  9974. .fontColor($r('app.color.text_color'))
  9975. .layoutWeight(1)
  9976. }
  9977. .width('100%')
  9978. .margin({ top: 10, bottom: 10 })
  9979. .justifyContent(FlexAlign.Start)
  9980. Row() {
  9981. Text('比特率:')
  9982. .fontSize(14)
  9983. .fontColor($r('app.color.text_color'))
  9984. .margin({ left: 22 })
  9985. Text(currentItem.bit_rate)
  9986. .fontSize(14)
  9987. .margin({ left: 10 })
  9988. .fontColor($r('app.color.text_color'))
  9989. .layoutWeight(1)
  9990. }
  9991. .width('100%')
  9992. .margin({ top: 10, bottom: 10 })
  9993. .justifyContent(FlexAlign.Start)
  9994. Row() {
  9995. Text('位深:')
  9996. .fontSize(14)
  9997. .fontColor($r('app.color.text_color'))
  9998. .margin({ left: 22 })
  9999. Text(`${currentItem.bits_per_raw_sample} bits`)
  10000. .fontSize(14)
  10001. .margin({ left: 10 })
  10002. .fontColor($r('app.color.text_color'))
  10003. .layoutWeight(1)
  10004. }
  10005. .width('100%')
  10006. .margin({ top: 10, bottom: 10 })
  10007. .justifyContent(FlexAlign.Start)
  10008. Row() {
  10009. Text('声道:')
  10010. .fontSize(14)
  10011. .fontColor($r('app.color.text_color'))
  10012. .margin({ left: 22 })
  10013. Text(`${currentItem.channels}`)
  10014. .fontSize(14)
  10015. .margin({ left: 10 })
  10016. .fontColor($r('app.color.text_color'))
  10017. .layoutWeight(1)
  10018. }
  10019. .width('100%')
  10020. .margin({ top: 10, bottom: 10 })
  10021. .justifyContent(FlexAlign.Start)
  10022. Row() {
  10023. Text('声道布局:')
  10024. .fontSize(14)
  10025. .fontColor($r('app.color.text_color'))
  10026. .margin({ left: 22 })
  10027. Text(`${currentItem.channel_layout}`)
  10028. .fontSize(14)
  10029. .margin({ left: 10 })
  10030. .fontColor($r('app.color.text_color'))
  10031. .layoutWeight(1)
  10032. }
  10033. .width('100%')
  10034. .margin({ top: 10, bottom: 10 })
  10035. .justifyContent(FlexAlign.Start)
  10036. Row() {
  10037. Text('起始播放点:')
  10038. .fontSize(14)
  10039. .fontColor($r('app.color.text_color'))
  10040. .margin({ left: 22 })
  10041. Text(`${currentItem.start_time}`)
  10042. .fontSize(14)
  10043. .margin({ left: 10 })
  10044. .fontColor($r('app.color.text_color'))
  10045. .layoutWeight(1)
  10046. }
  10047. .width('100%')
  10048. .margin({ top: 10, bottom: 10 })
  10049. .justifyContent(FlexAlign.Start)
  10050. Row() {
  10051. Text('风格:')
  10052. .fontSize(14)
  10053. .fontColor($r('app.color.text_color'))
  10054. .margin({ left: 22 })
  10055. Text(currentItem.genre)
  10056. .fontSize(14)
  10057. .margin({ left: 10 })
  10058. .fontColor($r('app.color.text_color'))
  10059. .layoutWeight(1)
  10060. }
  10061. .width('100%')
  10062. .margin({ top: 10, bottom: 10 })
  10063. .justifyContent(FlexAlign.Start)
  10064. Row() {
  10065. Text('发行时间:')
  10066. .fontSize(14)
  10067. .fontColor($r('app.color.text_color'))
  10068. .margin({ left: 22 })
  10069. Text(currentItem.year)
  10070. .fontSize(14)
  10071. .margin({ left: 10 })
  10072. .fontColor($r('app.color.text_color'))
  10073. .layoutWeight(1)
  10074. }
  10075. .width('100%')
  10076. .margin({ top: 10, bottom: 10 })
  10077. .justifyContent(FlexAlign.Start)
  10078. Row() {
  10079. Text('质量评分:')
  10080. .fontSize(14)
  10081. .fontColor($r('app.color.text_color'))
  10082. .margin({ left: 22 })
  10083. Text(currentItem.probe_score+"")
  10084. .fontSize(14)
  10085. .margin({ left: 10 })
  10086. .fontColor($r('app.color.text_color'))
  10087. .layoutWeight(1)
  10088. }
  10089. .width('100%')
  10090. .margin({ top: 10, bottom: 10 })
  10091. .justifyContent(FlexAlign.Start)
  10092. Row() {
  10093. Text('音轨号:')
  10094. .fontSize(14)
  10095. .fontColor($r('app.color.text_color'))
  10096. .margin({ left: 22 })
  10097. Text(currentItem.track)
  10098. .fontSize(14)
  10099. .margin({ left: 10 })
  10100. .fontColor($r('app.color.text_color'))
  10101. .layoutWeight(1)
  10102. }
  10103. .width('100%')
  10104. .margin({ top: 10, bottom: 10 })
  10105. .justifyContent(FlexAlign.Start)
  10106. Row() {
  10107. Text('碟号:')
  10108. .fontSize(14)
  10109. .fontColor($r('app.color.text_color'))
  10110. .margin({ left: 22 })
  10111. Text(currentItem.disc)
  10112. .fontSize(14)
  10113. .margin({ left: 10 })
  10114. .fontColor($r('app.color.text_color'))
  10115. .layoutWeight(1)
  10116. }
  10117. .width('100%')
  10118. .margin({ top: 10, bottom: 10 })
  10119. .justifyContent(FlexAlign.Start)
  10120. Row() {
  10121. Text('专辑艺术家:')
  10122. .fontSize(14)
  10123. .fontColor($r('app.color.text_color'))
  10124. .margin({ left: 22 })
  10125. Text(currentItem.ALBUMARTIST)
  10126. .fontSize(14)
  10127. .margin({ left: 10 })
  10128. .fontColor($r('app.color.text_color'))
  10129. .layoutWeight(1)
  10130. }
  10131. .width('100%')
  10132. .margin({ top: 10, bottom: 10 })
  10133. .justifyContent(FlexAlign.Start)
  10134. Row() {
  10135. Text('作曲家:')
  10136. .fontSize(14)
  10137. .fontColor($r('app.color.text_color'))
  10138. .margin({ left: 22 })
  10139. Text(currentItem.COMPOSER)
  10140. .fontSize(14)
  10141. .margin({ left: 10 })
  10142. .fontColor($r('app.color.text_color'))
  10143. .layoutWeight(1)
  10144. }
  10145. .width('100%')
  10146. .margin({ top: 10, bottom: 10 })
  10147. .justifyContent(FlexAlign.Start)
  10148. Row() {
  10149. Text('作词家:')
  10150. .fontSize(14)
  10151. .fontColor($r('app.color.text_color'))
  10152. .margin({ left: 22 })
  10153. Text(currentItem.LYRICIST)
  10154. .fontSize(14)
  10155. .margin({ left: 10 })
  10156. .fontColor($r('app.color.text_color'))
  10157. .layoutWeight(1)
  10158. }
  10159. .width('100%')
  10160. .margin({ top: 10, bottom: 10 })
  10161. .justifyContent(FlexAlign.Start)
  10162. Row() {
  10163. Text('注释:')
  10164. .fontSize(14)
  10165. .fontColor($r('app.color.text_color'))
  10166. .margin({ left: 22 })
  10167. Text(currentItem.COMMENT)
  10168. .fontSize(14)
  10169. .margin({ left: 10 })
  10170. .fontColor($r('app.color.text_color'))
  10171. .layoutWeight(1)
  10172. }
  10173. .width('100%')
  10174. .margin({ top: 10, bottom: 10 })
  10175. .justifyContent(FlexAlign.Start)
  10176. Row() {
  10177. Text('格式:')
  10178. .fontSize(14)
  10179. .fontColor($r('app.color.text_color'))
  10180. .margin({ left: 22 })
  10181. Text(Utility.formatMimeType(currentItem.mimeType))
  10182. .fontSize(14)
  10183. .margin({ left: 10 })
  10184. .fontColor($r('app.color.text_color'))
  10185. .layoutWeight(1)
  10186. }
  10187. .width('100%')
  10188. .margin({ top: 10, bottom: 10 })
  10189. .justifyContent(FlexAlign.Start)
  10190. Row() {
  10191. Text('播放次数:')
  10192. .fontSize(14)
  10193. .fontColor($r('app.color.text_color'))
  10194. .margin({ left: 22 })
  10195. Text(currentItem.playCount?.toString())
  10196. .fontSize(14)
  10197. .margin({ left: 10 })
  10198. .fontColor($r('app.color.text_color'))
  10199. .layoutWeight(1)
  10200. }
  10201. .width('100%')
  10202. .margin({ top: 10, bottom: 10 })
  10203. .justifyContent(FlexAlign.Start)
  10204. Row() {
  10205. Text('流数量:')
  10206. .fontSize(14)
  10207. .fontColor($r('app.color.text_color'))
  10208. .margin({ left: 22 })
  10209. Text(currentItem.nb_streams?.toString())
  10210. .fontSize(14)
  10211. .margin({ left: 10 })
  10212. .fontColor($r('app.color.text_color'))
  10213. .layoutWeight(1)
  10214. }
  10215. .width('100%')
  10216. .margin({ top: 10, bottom: 10 })
  10217. .justifyContent(FlexAlign.Start)
  10218. Row() {
  10219. Text('文件大小:')
  10220. .fontSize(14)
  10221. .fontColor($r('app.color.text_color'))
  10222. .margin({ left: 22 })
  10223. Text(currentItem.size)
  10224. .fontSize(14)
  10225. .margin({ left: 10 })
  10226. .fontColor($r('app.color.text_color'))
  10227. .layoutWeight(1)
  10228. }
  10229. .width('100%')
  10230. .margin({ top: 10, bottom: 10 })
  10231. .justifyContent(FlexAlign.Start)
  10232. Row() {
  10233. Text('文件名:')
  10234. .fontSize(14)
  10235. .fontColor($r('app.color.text_color'))
  10236. .margin({ left: 22 })
  10237. Text(currentItem.fileName)
  10238. .fontSize(14)
  10239. .margin({ left: 10 })
  10240. .fontColor($r('app.color.text_color'))
  10241. .layoutWeight(1)
  10242. }
  10243. .width('100%')
  10244. .margin({ top: 10, bottom: 10 })
  10245. .justifyContent(FlexAlign.Start)
  10246. Row() {
  10247. Text('修改时间:')
  10248. .fontSize(14)
  10249. .fontColor($r('app.color.text_color'))
  10250. .margin({ left: 22 })
  10251. Text(currentItem.cTime)
  10252. .fontSize(14)
  10253. .margin({ left: 10 })
  10254. .fontColor($r('app.color.text_color'))
  10255. .layoutWeight(1)
  10256. }
  10257. .width('100%')
  10258. .margin({ top: 10, bottom: 10 })
  10259. .justifyContent(FlexAlign.Start)
  10260. Row() {
  10261. Text('存放目录:')
  10262. .fontSize(14)
  10263. .fontColor($r('app.color.text_color'))
  10264. .margin({ left: 22 })
  10265. Text(currentItem.filePath)
  10266. .fontSize(12)
  10267. .margin({ left: 10 })
  10268. .fontColor($r('app.color.text_color'))
  10269. .layoutWeight(1)
  10270. }
  10271. .margin({ top: 10, bottom: 10 })
  10272. .width('100%')
  10273. .justifyContent(FlexAlign.Start)
  10274. Row() {
  10275. Text('内嵌歌词:')
  10276. .fontSize(14)
  10277. .fontColor($r('app.color.text_color'))
  10278. .margin({ left: 22 })
  10279. Text(currentItem.lyricContent)
  10280. .fontSize(12)
  10281. .copyOption(CopyOptions.InApp)
  10282. .margin({ left: 10 })
  10283. .fontColor($r('app.color.text_color'))
  10284. .layoutWeight(1)
  10285. }
  10286. .margin({ top: 10, bottom: 10 })
  10287. .width('100%')
  10288. .justifyContent(FlexAlign.Start)
  10289. }
  10290. }
  10291. .margin({ bottom: 20 })
  10292. }
  10293. //定时关闭布局
  10294. @Builder
  10295. TimeCloseSheet() {
  10296. Scroll() {
  10297. Column() {
  10298. this.TimeClose()
  10299. }
  10300. }
  10301. .width('100%')
  10302. .height('100%')
  10303. }
  10304. //倒计时关闭音乐,退出App功能实现。
  10305. @State selectedMinutes: number = 0 // 0表示未开启
  10306. @State remainingSeconds: number = 0
  10307. // 预设时间选项
  10308. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  10309. private formatTime(seconds: number): string {
  10310. const mins = Math.floor(seconds / 60)
  10311. const secs = seconds % 60
  10312. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  10313. }
  10314. // 开始倒计时
  10315. private handleTimeSelect(minutes: number) {
  10316. if (minutes === this.selectedMinutes) {
  10317. this.stopCountdown();
  10318. this.selectedMinutes = 0;
  10319. return;
  10320. }
  10321. this.selectedMinutes = minutes;
  10322. this.remainingSeconds = minutes * 60;
  10323. this.startCountdown(); // 新增调用
  10324. }
  10325. @Builder
  10326. TimeClose() {
  10327. Column() {
  10328. // 倒计时显示区域
  10329. Text(this.selectedMinutes > 0 ?
  10330. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  10331. "定时关闭未开启")
  10332. .fontSize(17)
  10333. .fontColor($r('app.color.text_color'))
  10334. .margin({ top: 2, bottom: 8 });
  10335. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  10336. ForEach(this.presetTimes, (minutes: number, index: number) => {
  10337. // 单行时间选项容器
  10338. Row() {
  10339. // 文字描述区域
  10340. Text(this.getDisplayText(minutes))
  10341. .fontSize(15)
  10342. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  10343. $r('app.color.text_color'))// 选中态颜色变化
  10344. .textAlign(TextAlign.Start)
  10345. .layoutWeight(1); // 占据剩余空间
  10346. // 复选框样式的选择器
  10347. Row() {
  10348. if (minutes === this.selectedMinutes) {
  10349. // 选中状态 - 带勾号的圆形复选框
  10350. Row() {
  10351. // 使用系统内置的勾号图标
  10352. Image($r('sys.media.ohos_ic_public_ok'))
  10353. .width(14)
  10354. .height(14)
  10355. .fillColor(Color.White)
  10356. }
  10357. .width(24)
  10358. .height(24)
  10359. .borderRadius(12)
  10360. .backgroundColor(this.themeColor)
  10361. .justifyContent(FlexAlign.Center)
  10362. .alignItems(VerticalAlign.Center)
  10363. } else {
  10364. // 未选中状态的圆形边框
  10365. Row()
  10366. .width(24)
  10367. .height(24)
  10368. .borderRadius(12)
  10369. .border({
  10370. width: 2,
  10371. color: $r('app.color.text_color'),
  10372. style: BorderStyle.Solid
  10373. })
  10374. .backgroundColor(Color.Transparent)
  10375. }
  10376. }
  10377. .width(24)
  10378. .height(24)
  10379. .margin({ left: 20 })
  10380. .justifyContent(FlexAlign.Center)
  10381. .alignItems(VerticalAlign.Center)
  10382. }
  10383. .width('100%')
  10384. .padding({
  10385. top: 18,
  10386. bottom: 18,
  10387. left: 18,
  10388. right: 18
  10389. })
  10390. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  10391. $r('app.color.bottom_control_background')) // 选中背景高亮
  10392. .borderRadius(12)
  10393. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10394. .margin({ bottom: 18 })
  10395. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  10396. });
  10397. }
  10398. .width('100%')
  10399. .padding(16)
  10400. }
  10401. }
  10402. // 获取显示文本
  10403. private getDisplayText(minutes: number): string {
  10404. if (minutes === -1) {
  10405. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  10406. }
  10407. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  10408. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  10409. }
  10410. // 处理选择事件
  10411. private handleSelect(minutes: number): void {
  10412. if (minutes === -1) { // 自定义
  10413. // 弹出自定义时间对话框
  10414. DialogHelper.showTextInputDialog({
  10415. title: '自定义时间',
  10416. maskColor: Color.Transparent,
  10417. inputType: InputType.Number,
  10418. text: '',
  10419. onChange: (text) => {
  10420. console.error("onChange: " + text);
  10421. },
  10422. onAction: (action, dialogId, content) => {
  10423. if (action == DialogAction.TWO) {
  10424. const customMinutes = Number(content);
  10425. if (customMinutes > 0) {
  10426. this.handleTimeSelect(customMinutes); // 设置自定义时间
  10427. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  10428. }
  10429. }
  10430. }
  10431. });
  10432. } else {
  10433. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  10434. }
  10435. }
  10436. // 添加定时器引用
  10437. private timerId: number = -1;
  10438. // 启动/重置倒计时
  10439. private startCountdown() {
  10440. // 清除旧定时器
  10441. if (this.timerId !== -1) {
  10442. clearInterval(this.timerId);
  10443. }
  10444. // 创建新定时器
  10445. if (this.selectedMinutes > 0) {
  10446. this.timerId = setInterval(() => {
  10447. if (this.remainingSeconds === 15) {
  10448. this.showConfirmationDialog();
  10449. }
  10450. if (this.remainingSeconds > 0) {
  10451. this.remainingSeconds -= 1;
  10452. } else {
  10453. this.stopCountdown();
  10454. this.handleTimeout();
  10455. }
  10456. }, 1000);
  10457. }
  10458. }
  10459. // 15倒计时后再次提示显示确认是否关闭App对话框
  10460. private showConfirmationDialog() {
  10461. DialogHelper.showAlertDialog({
  10462. backgroundColor: $r('app.color.btn_green'),
  10463. title: '确认关闭',
  10464. maskColor: Color.Transparent,
  10465. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  10466. borderStyle: BorderStyle.Dashed,
  10467. primaryButton: '暂不关闭',
  10468. secondaryButton: '确定',
  10469. onAction: (action) => {
  10470. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  10471. this.stopCountdown();
  10472. this.selectedMinutes = 0
  10473. } else if (action == DialogAction.TWO) {
  10474. }
  10475. }
  10476. })
  10477. }
  10478. // 停止倒计时
  10479. private stopCountdown() {
  10480. if (this.timerId !== -1) {
  10481. clearInterval(this.timerId);
  10482. this.timerId = -1;
  10483. }
  10484. }
  10485. // 超时处理
  10486. private handleTimeout() {
  10487. // 执行播放器关闭逻辑
  10488. this.selectedMinutes = 0;
  10489. ToastUtil.showToast(" 定时关闭已完成");
  10490. this.stop(); // 假设存在的播放器实例
  10491. //退出APP
  10492. const mContext = getContext(this) as common.UIAbilityContext
  10493. mContext.terminateSelf();
  10494. AvSessionController.getInstance(true).unregisterSessionListener()
  10495. }
  10496. //倒计时关闭音乐,退出App功能实现结束。
  10497. //播放列表的拖动List 重新排序
  10498. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  10499. //左滑操作 移动文件 重命名 删除等操作
  10500. @Builder
  10501. sonButton(item: VideoItem, index: number, filePath: string) {
  10502. Row() {
  10503. //加入下一首播放
  10504. Button() {
  10505. Image($r('app.media.next_to_play'))
  10506. .fillColor(Color.White)
  10507. .width(20)
  10508. }
  10509. .width(40)
  10510. .height(40)
  10511. .type(ButtonType.Circle)
  10512. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  10513. .backgroundColor(this.themeColor)
  10514. .margin(5)
  10515. .onClick(() => {
  10516. this.addToNextPlay(item);
  10517. })
  10518. Button() {
  10519. Image($r('app.media.close'))
  10520. .fillColor(Color.White)
  10521. .width(20)
  10522. }
  10523. .width(40)
  10524. .height(40)
  10525. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  10526. .type(ButtonType.Circle)
  10527. .backgroundColor(this.themeColor)
  10528. .margin(5)
  10529. .onClick(() => {
  10530. this.songList.splice(Number(index), 1)
  10531. this.sonDataSource.pushArrayData(this.songList)
  10532. })
  10533. Button() {
  10534. Image($r('app.media.share2'))
  10535. .fillColor(Color.White)
  10536. .width(20)
  10537. }
  10538. .width(40)
  10539. .height(40)
  10540. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  10541. .type(ButtonType.Circle)
  10542. .backgroundColor(this.themeColor)
  10543. .margin(5)
  10544. .onClick(() => {
  10545. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  10546. })
  10547. }
  10548. }
  10549. itemMoveSon(index: number, newIndex: number): void {
  10550. if (newIndex < 0 || newIndex >= this.songList.length) {
  10551. return;
  10552. }
  10553. let tmp = this.songList.splice(index, 1);
  10554. this.songList.splice(newIndex, 0, tmp[0]);
  10555. this.sonDataSource.pushArrayData(this.songList)
  10556. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  10557. if(this.modeType==4&&this.playlistTable){
  10558. updateAllSongsSortOrder(this.playlistTable, this.songList,this.currentSongListID)
  10559. }
  10560. }
  10561. @Builder
  10562. PlayList() {
  10563. List({ scroller: this.playListScroller }) {
  10564. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  10565. ListItem() {
  10566. this.MusicItemSon(item, index)
  10567. }
  10568. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  10569. .animation({
  10570. duration: 666,
  10571. curve: 'ease-in-out' // 可选动画曲线
  10572. })
  10573. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 600 }),
  10574. // TransitionEffect.scale({ x: 0, y: 0 })))
  10575. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  10576. //拖动List关键代码开始
  10577. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  10578. .zIndex(this.dragItem === index ? 1 : 0)
  10579. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  10580. .gesture(
  10581. GestureGroup(GestureMode.Sequence,
  10582. LongPressGesture({ repeat: true })
  10583. .onAction((event?: GestureEvent) => {
  10584. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  10585. this.scaleItem = index
  10586. })
  10587. })
  10588. .onActionEnd(() => {
  10589. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  10590. this.scaleItem = -1
  10591. })
  10592. }),
  10593. PanGesture({ fingers: 1, direction: null, distance: 0 })
  10594. .onActionStart(() => {
  10595. this.dragItem = index // 记录当前拖动项索引
  10596. this.dragRefOffset = 0 // 重置偏移基准
  10597. })
  10598. .onActionUpdate((event: GestureEvent) => {
  10599. this.offsetY = event.offsetY - this.dragRefOffset;
  10600. this.neighborItem = -1;
  10601. let indexA = this.songList.indexOf(item);
  10602. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  10603. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  10604. let value: number = 0;
  10605. if (this.offsetY < 0) {
  10606. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  10607. this.neighborItem = indexA - 1;
  10608. this.neighborScale = 1 - value / 20;
  10609. } else if (this.offsetY > 0) {
  10610. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  10611. this.neighborItem = indexA + 1;
  10612. this.neighborScale = 1 - value / 20;
  10613. }
  10614. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  10615. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  10616. this.offsetY -= this.ITEM_INTV;
  10617. this.dragRefOffset += this.ITEM_INTV;
  10618. this.itemMoveSon(indexA, indexA + 1);
  10619. });
  10620. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  10621. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  10622. this.offsetY += this.ITEM_INTV;
  10623. this.dragRefOffset -= this.ITEM_INTV;
  10624. this.itemMoveSon(indexA, indexA - 1);
  10625. });
  10626. }
  10627. })
  10628. .onActionEnd((event: GestureEvent) => {
  10629. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  10630. this.dragItem = -1
  10631. this.neighborItem = -1
  10632. })
  10633. animateTo({
  10634. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  10635. }, () => {
  10636. this.scaleItem = -1
  10637. })
  10638. })
  10639. )
  10640. .onCancel(() => {
  10641. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  10642. this.dragItem = -1
  10643. this.neighborItem = -1
  10644. })
  10645. animateTo({
  10646. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  10647. }, () => {
  10648. this.scaleItem = -1
  10649. })
  10650. })
  10651. ) //拖动List关键代码结束
  10652. .onClick(() => {
  10653. this.doPlay(item, index, true)
  10654. })
  10655. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  10656. }
  10657. .width('100%')
  10658. .height('100%')
  10659. .onReachEnd(() => {
  10660. if(this.modeType === 4 )
  10661. return;
  10662. // 检测是否是流媒体类型(Navidrome/Jellyfin/Emby/AudioStation/Plex),如果是则调用网盘加载更多逻辑
  10663. const isStreamingSong = this.currentSong && (
  10664. isNavidromeType(this.currentSong.type) ||
  10665. isJellyfinType(this.currentSong.type) ||
  10666. isEmbyType(this.currentSong.type) ||
  10667. isAudioStationType(this.currentSong.type) ||
  10668. isPlexType(this.currentSong.type)
  10669. );
  10670. if (isStreamingSong && hasMoreData()) {
  10671. Logger.info('heanup', '播放列表滚动到底部,加载更多流媒体歌曲');
  10672. void this.loadMoreNavidromeSongs();
  10673. } else {
  10674. void this.tryLoadNextPageForPlayback();
  10675. }
  10676. })
  10677. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  10678. // .animation({ duration: 500, curve: Curve.Ease }))
  10679. .cachedCount(10)
  10680. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  10681. .gesture(PinchGesture({ fingers: 2 })
  10682. .onActionEnd((event: GestureEvent) => {
  10683. this.setSonListTwoFingers()
  10684. })
  10685. .onActionUpdate(e => {
  10686. this.scaleValue = this.pinchValue * e.scale
  10687. })
  10688. .onActionStart(e => {
  10689. }))
  10690. .padding({
  10691. bottom: 0
  10692. })
  10693. }
  10694. setSonListTwoFingers() {
  10695. this.pinchValue = this.scaleValue;
  10696. Logger.info('this.pinchValue = ' + this.pinchValue);
  10697. if (this.pinchValue >= 1) {
  10698. this.sonTwoFingerType++
  10699. Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
  10700. if (this.sonTwoFingerType > 3) {
  10701. this.sonTwoFingerType = 1
  10702. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  10703. }
  10704. } else {
  10705. this.sonTwoFingerType--
  10706. Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
  10707. if (this.sonTwoFingerType < 1) {
  10708. this.sonTwoFingerType = 1
  10709. }
  10710. }
  10711. PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
  10712. this.pinchValue = 1;
  10713. this.scaleValue = 1;
  10714. }
  10715. @State sonTwoFingerType:number = 3
  10716. @Builder
  10717. private MusicItemSon(item: VideoItem, index?: number) {
  10718. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10719. Row() {
  10720. Stack() {
  10721. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  10722. .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  10723. .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  10724. .alt($r('app.media.alt'))
  10725. .fillColor(this.themeColor)
  10726. .borderRadius(this.isCoverRectangle?11:'100%')
  10727. .clip(true)
  10728. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  10729. .draggable(false)// 禁止长按手势拖动
  10730. .autoResize(true) // 重采样,可减少内存占用
  10731. .margin({ left: 20 })
  10732. }
  10733. .width('15%')
  10734. Column() {
  10735. Column() {
  10736. Text(this.isShowFileName?item.fileName :item.name)
  10737. .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
  10738. .fontColor(this.curIndex === index ? this.themeColor :
  10739. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  10740. .maxLines(1)
  10741. .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
  10742. Row() {
  10743. Column(){
  10744. Text(item.md5Str?.includes('Lossless')?
  10745. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  10746. .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
  10747. .padding({ top: 3,right:6,left:6,bottom:3 })
  10748. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  10749. $r('app.color.text_color'))
  10750. .fontWeight(500)
  10751. .borderRadius(12)
  10752. .visibility(StrUtil.isEmpty(item.md5Str) ? Visibility.None : Visibility.Visible)
  10753. .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
  10754. .backgroundColor('#FFC107')
  10755. }
  10756. .padding({ top: 8 })
  10757. Text(StrUtil.isEmpty(item.artist) ? item.duration :
  10758. item.artist + ' ' + item?.duration)
  10759. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  10760. .padding({ top: 8 })
  10761. .maxLines(1)
  10762. .fontColor(this.curIndex === index ? this.themeColor :
  10763. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  10764. .margin({ left: StrUtil.isEmpty(item.md5Str)? 12 :this.sonTwoFingerType == 3 ? 5 : 3 })
  10765. Blank()
  10766. Text(item.size)
  10767. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  10768. .padding({ top: 8 })
  10769. .maxLines(1)
  10770. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  10771. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  10772. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  10773. .margin({ left: 10 })
  10774. }
  10775. }
  10776. .height('100%')
  10777. .width('100%')
  10778. .justifyContent(FlexAlign.Center)
  10779. .alignItems(HorizontalAlign.Start)
  10780. }
  10781. .height('100%')
  10782. .width('65%')
  10783. Column() {
  10784. PlayingIndicator({
  10785. isActive: this.videoUrl === item.filePath && !this.isMultiSelect,
  10786. indicatorSize: 18
  10787. })
  10788. }
  10789. .width('20%')
  10790. }
  10791. }
  10792. .backgroundColor(Color.Transparent)
  10793. .width('100%')
  10794. .reuseId('son_item')
  10795. .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
  10796. .shadow(this.scaleItem === index ? {
  10797. radius: 70,
  10798. color: '#15000000',
  10799. offsetX: 0,
  10800. offsetY: 0
  10801. } :
  10802. {
  10803. radius: 0,
  10804. color: '#15000000',
  10805. offsetX: 0,
  10806. offsetY: 0
  10807. })
  10808. .animation({ curve: Curve.Sharp, duration: 300 })
  10809. }
  10810. @Builder
  10811. MusicPlayBuilder() {
  10812. Column() {
  10813. this.IjkMusicPlayerView()
  10814. }
  10815. .transition(TransitionEffect.asymmetric(
  10816. TransitionEffect.opacity(1),
  10817. TransitionEffect.OPACITY
  10818. ))
  10819. .visualEffect(deviceInfo.sdkApiVersion>=20&&this.bgController?
  10820. new hdsEffect.HdsEffectBuilder()
  10821. .shaderEffect({
  10822. effectType: hdsEffect.EffectType.UV_BACKGROUND_FLOW_LIGHT,
  10823. animation: {
  10824. duration: 10000,
  10825. iterations: -1,
  10826. autoPlay: true,
  10827. onFinish: ()=> {
  10828. console.info('Succeeded in finishing');
  10829. }
  10830. },
  10831. controller: this.bgController,
  10832. })
  10833. .buildEffect():null)
  10834. .height('100%')
  10835. .width('100%')
  10836. .onDisAppear(() => {
  10837. this.translateY = 0;
  10838. this.playDragUiOpacity = 1
  10839. })
  10840. .translate({ y: this.translateY })
  10841. .gesture(
  10842. PanGesture(this.panOption)
  10843. .onActionUpdate((event?: GestureEvent) => {
  10844. if (event) {
  10845. // 判断滑动方向
  10846. const offsetY = event.offsetY ?? 0;
  10847. const isSwipeUp = offsetY < 0;
  10848. if (isSwipeUp) {
  10849. // 向上滑动:不应用位移动画,保持 translateY = 0
  10850. this.translateY = 0;
  10851. this.scaleValueImage = 1
  10852. this.scaleValueText = 1
  10853. this.playDragUiOpacity = 1
  10854. } else {
  10855. if(this.isGeKongPlayNext){
  10856. return
  10857. }
  10858. // 向下滑动:应用位移动画
  10859. this.translateY = offsetY;
  10860. // 向下滑动时的缩放效果
  10861. this.getUIContext().animateTo({
  10862. duration: 500,
  10863. curve: Curve.Sharp
  10864. }, () => {
  10865. this.scaleValueImage = Math.min(1, Math.max(0.5, 1 - this.translateY / 880));
  10866. console.info('onecold scaleValueImage:', this.scaleValueImage)
  10867. this.scaleValueText = Math.min(1, Math.max(0.88, 1 - this.translateY / 2000));
  10868. this.playDragUiOpacity = Math.min(1, Math.max(0, 1 - this.translateY / 300));
  10869. })
  10870. }
  10871. }
  10872. })
  10873. .onActionEnd((event?: GestureEvent) => {
  10874. // 判断滑动方向
  10875. const offsetY = event?.offsetY ?? 0;
  10876. const isSwipeUp = offsetY < 0;
  10877. const minDistance = 300; // 最小滑动距离
  10878. const minVelocity = 500; // 最小滑动速度
  10879. const velocity = event?.velocityY ?? 0;
  10880. if (isSwipeUp) {
  10881. // 向上滑动:切换下一首
  10882. const shouldSwitch = this.isPlayPageSwipeNext &&
  10883. (Math.abs(offsetY) > minDistance || Math.abs(velocity) > minVelocity);
  10884. if (shouldSwitch) {
  10885. // 直接切换下一首,无需动画(因为界面没有移动)
  10886. this.playNext().catch(() => {
  10887. Logger.error('heanup MusicPlayBuilder', '向上滑动切换下一首失败');
  10888. });
  10889. }
  10890. } else {
  10891. //这里加个变量,是否开启隔空手势播放下一首
  10892. if(this.isGeKongPlayNext){
  10893. this.playNext()
  10894. return
  10895. }
  10896. // 向下滑动:关闭播放页
  10897. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  10898. if (shouldClose) {
  10899. // 添加关闭动画
  10900. this.getUIContext().animateTo({
  10901. duration: 600,
  10902. curve: Curve.Friction
  10903. }, () => {
  10904. this.isShowPlay = false;
  10905. this.scaleValueImage = 1
  10906. this.scaleValueText = 1
  10907. this.playDragUiOpacity = 1
  10908. this.translateY = 0;
  10909. })
  10910. } else {
  10911. // 回弹动画
  10912. this.getUIContext().animateTo({
  10913. duration: 600,
  10914. curve: Curve.Friction
  10915. }, () => {
  10916. this.scaleValueImage = 1
  10917. this.scaleValueText = 1
  10918. this.playDragUiOpacity = 1
  10919. this.translateY = 0;
  10920. })
  10921. }
  10922. }
  10923. })
  10924. )
  10925. }
  10926. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  10927. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  10928. HeightBreakpoint.HEIGHT_LG;
  10929. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  10930. @State topBarHeight: number = 50
  10931. @State barOpacity: number = 1
  10932. @State barBottomOpacity: number = 1
  10933. private hideDone: boolean = false;
  10934. @State currentYOffset: number = 0;
  10935. @State bottomBarHeight: number = 68;
  10936. private isHiding: boolean = false;
  10937. //是否是Pura X外屏,或者小屏幕
  10938. isPuraWP() {
  10939. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  10940. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  10941. }
  10942. //是否是Pura X外屏,或者小屏幕,手机横屏
  10943. /**
  10944. * 是否是Pura X外屏,或者小屏幕,手机横屏
  10945. * @returns
  10946. */
  10947. isCoverOpacity() {
  10948. if (this.isPuraWP()) {
  10949. return true
  10950. }
  10951. if (this.isPhoneLan()) {
  10952. return true
  10953. }
  10954. if (deviceInfo.marketName.includes('Pura X')
  10955. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  10956. return true
  10957. }
  10958. return false
  10959. }
  10960. //是不是手机横屏
  10961. isPhoneLan() {
  10962. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  10963. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  10964. logHiCarWindow(`isPhoneLan width=${this.windowWidth}`);
  10965. logHiCarWindow(`isPhoneLan height=${this.windowHeight}`);
  10966. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarStatus=${this.isHiCarStatus}`);
  10967. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, curDisplayIsHiCar=${this.curDisplayIsHiCar}`);
  10968. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall=${this.isHiCarSmall()}`);
  10969. if (this.isHiCarKuanBianPing()) {
  10970. return true
  10971. }
  10972. if (this.isHiCar()) {
  10973. return false
  10974. }
  10975. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  10976. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  10977. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  10978. return true
  10979. }
  10980. return false
  10981. }
  10982. //是不是1920x720的hicar的屏幕分辨率
  10983. isHiCarKuanBianPing(){
  10984. // if(!this.isHiCar()){
  10985. // return false
  10986. // }
  10987. const hiCarAspectRatios: HiCarAspectRatio[] = [
  10988. { ratio: 1920 / 720, name: "1920x720" },
  10989. ];
  10990. const currentRatio: number = this.windowWidth / this.windowHeight;
  10991. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  10992. logHiCarWindow(`HiCarKuanBianPing currentRatio=${currentRatio}`)
  10993. for (const hiCarRatio of hiCarAspectRatios) {
  10994. logHiCarWindow(`HiCarKuanBianPing hiCarRatio=${hiCarRatio.ratio}`)
  10995. logHiCarWindow(`HiCarKuanBianPing diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  10996. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  10997. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  10998. //宽扁平的尺寸设置列表展示
  10999. this.twoFingerType ==3
  11000. this.isGridMusic = false
  11001. return true;
  11002. }
  11003. }
  11004. return false;
  11005. }
  11006. //是不是hicar的屏幕分辨率
  11007. isHiCarSmall() {
  11008. if(!this.isHiCar()){
  11009. return false
  11010. }
  11011. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  11012. {
  11013. this.columns = 6
  11014. return false
  11015. }
  11016. const hiCarAspectRatios: HiCarAspectRatio[] = [
  11017. { ratio: 800 / 480, name: "800x480" },
  11018. { ratio: 1280 / 720, name: "1280x720" },
  11019. { ratio: 1920 / 1080, name: "1920x1080" },
  11020. ];
  11021. const currentRatio: number = this.windowWidth / this.windowHeight;
  11022. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  11023. logHiCarWindow(`HiCarSmall currentRatio=${currentRatio}`)
  11024. for (const hiCarRatio of hiCarAspectRatios) {
  11025. logHiCarWindow(`HiCarSmall hiCarRatio=${hiCarRatio.ratio}`)
  11026. logHiCarWindow(`HiCarSmall diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  11027. logHiCarWindow(`HiCarSmall isHiCarStatus=${this.isHiCarStatus}`);
  11028. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  11029. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  11030. //宽扁平的尺寸设置列表展示
  11031. return true;
  11032. }
  11033. }
  11034. return false;
  11035. }
  11036. isHiCar(): boolean {
  11037. return this.curDisplayIsHiCar;
  11038. }
  11039. //是不是正常的手机竖屏
  11040. isPhonePortrait() {
  11041. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  11042. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  11043. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  11044. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  11045. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  11046. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  11047. return true
  11048. }
  11049. return false
  11050. }
  11051. @State showSpeedDialog: boolean = false
  11052. @State longPressSpeed: number = 3 //长按默认倍数
  11053. @Builder
  11054. SpeedDialog() {
  11055. Stack() {
  11056. Column() {
  11057. Text('已切换至' + this.longPressSpeed + '倍速播放')
  11058. .fontColor(Color.White)
  11059. .visibility(Visibility.Hidden)
  11060. }
  11061. .backgroundColor(Color.Black)
  11062. .borderRadius(20)
  11063. .padding({
  11064. top: 10,
  11065. right: 20,
  11066. left: 15,
  11067. bottom: 20
  11068. })
  11069. .opacity(0.6)
  11070. Text('已切换至' + this.longPressSpeed + '倍速播放')
  11071. .fontColor(Color.White)
  11072. }
  11073. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  11074. .zIndex(5)
  11075. .margin({ top: 80 })
  11076. }
  11077. @Builder
  11078. IjkMusicPlayerView() {
  11079. Stack() {
  11080. if(canIUse("SystemCapability.UIDesign.HDSComponent.Core")
  11081. &&deviceInfo.sdkApiVersion>=20&&this.sceneBgController){
  11082. HdsVisualComponent()
  11083. .scene(HdsSceneType.DUAL_EDGE_FLOW_LIGHT_WITH_BACKGROUND_MASK, this.sceneBgController, () => {
  11084. console.info('Succeeded in finishing');
  11085. })
  11086. .width('100%')
  11087. .height('100%')
  11088. .visibility(this.isShowBgLiuGUANG?Visibility.Visible:Visibility.None)
  11089. }
  11090. Column() {
  11091. Column() {
  11092. //播放标题
  11093. Column() {
  11094. this.PlayTitle()
  11095. }
  11096. .opacity(this.playDragUiOpacity)
  11097. .position({ x: 0, y: this.isCoverOpacity() ? 10 : 30 })
  11098. .width('100%')
  11099. .margin({ top: 0 })
  11100. .height(PlayConstants.HEIGHT)
  11101. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  11102. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  11103. if (this.showSpeedDialog) {
  11104. this.SpeedDialog()
  11105. }
  11106. Stack() {
  11107. //手势拖动快进
  11108. Column()
  11109. .width(CommonConstants.FULL_PERCENT)
  11110. .height('100%')
  11111. .gesture(
  11112. GestureGroup(GestureMode.Parallel,
  11113. // 长按屏幕倍数播放
  11114. LongPressGesture({ repeat: true })
  11115. .onAction(() => {
  11116. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  11117. this.showSpeedDialog = true;
  11118. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  11119. }
  11120. })
  11121. .onActionEnd(() => {
  11122. this.showSpeedDialog = false;
  11123. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  11124. }),
  11125. )
  11126. )
  11127. }
  11128. .height('65%')
  11129. Swiper() {
  11130. this.CoverInfo()
  11131. this.PlayerLyrics()
  11132. }
  11133. .onChange((index: number) => {
  11134. this.currentSwiperIndex = index
  11135. if (index === 1) {
  11136. this.syncLyricPositionNow()
  11137. }
  11138. })
  11139. .indicator(false)
  11140. .displayCount(this.getPlayerSwiperDisplayCount())
  11141. .clip(false)
  11142. .loop(false)
  11143. .autoPlay(false)
  11144. // .interval(8000)
  11145. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  11146. .height('100%')
  11147. .hitTestBehavior(HitTestMode.Transparent)
  11148. Image($r('app.media.icon_replay'))
  11149. .objectFit(ImageFit.Auto)
  11150. .width('120px')
  11151. .height('120px')
  11152. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  11153. .border({ width: 0 })
  11154. .visibility(Visibility.None)
  11155. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  11156. .onClick(() => {
  11157. console.info('onecold startPlayOrResumePlay 6744')
  11158. this.startPlayOrResumePlay();
  11159. })
  11160. }
  11161. .width(CommonConstants.FULL_PERCENT)
  11162. .height(CommonConstants.FULL_PERCENT)
  11163. .justifyContent(FlexAlign.End)
  11164. }
  11165. .justifyContent(FlexAlign.End)
  11166. .margin({ bottom: 5 })
  11167. }
  11168. .backgroundImage(!this.isMusicBGCover||StrUtil.isEmpty(this.cover)?null: this.cover)
  11169. .backgroundImageSize(this.isPuraWP()||!this.isMusicBGCover ? { width: '100%' } : { height: '150%', width: '100%' })
  11170. .animation({
  11171. duration: 666,
  11172. curve: 'ease-in-out' // 可选动画曲线
  11173. })
  11174. .backgroundBlurStyle((this.isPuraWP() && this.currentSwiperIndex === 0) ||!this.isMusicBGCover
  11175. ? BlurStyle.NONE :
  11176. BlurStyle.BACKGROUND_ULTRA_THICK)
  11177. .hitTestBehavior(HitTestMode.Transparent)
  11178. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  11179. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  11180. .onClick(() => {
  11181. if(this.isHiCar())
  11182. return
  11183. if(this.is_auto_hide_progress){
  11184. this.is_auto_hide_progress = false
  11185. }
  11186. this.startAutoHide()
  11187. })
  11188. }
  11189. @Consume progressValue: number ;
  11190. @State currentTime: string = "00:00";
  11191. @State totalTime: string = "00:00";
  11192. @State loadingVisible: Visibility = Visibility.None;
  11193. @State replayVisible: Visibility = Visibility.None;
  11194. @State slideEnable: boolean = false;
  11195. @State aspRatio: number = 0.5;
  11196. @State mContext: object | undefined = undefined;
  11197. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  11198. @State mFirst: boolean = true;
  11199. @State mDestroyPage: boolean = false;
  11200. @State playSpeed: number = 1;
  11201. @State oldSeconds: number = 0;
  11202. @State isSeekTo: boolean = false;
  11203. @State isCurrentTime: boolean = false;
  11204. @State videoWidth: string = '100%';
  11205. @State videoHeight: string = '100%';
  11206. @State initAspectRatio: number = 1;
  11207. @State videoAspectRatio: number = this.initAspectRatio;
  11208. @State videoUrl: string = '';
  11209. private last: number = 0;
  11210. @State videoParentAspectRatio: number = this.initAspectRatio;
  11211. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  11212. @Consume CONTROL_PlayStatus: number ;
  11213. @State PROGRESS_MAX_VALUE: number = 100;
  11214. @State updateProgressTimer: number = 0;
  11215. private readonly progressUpdateIntervalMs: number = 120;
  11216. private readonly lyricUpdateMinDeltaMs: number = 24;
  11217. private lastLyricRenderPosition: number = Number.NaN;
  11218. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  11219. @State name: string = '';
  11220. // @State loop: boolean = false;
  11221. @State playType: number = 0; //0:连续循环播放 1:单片重复播放 2:正常播放 3:随机播放 4:连续播放不循环
  11222. @State multiple: string = '1.0X';
  11223. xcomponentController: XComponentController = new XComponentController()
  11224. private panOptionBright: PanGestureOptions =
  11225. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  11226. private panOptionVolume: PanGestureOptions =
  11227. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  11228. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  11229. //手势的音量控制和亮度控制
  11230. private positionX: number = PlayConstants.POSITION_X;
  11231. private positionY: number = PlayConstants.POSITION_Y;
  11232. private windowClass: window.Window = globalThis.windowClass
  11233. @State volume: number = 0.8;
  11234. @State volumeBoostPercent: number = 0
  11235. @State volumeSmall: boolean = false
  11236. @State autoParseMusicName: boolean = true
  11237. @State isShowFileName: boolean = false
  11238. @State isLongNameRoLL: boolean = true//长歌名滚动
  11239. private readonly volumeBoostPreferenceKey: string = 'volumeBoostPercent';
  11240. private readonly volumeBoostMaxPercent: number = 500;
  11241. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  11242. @State bright: number = PlayConstants.BRIGHT;
  11243. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  11244. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  11245. @State screenWidth: number = 0
  11246. @State screenHeight: number = 0
  11247. @State statusBarHeight: number = 0
  11248. @State isYesFull: boolean = false
  11249. private seekValue: number = 0
  11250. @State isVideoLock: boolean = false; // Whether the video playback is locked
  11251. private preloadNextRandomIndex: number = -1; // 预缓存的随机下一首索引
  11252. private playbackUrlRequestSerial: number = 0;
  11253. eventHub = getContext().eventHub;
  11254. private isAppForeground: boolean = true;
  11255. private lastBufferingLogTs: number = 0;
  11256. private readonly bufferingLogIntervalMs: number = 5000;
  11257. //投播组件
  11258. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  11259. // 新的投播控制器(封装了官方示例的逻辑)
  11260. private castControllerWrapper: CastController | undefined = undefined;
  11261. // 保留原始的 avCastController 引用(用于兼容旧代码)
  11262. private castController: avSession.AVCastController | undefined = undefined;
  11263. @State isCastPlaying: boolean = false;
  11264. @State currentTime2: number = 0;
  11265. @State currentStringTime: string = '00:00';
  11266. @State duration: number = 0;
  11267. @State isReady: boolean = false;
  11268. @State durationTime: number = 0;
  11269. @State durationStringTime: string = '00:00';
  11270. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  11271. // @State isPlaying: boolean = false;
  11272. private castSeek: boolean = false;
  11273. private castItem: avSession.AVQueueItem | undefined = undefined;
  11274. private castFile: fs.File | undefined = undefined; // 保持文件描述符引用,避免被垃圾回收
  11275. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  11276. @State rotateAngle2: number = -9
  11277. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  11278. @Consume cover: string | undefined ;
  11279. @State artist: string | undefined = ''
  11280. // 1.初始化controller
  11281. private lyricController: LyricController = new LyricController()
  11282. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  11283. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  11284. private parser = new LyricParser()
  11285. @State randomShakenX: number = 0
  11286. @State randomShakenY: number = 0
  11287. @State lyricTextSize: number = 24
  11288. @State lyricContent: string = ''
  11289. @State isDebug: boolean = false
  11290. @State isHightLightCenter: boolean = true
  11291. private syncWordByWordLyricMode(): void {
  11292. this.lyricController.setEnableWordByWordLyric(this.isEnableWordByWordLyric)
  11293. this.lyricControllerXF.setEnableWordByWordLyric(this.isEnableWordByWordLyric)
  11294. this.lyricControllerSingle.setEnableWordByWordLyric(this.isEnableWordByWordLyric)
  11295. }
  11296. private syncLyricLightTextMode(): void {
  11297. this.lyricController.setLightText(this.isLightText)
  11298. this.lyricControllerXF.setLightText(this.isLightText)
  11299. this.lyricControllerSingle.setLightText(this.isLightText)
  11300. }
  11301. /**
  11302. * 初始化歌词加载与展示逻辑
  11303. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  11304. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  11305. * @param isApi2 是否使用API2获取歌词(可选)
  11306. *
  11307. * 主要流程:
  11308. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  11309. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  11310. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  11311. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  11312. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  11313. * 6. 解析失败或读取失败时,清空歌词显示。
  11314. *
  11315. * 注意事项:
  11316. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  11317. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  11318. * - 歌词内容解析后通过lyricController驱动UI渲染。
  11319. */
  11320. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
  11321. if (StrUtil.isEmpty(lyricPath)) {
  11322. return
  11323. }
  11324. this.syncWordByWordLyricMode()
  11325. this.syncLyricLightTextMode()
  11326. this.initPipLyricSetting()
  11327. this.lyricControllerSingle
  11328. .setTextSize(15)
  11329. .setCacheSize(4)
  11330. .setTextColor("#FFFFFF")
  11331. .setHighlightColor(this.currentHighLightLyricColor)
  11332. .setHighlightScale(1.2)
  11333. .setEmptyHint("")
  11334. .setLineSpace(1)
  11335. .setAlignMode('center')
  11336. .setAnimationDuration(500)
  11337. .setSingleLine(true)
  11338. this.lyricContent = ''
  11339. this.lyricController
  11340. .setTextSize(this.currentLyricSize)
  11341. .setCacheSize(4)
  11342. .setTextColor("#DDDDDD")
  11343. .setHighlightColor("#FFFFFF")
  11344. .setEmptyHint("")
  11345. .setAnimationDuration(1000)
  11346. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  11347. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  11348. this.setBlurDegree(this.blurDegree, false)
  11349. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  11350. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  11351. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  11352. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  11353. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  11354. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  11355. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  11356. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  11357. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  11358. this.lyricController.setTextWeight(this.lyricTextWeight)
  11359. this.showSingleLyric = false
  11360. // 加载已保存的歌词时间偏移
  11361. this.loadLyricTimeOffset()
  11362. this.lyricController.setLyric(null)
  11363. this.lyricControllerSingle.setLyric(null)
  11364. console.log("onecold lyricPath =" + lyricPath)
  11365. // 1. 检查内嵌歌词
  11366. let neiqianLrc = ''
  11367. let lyContent = this.currentSong?.lyricContent
  11368. if(lyContent && StrUtil.isNotEmpty(lyContent)){
  11369. neiqianLrc = lyContent
  11370. }
  11371. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast && !isLocal) {
  11372. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  11373. // Navidrome JSON歌词转换
  11374. if (this.currentSong && isNavidromeType(this.currentSong.type)) {
  11375. const convertedLyric: string | undefined = LyricUtil.convertNavidromeJsonLyricToLrc(neiqianLrc);
  11376. if (convertedLyric) {
  11377. neiqianLrc = convertedLyric;
  11378. console.log("onecold Navidrome歌词转换成功");
  11379. }
  11380. }
  11381. this.setLyricToControllers(neiqianLrc);
  11382. return
  11383. }
  11384. // 2. 远程播放实时探测歌词: 优先探测内嵌歌词,失败后查找同路径同名 .lrc
  11385. if (this.currentSong && shouldResolveRemoteLyricOnPlay(this.currentSong) && !isOnLineAndToast && !isLocal) {
  11386. const remoteLyric: string = await tryResolveRemotePlaybackLyric({
  11387. song: this.currentSong,
  11388. playbackUrl: this.videoUrl,
  11389. manager: RemoteDriveManager.getInstance(),
  11390. detectEncoding: (data: ArrayBuffer): string => this.detect(data)
  11391. });
  11392. if (StrUtil.isNotEmpty(remoteLyric)) {
  11393. this.currentSong.lyricContent = remoteLyric;
  11394. this.setLyricToControllers(remoteLyric);
  11395. void this.persistRemoteMetadataToDb(this.currentSong);
  11396. return;
  11397. }
  11398. }
  11399. // 3. 尝试从服务器获取歌词 (Navidrome/Jellyfin/Emby/AudioStation/Plex)
  11400. if (this.currentSong && (isJellyfinType(this.currentSong.type)||isNavidromeType(this.currentSong.type)
  11401. || isEmbyType(this.currentSong.type) || isAudioStationType(this.currentSong.type)
  11402. || isPlexType(this.currentSong.type))) {
  11403. const manager = RemoteDriveManager.getInstance();
  11404. const getAccount = (accountId: string) => manager.getWebDavAccountById(accountId);
  11405. // 将currentSong转换为SongData接口
  11406. const songData: SongData = {
  11407. webdav_account_id: this.currentSong.webdav_account_id,
  11408. artist: this.currentSong.artist,
  11409. name: this.currentSong.name,
  11410. webdav_id: this.currentSong.webdav_id,
  11411. lyricIndex: this.currentSong.lyricIndex,
  11412. type: this.currentSong.type
  11413. };
  11414. let serverLyric = '';
  11415. if (!serverLyric && isNavidromeType(songData.type)) {
  11416. serverLyric = await lyricService.fetchNavidromeLyric(songData, getAccount,this.currentSong.id);
  11417. }
  11418. if (!serverLyric && isJellyfinType(songData.type)) {
  11419. serverLyric = await lyricService.fetchJellyfinLyric(songData, getAccount);
  11420. }
  11421. if (!serverLyric && isEmbyType(songData.type)) {
  11422. serverLyric = await lyricService.fetchEmbyLyric(songData, getAccount);
  11423. }
  11424. if (!serverLyric && isAudioStationType(songData.type)) {
  11425. serverLyric = await lyricService.fetchAudioStationLyric(songData, getAccount);
  11426. }
  11427. if (!serverLyric && isPlexType(songData.type)) {
  11428. serverLyric = await lyricService.fetchPlexLyric(songData, getAccount);
  11429. }
  11430. if (serverLyric) {
  11431. this.setLyricToControllers(serverLyric, lyricPath);
  11432. return;
  11433. }
  11434. }
  11435. // 4. 尝试在线歌词API
  11436. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath))
  11437. && !Utility.isVideoByExtension(this.videoUrl))) {
  11438. this.fetchOnlineLyric(lyricPath, isOnLineAndToast || false, isApi2);
  11439. return;
  11440. }
  11441. // 5. 从本地文件读取歌词
  11442. await this.loadLyricFromFile(lyricPath, isLocal || false);
  11443. }
  11444. /**
  11445. * 从本地文件加载歌词
  11446. */
  11447. private async loadLyricFromFile(lyricPath: string, isLocal: boolean): Promise<void> {
  11448. try {
  11449. let realLyricPath = lyricPath;
  11450. // 读取文件内容
  11451. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  11452. const stat = await fileIo.stat(file.fd);
  11453. const arrayBuffer = new ArrayBuffer(stat.size);
  11454. fs.read(file.fd, arrayBuffer)
  11455. .then((readLen: number) => {
  11456. console.info("read file data succeed");
  11457. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  11458. if (buf.length === 0) {
  11459. throw new Error("Buffer is empty after reading the file");
  11460. }
  11461. try {
  11462. // 检测文件编码
  11463. let detectedEncoding = this.detect(arrayBuffer);
  11464. console.info("onecoldT Detected encoding: " + detectedEncoding);
  11465. // 使用检测到的编码解码,解决中文乱码问题
  11466. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  11467. console.info("onecoldT Detected textDecoder: " + textDecoder);
  11468. let fileContent = textDecoder.decode(buf);
  11469. console.info(`onecoldT The content of file1: ${fileContent}`);
  11470. console.info(`onecold The content of file2: ${fileContent}`);
  11471. this.lyricContent = fileContent;
  11472. if(isLocal){
  11473. // 编辑标签选择本地歌词需要赋值给this.lyricConStr
  11474. this.lyricConStr = fileContent;
  11475. }
  11476. this.setLyricToControllers(fileContent);
  11477. console.info(`The content of file: ${fileContent}`);
  11478. } catch (chardetError) {
  11479. console.error("chardet.detect failed with error: " + chardetError.message);
  11480. this.clearLyricControllers();
  11481. }
  11482. })
  11483. .catch((err: BusinessError) => {
  11484. this.clearLyricControllers();
  11485. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  11486. })
  11487. .catch((err: Error) => {
  11488. this.clearLyricControllers();
  11489. console.error("read file 2 data failed with error message: " + err.message);
  11490. })
  11491. .finally(() => {
  11492. fs.closeSync(file);
  11493. });
  11494. } catch (error) {
  11495. this.clearLyricControllers();
  11496. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  11497. }
  11498. }
  11499. detect(data: ArrayBuffer): string {
  11500. //创建检测对象
  11501. let detector: UniversalDetector = new UniversalDetector();
  11502. // 限制检测数据大小,避免内存溢出
  11503. // 通常只需要检测文件前16KB就足够判断编码格式
  11504. const MAX_DETECT_SIZE = 16 * 1024; // 16KB
  11505. const detectSize = Math.min(data.byteLength, MAX_DETECT_SIZE);
  11506. // 传入检测数据并实时判断编码格式
  11507. detector.handleData(data, 0, detectSize);
  11508. // 标记检测数据 读取结束
  11509. detector.dataEnd();
  11510. // 获取检测结果
  11511. let detected: string = detector.getDetectedCharset();
  11512. // 释放资源
  11513. detector.reset();
  11514. Logger.info(TAG, "heanup detect encoding: " + detected + ", data size: " + data.byteLength + ", detect size: " + detectSize);
  11515. return detected;
  11516. }
  11517. /**
  11518. * 设置歌词到所有控制器
  11519. * @param lyricText 歌词文本
  11520. * @param savePath 可选,如果提供则保存到本地文件
  11521. */
  11522. private setLyricToControllers(lyricText: string, savePath?: string): void {
  11523. if (StrUtil.isEmpty(lyricText)) {
  11524. this.clearLyricControllers();
  11525. return;
  11526. }
  11527. this.lyricContent = lyricText;
  11528. const lines: string[] = lyricText.split('\n').map((line: string) => line.trim());
  11529. const lyric: Lyric = this.parser.parse(lines);
  11530. this.lyricController.setLyric(lyric);
  11531. this.lyricControllerXF.setLyric(lyric);
  11532. this.lyricControllerSingle.setLyric(lyric);
  11533. this.showSingleLyric = true;
  11534. // 如果提供了保存路径,保存歌词到本地
  11535. if (savePath) {
  11536. this.saveDataToFile(lyricText, savePath);
  11537. }
  11538. }
  11539. /**
  11540. * 清空所有歌词控制器
  11541. */
  11542. private clearLyricControllers(): void {
  11543. this.lyricController.setLyric(null);
  11544. this.lyricControllerXF.setLyric(null);
  11545. this.lyricControllerSingle.setLyric(null);
  11546. }
  11547. private extractLyricCopyLines(lyricText: string): string[] {
  11548. if (StrUtil.isEmpty(lyricText)) {
  11549. return [];
  11550. }
  11551. const normalizedLyric = LyricUtil.convertLyricToSimpleLrc(lyricText);
  11552. const source = StrUtil.isNotEmpty(normalizedLyric) ? normalizedLyric : lyricText;
  11553. const lines = source.split('\n');
  11554. const result: string[] = [];
  11555. const metaTagPattern = /^\[(ti|ar|al|by|offset|hash|sign|qq|total|tool|re|ve|length|au):?.*]$/i;
  11556. for (let i = 0; i < lines.length; i++) {
  11557. const line = lines[i].trim();
  11558. if (!line || metaTagPattern.test(line)) {
  11559. continue;
  11560. }
  11561. const pureLine = line
  11562. .replace(/\[\d{1,2}:\d{2}(?:\.\d{1,3})?]/g, '')
  11563. .replace(/<\d{1,2}:\d{2}(?:\.\d{1,3})?>/g, '')
  11564. .trim();
  11565. if (pureLine.length > 0) {
  11566. result.push(pureLine);
  11567. }
  11568. }
  11569. return result;
  11570. }
  11571. private openLyricCopySheet(): void {
  11572. const lines = this.extractLyricCopyLines(this.lyricContent);
  11573. if (ArrayUtil.isEmpty(lines)) {
  11574. ToastUtil.showToast('暂无可复制歌词');
  11575. return;
  11576. }
  11577. this.lyricCopyLines = lines;
  11578. this.lyricSelectedIndexes = [];
  11579. this.isShowLyricCopySheet = true;
  11580. }
  11581. private toggleLyricLineSelection(index: number): void {
  11582. const selectedIndex = this.lyricSelectedIndexes.indexOf(index);
  11583. if (selectedIndex >= 0) {
  11584. const nextSelectedIndexes = [...this.lyricSelectedIndexes];
  11585. nextSelectedIndexes.splice(selectedIndex, 1);
  11586. this.lyricSelectedIndexes = nextSelectedIndexes;
  11587. return;
  11588. }
  11589. this.lyricSelectedIndexes = [...this.lyricSelectedIndexes, index];
  11590. }
  11591. private toggleLyricSelectAll(): void {
  11592. if (this.lyricSelectedIndexes.length === this.lyricCopyLines.length) {
  11593. this.lyricSelectedIndexes = [];
  11594. return;
  11595. }
  11596. this.lyricSelectedIndexes = this.lyricCopyLines.map((_: string, index: number) => index);
  11597. }
  11598. private copySelectedLyricLines(): void {
  11599. const selectedLines = this.getSelectedLyricLines();
  11600. if (ArrayUtil.isEmpty(selectedLines)) {
  11601. ToastUtil.showToast('暂无可复制歌词');
  11602. return;
  11603. }
  11604. Utility.copyText(selectedLines.join('\n'));
  11605. ToastUtil.showToast(`已复制${selectedLines.length}行歌词`);
  11606. }
  11607. private getSelectedLyricLines(): string[] {
  11608. if (ArrayUtil.isEmpty(this.lyricSelectedIndexes)) {
  11609. return [];
  11610. }
  11611. const selectedIndexes = [...this.lyricSelectedIndexes].sort((a: number, b: number) => a - b);
  11612. const selectedLines: string[] = [];
  11613. for (let i = 0; i < selectedIndexes.length; i++) {
  11614. const index = selectedIndexes[i];
  11615. if (index >= 0 && index < this.lyricCopyLines.length) {
  11616. selectedLines.push(this.lyricCopyLines[index]);
  11617. }
  11618. }
  11619. return selectedLines;
  11620. }
  11621. private shareSelectedLyricLines(): void {
  11622. const selectedLines = this.getSelectedLyricLines();
  11623. if (ArrayUtil.isEmpty(selectedLines)) {
  11624. ToastUtil.showToast('暂无可分享歌词');
  11625. return;
  11626. }
  11627. const shareTitle = `${this.currentSong?.name ?? '歌词'}歌词`;
  11628. Utility.doShareText(selectedLines.join('\n'), this.context, shareTitle, '分享歌词');
  11629. }
  11630. /**
  11631. * 从在线API获取歌词
  11632. */
  11633. private fetchOnlineLyric(lyricPath: string, isOnLineAndToast: boolean, isApi2?: boolean): void {
  11634. if (!this.currentSong) {
  11635. this.clearLyricControllers();
  11636. if (isOnLineAndToast) {
  11637. ToastUtil.showShort('未获取到歌词!');
  11638. }
  11639. return;
  11640. }
  11641. let artist = this.currentSong.artist || '';
  11642. if (isApi2 === undefined) {
  11643. isApi2 = false;
  11644. }
  11645. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  11646. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  11647. this.setLyricToControllers(res, lyricPath);
  11648. } else {
  11649. this.clearLyricControllers();
  11650. if (isOnLineAndToast) {
  11651. ToastUtil.showShort('未获取到歌词!');
  11652. }
  11653. }
  11654. });
  11655. }
  11656. //初始化悬浮歌词的自定义设置
  11657. initPipLyricSetting() {
  11658. this.lyricControllerXF
  11659. .setTextSize(this.currentLyricSize)
  11660. .setCacheSize(4)
  11661. .setTextColor("#DDDDDD")
  11662. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  11663. .setEmptyHint("")
  11664. .setAnimationDuration(1000)
  11665. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  11666. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  11667. this.setBlurDegree(this.blurDegreePip, true)
  11668. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  11669. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  11670. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  11671. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  11672. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  11673. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  11674. this.lyricControllerXF.setHightLightCenter(true)
  11675. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  11676. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  11677. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  11678. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  11679. if (this.pipBgIndex === 0) {
  11680. if (this.cover) {
  11681. this.pipBg = this.cover
  11682. } else {
  11683. this.pipBg = this.imageColor
  11684. }
  11685. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  11686. }
  11687. }
  11688. //根据item返回歌词内容
  11689. async getLyricContent(item: VideoItem): Promise<string> {
  11690. let neiqianLrc = ''
  11691. let lyContent = item?.lyricContent
  11692. if(lyContent&&StrUtil.isNotEmpty(lyContent)){
  11693. neiqianLrc = lyContent
  11694. return neiqianLrc
  11695. }
  11696. try {
  11697. //取数据库里面的歌词lyContent
  11698. const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
  11699. if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
  11700. console.log("onecold Lyrics:", lyricContent);
  11701. neiqianLrc = lyricContent
  11702. return neiqianLrc
  11703. }
  11704. } catch (error) {
  11705. console.error("Error fetching lyrics:", error);
  11706. }
  11707. try {
  11708. let filePath = item.filePath;
  11709. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  11710. let realLyricPath = lyricPath;
  11711. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  11712. const stat = await fileIo.stat(file.fd);
  11713. const arrayBuffer = new ArrayBuffer(stat.size);
  11714. const readLen = await fs.read(file.fd, arrayBuffer);
  11715. console.info("read file data succeed");
  11716. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  11717. if (buf.length === 0) {
  11718. throw new Error("Buffer is empty after reading the file");
  11719. }
  11720. // let detectedEncoding = chardet.detect(buf);
  11721. let detectedEncoding = this.detect(arrayBuffer)
  11722. console.info("Detected encoding: " + detectedEncoding);
  11723. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  11724. let fileContent = textDecoder.decode(buf);
  11725. console.info(`onecold The content of file1: ${fileContent}`);
  11726. fs.closeSync(file);
  11727. return fileContent;
  11728. } catch (error) {
  11729. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  11730. return '';
  11731. }
  11732. }
  11733. async saveDataToFile(content: string, filePath: string) {
  11734. if (StrUtil.isEmpty(filePath)) {
  11735. return
  11736. }
  11737. try {
  11738. let lyricContent = ''
  11739. lyricContent = content
  11740. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  11741. // 清空文件内容
  11742. await fileIo.truncate(file.fd, 0);
  11743. await fileIo.write(file.fd, lyricContent);
  11744. await fileIo.close(file);
  11745. console.log('onecold lyric file Data saved successfully.');
  11746. } catch (error) {
  11747. console.error('onecold lyric file Failed to save data:', error);
  11748. }
  11749. }
  11750. // 定义开始旋转的方法
  11751. // 使用动画系统优化旋转性能,避免 setInterval 频繁更新导致卡顿
  11752. @State timer: number = 0
  11753. @State rotateAngle: number = 0
  11754. @State isRotationRunning: boolean = false // 旋转动画是否正在运行
  11755. @StorageProp('isPageVisible') @Watch('onPageVisibilityChange') isPageVisible: boolean = true // 页面可见性标志
  11756. // 页面可见性变化回调
  11757. onPageVisibilityChange() {
  11758. // 当页面可见性改变时,重新启动/停止旋转动画
  11759. this.animationRoFun()
  11760. }
  11761. //封面旋转动画
  11762. animationRoFun() {
  11763. if (this.isPlaying && !this.isCoverRectangle && this.isPageVisible) {
  11764. // 启动旋转动画
  11765. if (!this.isRotationRunning) {
  11766. this.isRotationRunning = true
  11767. this.startContinuousRotation()
  11768. }
  11769. this.startRotation()
  11770. } else {
  11771. // 停止旋转动画
  11772. this.isRotationRunning = false
  11773. clearInterval(this.timer)
  11774. this.stopRotation()
  11775. }
  11776. }
  11777. // 使用持续的动画进行旋转,避免频繁状态更新
  11778. private startContinuousRotation() {
  11779. clearInterval(this.timer)
  11780. // 改为每 1000ms 更新 36 度(10秒一圈),减少更新频率
  11781. // 不使用 % 360 取模,让角度持续累加,避免反转
  11782. this.timer = setInterval(() => {
  11783. if (this.isRotationRunning) {
  11784. this.rotateAngle = this.rotateAngle + 36
  11785. }
  11786. }, 1000)
  11787. }
  11788. // 定义开始旋转的方法
  11789. startRotation() {
  11790. if (this.isPlaying) {
  11791. animateTo({
  11792. duration: 777,
  11793. iterations: 1,
  11794. curve: Curve.Linear
  11795. }, () => {
  11796. this.rotateAngle2 = -9
  11797. })
  11798. }
  11799. }
  11800. // 回调,暂停和播放按钮回调,下一首和上一首
  11801. playChange() {
  11802. // if(this.isCoverRectangle){
  11803. // return
  11804. // }
  11805. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  11806. this.setIsPlaying(true)
  11807. this.animationState = AnimationStatus.Running
  11808. } else {
  11809. this.setIsPlaying(false)
  11810. this.animationState = AnimationStatus.Paused
  11811. }
  11812. AppStorage.setOrCreate('animationState', this.animationState);
  11813. }
  11814. // 定义停止旋转的方法
  11815. stopRotation() {
  11816. if (this.isCoverRectangle) {
  11817. this.rotateAngle = 0
  11818. } else {
  11819. //唱针以左上角为点选择逆时针40度
  11820. animateTo({
  11821. duration: 1000,
  11822. curve: Curve.Linear,
  11823. iterations: 1,
  11824. }, () => {
  11825. this.rotateAngle2 = -45;
  11826. });
  11827. }
  11828. }
  11829. @Builder
  11830. private LyricsTopItem() {
  11831. Row() {
  11832. Stack({ alignContent: Alignment.Center }) {
  11833. Image( StrUtil.isNotEmpty(this.cover)?
  11834. this.cover:$r('app.media.alt'))
  11835. .height(58)
  11836. .width(58)
  11837. .clip(true)
  11838. .sourceSize({width:38, height:38})
  11839. .alt($r('app.media.alt'))
  11840. .borderRadius(8)
  11841. .clickEffect({ level: ClickEffectLevel.HEAVY })
  11842. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  11843. .shadow({
  11844. radius: 22,
  11845. type: ShadowType.BLUR,
  11846. color: 'on_primary'
  11847. })
  11848. }
  11849. .width(62)
  11850. .height('100%')
  11851. Column() {
  11852. Column() {
  11853. Text(this.name)
  11854. .fontSize(16)
  11855. .maxLines(1)
  11856. .fontWeight(FontWeight.Bolder)
  11857. .fontColor(Color.White)
  11858. .textOverflow({ overflow: TextOverflow.Ellipsis })
  11859. .margin({ left: 10 })
  11860. Row() {
  11861. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  11862. .fontSize(13)
  11863. .fontWeight(FontWeight.Bolder)
  11864. .padding({ top: 8 })
  11865. .fontColor(Color.White)
  11866. .margin({ left: 10 })
  11867. Blank()
  11868. }
  11869. }
  11870. .height('100%')
  11871. .width('100%')
  11872. .justifyContent(FlexAlign.Center)
  11873. .alignItems(HorizontalAlign.Start)
  11874. }
  11875. .height('100%')
  11876. .layoutWeight(1)
  11877. .margin({ right: 8 })
  11878. Column() {
  11879. PointLightDefaultButton({
  11880. isSysBol:false,
  11881. pointColor:Color.White,
  11882. imageResource:$r('app.media.lyric'),
  11883. isPx: false,
  11884. builderHeight: 23,
  11885. builderWidth: 23,
  11886. })
  11887. .onClick(() => {
  11888. this.isLyricSetting = !this.isLyricSetting;
  11889. })
  11890. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  11891. height: '99%',
  11892. dragBar: true,
  11893. preferType: SheetType.CENTER,
  11894. showClose: true,
  11895. blurStyle: BlurStyle.Thin,
  11896. backgroundColor: Color.Transparent,
  11897. title: { title: $r('app.string.lyric_setting') }
  11898. })
  11899. }
  11900. .width(44)
  11901. .height('100%')
  11902. .justifyContent(FlexAlign.Center)
  11903. .alignItems(HorizontalAlign.End)
  11904. }
  11905. .width(this.currentLyricAlignModePip === 1?'98%':'90%%')
  11906. .padding({ left: 28, right: 28 })
  11907. .height(58)
  11908. .alignItems(VerticalAlign.Center)
  11909. }
  11910. //歌词显示
  11911. @Builder
  11912. PlayerLyrics() {
  11913. Column() {
  11914. Column() {
  11915. this.LyricsTopItem()
  11916. }
  11917. .height(this.isPuraWP() ? 15 : 58)
  11918. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  11919. Visibility.None : Visibility.Visible)
  11920. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  11921. .width("100%")
  11922. Column() {
  11923. LyricView2({
  11924. controller: this.lyricController,
  11925. enableSeek: true,
  11926. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  11927. seekLineColor: "#80ffffff", // 滑动定位线颜色
  11928. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  11929. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  11930. if (!this.isPlaying) {
  11931. console.info('onecold startPlayOrResumePlay 7527')
  11932. this.startPlayOrResumePlay()
  11933. }
  11934. else {
  11935. this.isSeekTo = true;
  11936. this.mDestroyPage = false;
  11937. // 只有播放网盘歌曲时才显示转圈圈
  11938. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  11939. this.showLoadIng();
  11940. }
  11941. this.seekTo(position + "");
  11942. }
  11943. return true
  11944. }
  11945. })
  11946. .width("100%")
  11947. .layoutWeight(1)
  11948. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  11949. .gesture(LongPressGesture()
  11950. .onAction(() => {
  11951. this.openLyricCopySheet();
  11952. }))
  11953. .bindSheet($$this.isShowLyricCopySheet, this.LyricCopySheetBuilder(), {
  11954. height: '99%',
  11955. dragBar: true,
  11956. showClose: true,
  11957. preferType: SheetType.CENTER,
  11958. blurStyle: BlurStyle.Thin,
  11959. title: { title: '歌词' }
  11960. })
  11961. if (this.isPhoneLan()) {
  11962. Column() {
  11963. if (this.isShowSpectrum) {
  11964. this.InlineSpectrumView()
  11965. }
  11966. this.playProgressView()
  11967. }
  11968. .margin({ bottom: 32, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  11969. }
  11970. }
  11971. .position({
  11972. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  11973. (this.isPuraWP() ? 58 : 99)
  11974. })
  11975. .justifyContent(FlexAlign.Center)
  11976. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  11977. }
  11978. }
  11979. @Builder
  11980. LyricCopySheetBuilder() {
  11981. LyricCopySheet({
  11982. lyricCopyLines: this.lyricCopyLines,
  11983. lyricSelectedIndexes: this.lyricSelectedIndexes,
  11984. isDarkMode: this.isDarkMode,
  11985. themeColor: this.themeColor,
  11986. bottomSafeHeight: this.bottomSafeHeight,
  11987. onToggleLyricLine: (index: number) => {
  11988. this.toggleLyricLineSelection(index);
  11989. },
  11990. onToggleSelectAll: () => {
  11991. this.toggleLyricSelectAll();
  11992. },
  11993. onCopySelectedLines: () => {
  11994. this.copySelectedLyricLines();
  11995. },
  11996. onShareSelectedLines: () => {
  11997. this.shareSelectedLyricLines();
  11998. }
  11999. })
  12000. }
  12001. @Builder
  12002. SingleLyricView() {
  12003. Column() {
  12004. Column() {
  12005. LyricView2({
  12006. controller: this.lyricControllerSingle,
  12007. enableSeek: false,
  12008. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  12009. seekLineColor: "#80ffffff", // 滑动定位线颜色
  12010. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  12011. })
  12012. .gesture(LongPressGesture()
  12013. .onAction(() => {
  12014. this.openLyricCopySheet();
  12015. }))
  12016. }
  12017. .height(82)
  12018. .margin({ bottom: 20 })
  12019. }
  12020. .opacity(this.playDragUiOpacity)
  12021. }
  12022. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  12023. @Builder
  12024. BottomControl() {
  12025. Column() {
  12026. if (this.isShowSpectrum) {
  12027. this.InlineSpectrumView()
  12028. }
  12029. this.TopPlayProgressView()
  12030. //播放 暂停,下一首,上一首
  12031. this.playCenterView()
  12032. if(!this.curDisplayIsHiCar){
  12033. //播放进度条
  12034. this.BottomView()
  12035. }
  12036. }
  12037. .justifyContent(FlexAlign.Center)
  12038. .alignItems(HorizontalAlign.Center)
  12039. .opacity(this.playDragUiOpacity)
  12040. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  12041. }
  12042. @Builder
  12043. playMenuBuilder(){
  12044. Image($r('app.media.menu'))
  12045. .width(24)
  12046. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12047. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  12048. height: '99%',
  12049. preferType:SheetType.CENTER,
  12050. dragBar: true,
  12051. showClose: true,
  12052. blurStyle: BlurStyle.Thin,
  12053. title: { title: $r('app.string.more') },
  12054. backgroundColor: Color.Transparent,
  12055. })
  12056. }
  12057. //播放控制上一首 下一首 暂停和播放
  12058. @Builder
  12059. playCenterView(){
  12060. Row() {
  12061. PointLightButton({
  12062. builder: () => {
  12063. this.playMenuBuilder()
  12064. },
  12065. isPx: false,
  12066. builderHeight: 26,
  12067. builderWidth: 26,
  12068. })
  12069. .onClick(async () =>{
  12070. this.isShowMoreView = !this.isShowMoreView;
  12071. })
  12072. PointLightButton({
  12073. builder: () => {
  12074. this.playPreviousBuilder()
  12075. },
  12076. isPx: false,
  12077. builderHeight: 26,
  12078. builderWidth: 26,
  12079. })
  12080. .onClick(async () =>{
  12081. await this.playPrevious()
  12082. })
  12083. PointLightButton({
  12084. builder: () => {
  12085. this.PlayOrPauseButton()
  12086. },
  12087. isPx: false,
  12088. builderHeight: this.isPhoneLan()?38:41,
  12089. builderWidth: this.isPhoneLan()?38:41,
  12090. })
  12091. .onClick(() =>{
  12092. this.playOrPause()
  12093. })
  12094. PointLightButton({
  12095. builder: () => {
  12096. this.playNextBuilder()
  12097. },
  12098. isPx: false,
  12099. builderHeight: 26,
  12100. builderWidth: 26,
  12101. })
  12102. .onClick(async () =>{
  12103. await this.playNext()
  12104. })
  12105. this.playModeButton()
  12106. }
  12107. .width('95%')
  12108. .margin({ bottom:this.isCoverOpacity()?0:15 })
  12109. .justifyContent(FlexAlign.SpaceEvenly)
  12110. }
  12111. @Builder
  12112. playPreviousBuilder(){
  12113. Image($r('app.media.ic_previous'))
  12114. .width(32)
  12115. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12116. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12117. }
  12118. @Builder
  12119. playNextBuilder(){
  12120. Image($r('app.media.ic_next'))
  12121. .width(32)
  12122. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12123. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12124. }
  12125. @Builder
  12126. PlayOrPauseButton(){
  12127. Stack() {
  12128. Column() {
  12129. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  12130. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  12131. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  12132. .width(this.isPhoneLan()?38:40)
  12133. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12134. .fillColor(Color.White)
  12135. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12136. }
  12137. // 加载进度圈
  12138. if (this.isPlayerLoading) {
  12139. Progress({value:0,total:100,type:ProgressType.Ring })
  12140. .width(this.isPhoneLan()?40:43)
  12141. .height(this.isPhoneLan()?40:43)
  12142. .color(Color.White)
  12143. .style({ strokeWidth: 5, status: ProgressStatus.LOADING })
  12144. }
  12145. }
  12146. .width(this.isPhoneLan()?38:41)
  12147. .height(this.isPhoneLan()?38:41)
  12148. }
  12149. @Builder
  12150. TopPlayProgressView(){
  12151. Column() {
  12152. Row(){
  12153. Stack(){
  12154. SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
  12155. .fontColor([Color.White])
  12156. .fontSize(21)
  12157. .effectStrategy(1)
  12158. Text(this.fastForwardSeconds)
  12159. .fontColor(Color.White)
  12160. .fontSize(10)
  12161. .fontWeight(FontWeight.Bold)
  12162. }
  12163. .padding({left:12,bottom:6})
  12164. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  12165. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  12166. .onClick(()=>{
  12167. this.backForward()
  12168. })
  12169. Slider({
  12170. value: this.progressValue,
  12171. min: 0,
  12172. max: this.PROGRESS_MAX_VALUE,
  12173. step: 1,
  12174. style: SliderStyle.InSet
  12175. })
  12176. .height(20)
  12177. .blockColor('rgba(255,255,255,1)')
  12178. .trackColor('rgba(255,255,255,0.3)')
  12179. .selectedColor(Color.White)
  12180. .trackThickness(4)
  12181. .showSteps(false)
  12182. .showTips(true)
  12183. .layoutWeight(1)
  12184. .enabled(this.slideEnable)
  12185. .onChange((value: number, mode: SliderChangeMode) => {
  12186. if (mode !== 2) {
  12187. return
  12188. }
  12189. if(this.isSeekTo)
  12190. return
  12191. this.isSeekTo = true;
  12192. this.mDestroyPage = false;
  12193. // 只有播放网盘歌曲时才显示转圈圈
  12194. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  12195. this.showLoadIng();
  12196. }
  12197. let seekValue = value * (this.getActiveDuration() / 100);
  12198. this.seekTo(seekValue + "", "top-progress-slider");
  12199. })
  12200. Stack(){
  12201. SymbolGlyph($r('sys.symbol.arrow_clockwise'))
  12202. .fontColor([Color.White])
  12203. .fontSize(21)
  12204. .effectStrategy(1)
  12205. Text(this.fastForwardSeconds)
  12206. .fontColor(Color.White)
  12207. .fontSize(10)
  12208. .fontWeight(FontWeight.Bold)
  12209. }
  12210. .padding({right:10,bottom:6})
  12211. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  12212. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  12213. .onClick(()=>{
  12214. this.fastForward()
  12215. })
  12216. }
  12217. .justifyContent(FlexAlign.Center)
  12218. .padding({left:20,right:20})
  12219. .width(this.isLandscape?'88%':'95%')
  12220. Row() {
  12221. Text(this.currentTime)
  12222. .fontSize(10)
  12223. .fontColor(Color.White)
  12224. .margin({left:25})
  12225. Blank()
  12226. Text(this.totalTime)
  12227. .fontSize(10)
  12228. .fontColor(Color.White)
  12229. .margin({right:25})
  12230. }
  12231. .width(this.isLandscape?'85%':'90%')
  12232. .height(10)
  12233. }
  12234. .width('100%')
  12235. .alignItems(HorizontalAlign.Center)
  12236. }
  12237. @Builder
  12238. playModeButton(){
  12239. PointLightButton({
  12240. builder: () => {
  12241. this.playModeBuilder()
  12242. },
  12243. isPx: false,
  12244. builderHeight: 26,
  12245. builderWidth: 26,
  12246. })
  12247. .onClick(async () =>{
  12248. this.setLoopMode()
  12249. })
  12250. }
  12251. @Builder
  12252. playModeBuilder(){
  12253. Column() {
  12254. if (this.playType === 0) {
  12255. Image($r('app.media.loop'))
  12256. .width(24)
  12257. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12258. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12259. } else if (this.playType === 1) {
  12260. Image($r('app.media.single'))
  12261. .width(24)
  12262. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12263. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12264. } else if (this.playType === 2) {
  12265. Image($r('app.media.normal_play'))
  12266. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12267. .width(24)
  12268. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12269. } else if (this.playType === 3) {
  12270. Image($r('app.media.random'))
  12271. .width(24)
  12272. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12273. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12274. } else if (this.playType === 4) {
  12275. Image($r('app.media.noloop'))
  12276. .width(24)
  12277. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12278. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12279. }
  12280. }
  12281. }
  12282. //播放进度条
  12283. @Builder
  12284. BottomView(){
  12285. Row() {
  12286. PointLightDefaultButton({
  12287. isSysBol:true,
  12288. pointColor:Color.White,
  12289. imageResource:$r('sys.symbol.rectangle_portrait_rotate'),
  12290. isPx: false,
  12291. builderHeight: 22,
  12292. builderWidth: 22,
  12293. })
  12294. .onClick(async () =>{
  12295. if (this.isLandscape) {
  12296. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  12297. } else {
  12298. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  12299. }
  12300. })
  12301. if(this.currentSong){
  12302. PointLightDefaultButton({
  12303. isSysBol:true,
  12304. pointColor:Color.White,
  12305. imageResource:$r('sys.symbol.rename'),
  12306. isPx: false,
  12307. builderHeight: 22,
  12308. builderWidth: 22,
  12309. })
  12310. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  12311. height: '99%',
  12312. dragBar: true,
  12313. showClose: true,
  12314. preferType: SheetType.BOTTOM,
  12315. title: { title: '编辑标签' }
  12316. })
  12317. .onClick(async () => {
  12318. this.initEditFields(this.currentSong)
  12319. this.tempLyricContent = this.lyricContent
  12320. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  12321. this.lyricConStr = this.tempLyricContent
  12322. }
  12323. this.isShowEdit = !this.isShowEdit;
  12324. })
  12325. }
  12326. PointLightDefaultButton({
  12327. isSysBol:true,
  12328. pointColor:Color.White,
  12329. imageResource:$r('sys.symbol.slider_vertical_3'),
  12330. isPx: false,
  12331. builderHeight: 22,
  12332. builderWidth: 22,
  12333. })
  12334. .onClick(async () => {
  12335. this.isEqualizerSheet = !this.isEqualizerSheet;
  12336. })
  12337. PointLightDefaultButton({
  12338. isSysBol:true,
  12339. pointColor:Color.White,
  12340. imageResource:Utility.getIsFav(this.favList,this.currentSong)?
  12341. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'),
  12342. isPx: false,
  12343. builderHeight: 22,
  12344. builderWidth: 22,
  12345. })
  12346. .onClick(async () => {
  12347. if(this.currentSong){
  12348. this.doFav(this.currentSong)
  12349. }
  12350. })
  12351. this.playListBuilder()
  12352. }
  12353. .width(this.isLandscape?'88%':'95%')
  12354. .justifyContent(FlexAlign.SpaceAround)
  12355. .visibility(this.showSimple?Visibility.None:Visibility.Visible)
  12356. .height(30)
  12357. .animation({
  12358. duration: 666,
  12359. curve: 'ease-in-out' // 可选动画曲线
  12360. })
  12361. }
  12362. @Builder
  12363. fullButton(){
  12364. Column() {
  12365. Image($r('app.media.full_4'))
  12366. .width(25)
  12367. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12368. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12369. }
  12370. }
  12371. @Builder
  12372. playListBuilder(){
  12373. PointLightDefaultButton({
  12374. isSysBol:true,
  12375. pointColor:Color.White,
  12376. imageResource:$r('sys.symbol.music_note_list'),
  12377. isPx: false,
  12378. builderHeight: 26,
  12379. builderWidth: 26,
  12380. })
  12381. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  12382. height: '95%',
  12383. dragBar: true,
  12384. showClose: true,
  12385. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  12386. blurStyle: BlurStyle.Thin,
  12387. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  12388. title: {
  12389. title:this.getPlayListDisplayCount()==0?Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  12390. :Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  12391. + `(${this.getPlayListDisplayCount()}首)`
  12392. }
  12393. })
  12394. .onClick(() => {
  12395. this.isShowSheetView = !this.isShowSheetView;
  12396. if(this.isPlayListBgGrass){
  12397. this.isFrontWhite = true
  12398. }else{
  12399. this.isFrontWhite = false
  12400. }
  12401. this.scrollIndex()
  12402. // 只有在播放本地音乐时才自动加载完整列表
  12403. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_LOCAL) {
  12404. void this.hydrateFullMediaPlayListIfNeeded();
  12405. }
  12406. })
  12407. }
  12408. //旧版本播放进度条(现在是手机横屏的播放条)
  12409. @Builder
  12410. playProgressView() {
  12411. Row() {
  12412. Column(){
  12413. PointLightDefaultButton({
  12414. isSysBol:true,
  12415. pointColor:Color.White,
  12416. imageResource:$r('sys.symbol.rectangle_portrait_rotate'),
  12417. isPx: false,
  12418. builderHeight: 26,
  12419. builderWidth: 26,
  12420. })
  12421. .onClick(async () =>{
  12422. if (this.isLandscape) {
  12423. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  12424. } else {
  12425. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  12426. }
  12427. })
  12428. }
  12429. .margin({ right: 10,bottom:6})
  12430. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  12431. .animation({
  12432. duration: 666,
  12433. curve: 'ease-in-out' // 可选动画曲线
  12434. })
  12435. Text(this.currentTime)
  12436. .fontSize($r('app.float.slider_font_size'))
  12437. .fontColor(Color.White)
  12438. .margin(3)
  12439. Slider({
  12440. value: this.progressValue,
  12441. min: 0,
  12442. max: this.PROGRESS_MAX_VALUE,
  12443. step: 1,
  12444. style: SliderStyle.InSet
  12445. })
  12446. .width('600px')
  12447. .blockColor('rgba(255,255,255,1)')
  12448. .trackColor('rgba(255,255,255,0.3)')
  12449. .selectedColor(Color.White)
  12450. .trackThickness(5)
  12451. .layoutWeight(1)
  12452. .margin({top:4, left: PlayConstants.PROGRESS_MARGIN_LEFT })
  12453. .showSteps(false)
  12454. .showTips(true)
  12455. .enabled(this.slideEnable)
  12456. .onChange((value: number, mode: SliderChangeMode) => {
  12457. if (mode !== 2) {
  12458. return
  12459. }
  12460. this.isSeekTo = true;
  12461. this.mDestroyPage = false;
  12462. // 只有播放网盘歌曲时才显示转圈圈
  12463. console.info("onecold this.currentSong.type:"+this.currentSong?.type)
  12464. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  12465. this.showLoadIng();
  12466. }
  12467. let seekValue = value * (this.getActiveDuration() / 100);
  12468. this.seekTo(seekValue + "", "landscape-progress-slider");
  12469. })
  12470. Text(this.totalTime)
  12471. .fontSize($r('app.float.slider_font_size'))
  12472. .fontColor(Color.White)
  12473. .margin(3)
  12474. //播放列表
  12475. Column(){
  12476. this.playListBuilder()
  12477. }
  12478. .margin({ left: 10,bottom:6})
  12479. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  12480. .animation({
  12481. duration: 666,
  12482. curve: 'ease-in-out' // 可选动画曲线
  12483. })
  12484. }
  12485. //x5的竖屏模式需要99%
  12486. .width(this.isPhonePortrait() ? '93.4%'
  12487. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  12488. .height(this.isPhoneLan() ? 25 : 33)
  12489. .alignItems(VerticalAlign.Bottom)
  12490. .animation({
  12491. duration: 666,
  12492. curve: 'ease-in-out' // 可选动画曲线
  12493. })
  12494. }
  12495. isBigScreen() {
  12496. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  12497. return true
  12498. }
  12499. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  12500. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  12501. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  12502. return false
  12503. } else {
  12504. return true
  12505. }
  12506. return false
  12507. }
  12508. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  12509. // 添加控制缩放的状态变量
  12510. @State scaleValueImage: number = 1
  12511. @State scaleValueText: number = 1
  12512. @State playDragUiOpacity: number = 1
  12513. @Builder
  12514. private CoverScaleGuideOverlay() {
  12515. Stack() {
  12516. Column({ space: 10 }) {
  12517. SymbolGlyph($r('sys.symbol.arrow_up_left_and_arrow_down_right'))
  12518. .fontSize(34)
  12519. .fontColor([Color.White])
  12520. Text('双指缩放封面')
  12521. .fontSize(16)
  12522. .fontWeight(FontWeight.Bold)
  12523. .fontColor(Color.White)
  12524. Text('在封面区域双指捏合,可调整封面大小')
  12525. .fontSize(12)
  12526. .fontColor(Color.White)
  12527. .opacity(0.88)
  12528. .textAlign(TextAlign.Center)
  12529. }
  12530. .padding({ left: 18, right: 18, top: 16, bottom: 16 })
  12531. .backgroundColor('#A6000000')
  12532. .borderRadius(18)
  12533. .width(this.isPhoneLan() ? 230 : 240)
  12534. }
  12535. .width('100%')
  12536. .height(this.isPhoneLan() ? 260 : 360)
  12537. .align(Alignment.Center)
  12538. .zIndex(10)
  12539. .visibility(this.isShowCoverScaleGuide ? Visibility.Visible : Visibility.None)
  12540. .onClick(() => {
  12541. this.dismissCoverScaleGuide()
  12542. })
  12543. }
  12544. @Builder
  12545. CoverInfo() {
  12546. Column() {
  12547. Stack() {
  12548. Column() {
  12549. //方形封面布局
  12550. if (this.isCoverRectangle) {
  12551. this.RectangleCoverView()
  12552. } else {
  12553. //圆形封面布局
  12554. this.CicleCoverView()
  12555. }
  12556. this.musicNameInfo(false)
  12557. if (this.isPhoneLan()) {
  12558. Text(this.name+"--"+this.artist)
  12559. .fontSize(18)
  12560. .fontWeight(FontWeight.Bold)
  12561. .margin({ top: 13 })
  12562. .textOverflow({ overflow: TextOverflow.Ellipsis })
  12563. .maxLines(1)
  12564. .width('99%')
  12565. .textAlign(TextAlign.Center)
  12566. .fontColor(Color.White)
  12567. }
  12568. }
  12569. .width('100%')
  12570. Column({ space: 8 }) {
  12571. Text(this.name)
  12572. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  12573. .fontWeight(FontWeight.Bold)
  12574. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  12575. .maxLines(1)
  12576. .width('85%')
  12577. .textAlign(TextAlign.Center)
  12578. .fontColor(Color.White)
  12579. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  12580. Text(this.artist)
  12581. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  12582. .fontColor(Color.White)
  12583. .fontWeight(FontWeight.Bold)
  12584. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  12585. }
  12586. .justifyContent(FlexAlign.Start)
  12587. .zIndex(1)
  12588. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  12589. this.CoverScaleGuideOverlay()
  12590. }
  12591. .margin({
  12592. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  12593. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  12594. top: this.isCoverOpacity() ? 0 : 20
  12595. })
  12596. if (this.isShowSingleLineLyric&&this.isPhonePortrait()) {
  12597. this.SingleLyricView()
  12598. }
  12599. if (this.isPhoneLan()) {
  12600. Column() {
  12601. this.playCenterView()
  12602. }
  12603. .position({ left: 28, bottom: 35 })
  12604. } else {
  12605. this.BottomControl()
  12606. }
  12607. }
  12608. .width(CommonConstants.FULL_PERCENT)
  12609. .clip(true)
  12610. }
  12611. //方形封面布局
  12612. @Builder
  12613. RectangleCoverView(){
  12614. Stack({alignContent:Alignment.Center}){
  12615. Image( StrUtil.isNotEmpty(this.cover)?
  12616. this.cover:$r('app.media.alt'))
  12617. .height(this.getRectangleCoverHeight())
  12618. .width(this.getRectangleCoverWidth())
  12619. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  12620. .alt($r('app.media.alt'))
  12621. .margin({ right: 8, left: 8, top: 5 })
  12622. .aspectRatio(1)
  12623. .geometryTransition('cover') // 绑定标识符
  12624. .opacity(this.opacityValueImage)
  12625. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  12626. .bindContextMenu(this.MenuImageBuilder(this.cover), ResponseType.LongPress,
  12627. {
  12628. preview: MenuPreviewMode.IMAGE,
  12629. previewAnimationOptions: { scale: [0.8, 1.0] },
  12630. })
  12631. .bindContextMenu(this.MenuImageBuilder(this.cover), ResponseType.RightClick,
  12632. {
  12633. preview: MenuPreviewMode.IMAGE,
  12634. previewAnimationOptions: { scale: [0.8, 1.0] },
  12635. })
  12636. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  12637. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  12638. .clip(true)
  12639. .rotate({
  12640. x: 0,
  12641. y: 0,
  12642. z: 1,
  12643. angle: this.rotateAngle
  12644. })
  12645. .animation({
  12646. duration: 1000, // 与 setInterval 同步
  12647. curve: Curve.Linear,
  12648. iterations: 1
  12649. })
  12650. .shadow({
  12651. radius: 22,
  12652. type: ShadowType.BLUR,
  12653. color: 'on_primary'
  12654. })
  12655. .onClick(() => {
  12656. this.isMusicBGCover = !this.isMusicBGCover
  12657. })
  12658. .gesture(PinchGesture({ fingers: 2 })
  12659. .onActionUpdate((event: GestureEvent) => {
  12660. this.updateRectangleCoverScaleByPinch(event.scale)
  12661. })
  12662. .onActionEnd(() => {
  12663. this.rectangleCoverPinchValue = this.rectangleCoverScale
  12664. PreferencesUtil.put(SettingPage.RECTANGLE_COVER_SCALE, this.rectangleCoverScale)
  12665. }))
  12666. }
  12667. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  12668. // 设置左下角为缩放中心点
  12669. centerX: '0%',
  12670. centerY: '50%' })
  12671. }
  12672. private getRectangleCoverWidth(): string | number {
  12673. if (this.isHiCar() || this.isCoverOpacity()) {
  12674. return 'auto'
  12675. }
  12676. const baseWidth = this.isBigScreen() ? 72 : this.isCoverTopBig ? 100 : 88
  12677. return `${Math.min(100, Math.max(48, baseWidth * this.rectangleCoverScale))}%`
  12678. }
  12679. private getRectangleCoverHeight(): string | number {
  12680. if (this.isHiCar()) {
  12681. return px2vp(this.windowHeight) * 0.4 * this.rectangleCoverScale
  12682. }
  12683. if (this.isCoverOpacity()) {
  12684. return px2vp(this.windowHeight) * 0.54 * this.rectangleCoverScale
  12685. }
  12686. return 'auto'
  12687. }
  12688. private updateCoverScaleByPinch(scale: number): void {
  12689. this.rectangleCoverScale = Math.min(1.4, Math.max(0.7, this.rectangleCoverPinchValue * scale))
  12690. }
  12691. private updateRectangleCoverScaleByPinch(scale: number): void {
  12692. const dampedScale = 1 + (scale - 1) * 0.45
  12693. this.rectangleCoverScale = Math.min(1.4, Math.max(0.7, this.rectangleCoverPinchValue * dampedScale))
  12694. }
  12695. private persistCoverScaleAfterPinch(): void {
  12696. this.rectangleCoverPinchValue = this.rectangleCoverScale
  12697. PreferencesUtil.put(SettingPage.RECTANGLE_COVER_SCALE, this.rectangleCoverScale)
  12698. }
  12699. @Builder
  12700. CicleCoverView() {
  12701. //圆形封面布局
  12702. Stack({alignContent:Alignment.Center}) {
  12703. Image($r('app.media.ic_music_disc'))
  12704. .width(245)
  12705. .height(245)
  12706. .margin({ right: 20, left: 20 ,top:this.isLandscape?0:50 })
  12707. .aspectRatio(1)
  12708. .opacity(this.isCoverOpacity() ? 0 : 1)
  12709. .visibility(this.isCoverOpacity() ? Visibility.None : Visibility.Visible)
  12710. .borderRadius('100%')
  12711. .align(Alignment.Center)
  12712. .clip(true)
  12713. .rotate({
  12714. angle: this.rotateAngle,
  12715. centerX: "50%",
  12716. centerY: "50%",
  12717. })
  12718. .animation({
  12719. duration: 1000, // 改为 1000ms 与 setInterval 同步
  12720. curve: Curve.Linear,
  12721. iterations: 1 // 只执行一次,下一次更新会触发新的动画
  12722. })
  12723. .shadow({
  12724. radius: 22,
  12725. type: ShadowType.BLUR,
  12726. color: 'on_primary'
  12727. })
  12728. Image( StrUtil.isNotEmpty(this.cover)?
  12729. this.cover:$r('app.media.alt'))
  12730. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
  12731. (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 168))
  12732. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  12733. .alt($r('app.media.alt'))
  12734. .margin({ right: 20, left: 20,
  12735. top:this.isCoverRectangle||this.isLandscape?0:50})
  12736. .aspectRatio(1)
  12737. .opacity(this.opacityValueImage)
  12738. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  12739. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  12740. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  12741. .align(Alignment.Center)//
  12742. .clip(true)
  12743. .shadow({
  12744. radius: 22,
  12745. type: ShadowType.BLUR,
  12746. color: 'on_primary'
  12747. })
  12748. .rotate({
  12749. x: 0,
  12750. y: 0,
  12751. z: 1,
  12752. angle: this.rotateAngle
  12753. })
  12754. .animation({
  12755. duration: 1000, // 与 setInterval 同步
  12756. curve: Curve.Linear,
  12757. iterations: 1
  12758. })
  12759. .onClick(() => {
  12760. this.isMusicBGCover = !this.isMusicBGCover
  12761. })
  12762. // 唱针以左上角为点选择逆时针40度
  12763. Image($r('app.media.ic_music_cover_hand'))
  12764. .height(130)
  12765. .margin({ bottom: 200, top: 0 })
  12766. // .position({ x: this.windowWidth/2, y: 0 })
  12767. .align(Alignment.Top)
  12768. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  12769. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  12770. .visibility(this.isHiCar()||this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  12771. }
  12772. .scale({ x: this.scaleValueImage * this.rectangleCoverScale, y: this.scaleValueImage * this.rectangleCoverScale,
  12773. centerX: '50%',
  12774. centerY: '50%' })
  12775. .priorityGesture(PinchGesture({ fingers: 2 })
  12776. .onActionStart(() => {
  12777. this.rectangleCoverPinchValue = this.rectangleCoverScale
  12778. })
  12779. .onActionUpdate((event: GestureEvent) => {
  12780. this.updateCoverScaleByPinch(event.scale)
  12781. })
  12782. .onActionEnd(() => {
  12783. this.persistCoverScaleAfterPinch()
  12784. }))
  12785. }
  12786. @Builder
  12787. MenuImageBuilder(cover: string|undefined) {
  12788. Menu(){
  12789. MenuItem({
  12790. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.picture_2')),
  12791. content: '查看封面'
  12792. })
  12793. .onClick(async() => {
  12794. if (StrUtil.isEmpty(cover)) {
  12795. ToastUtil.showToast('当前没有可用封面')
  12796. return;
  12797. }
  12798. this.getUIContext().getRouter().pushUrl({
  12799. url: 'pages/WallpaperPreviewPage',
  12800. params: {
  12801. imageUri: cover
  12802. }
  12803. })
  12804. })
  12805. MenuItem({
  12806. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.picture')),
  12807. content: '更换封面'
  12808. })
  12809. .onClick(async() => {
  12810. await this.replaceCurrentSongCoverByAlbum();
  12811. })
  12812. }
  12813. }
  12814. @Builder
  12815. private musicNameInfo(isHidden: boolean) {
  12816. Row(){
  12817. Column({ space: 8 }) {
  12818. Text(this.name)
  12819. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 20)
  12820. .fontWeight(FontWeight.Bold)
  12821. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  12822. .maxLines(1)
  12823. .width('99%')
  12824. .textAlign(TextAlign.Start)
  12825. .fontColor(Color.White)
  12826. Text(this.artist + ' ' + this.currentSong?.album)
  12827. .fontSize(this.isCoverOpacity() ? 12 : 15)
  12828. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  12829. .fontColor(Color.White)
  12830. .textAlign(TextAlign.Start)
  12831. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  12832. .width('99%')
  12833. .maxLines(1)
  12834. }
  12835. .zIndex(1)
  12836. .layoutWeight(1)
  12837. .margin({ left: 15 })
  12838. Blank()
  12839. Row(){
  12840. PointLightDefaultButton({
  12841. isSysBol:true,
  12842. pointColor:Color.White,
  12843. imageResource:this.showSimple?
  12844. $r('sys.symbol.sun_max'):$r('sys.symbol.moon'),
  12845. isPx: false,
  12846. builderHeight: 26,
  12847. builderWidth: 26,
  12848. })
  12849. .onClick(async () => {
  12850. this.showSimple = !this.showSimple
  12851. PreferencesUtil.put('showSimple', this.showSimple)
  12852. })
  12853. }
  12854. .margin({ left: 8,right:8 })
  12855. }
  12856. .width(this.isLandscape?'83%':'90%')
  12857. .scale({ x: this.scaleValueText, y: this.scaleValueText }) // 添加缩放效果
  12858. .opacity(this.playDragUiOpacity)
  12859. .margin({ top:this.isCoverRectangle?10: 0 })
  12860. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  12861. }
  12862. @Builder
  12863. private PlayTitle() {
  12864. Row() {
  12865. Row() {
  12866. Image($r('app.media.ic_back_down'))
  12867. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  12868. .hitTestBehavior(HitTestMode.Transparent)
  12869. }
  12870. .width('100%')
  12871. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  12872. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  12873. .onClick(() => {
  12874. this.setShowPlayFalse()
  12875. })
  12876. Column() {
  12877. AVCastPicker({
  12878. normalColor: Color.White,
  12879. onStateChange: this.onStateVastChange
  12880. })
  12881. .width(24)
  12882. .height(24)
  12883. }
  12884. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  12885. }
  12886. .width(PlayConstants.ROW_WIDTH)
  12887. }
  12888. @Builder
  12889. lyricSettingSheet(isPip: boolean) {
  12890. Scroll() {
  12891. this.lyricSetting(isPip)
  12892. }
  12893. .width('100%')
  12894. .height('100%')
  12895. }
  12896. @Builder
  12897. lyricSetting(isPip: boolean) {
  12898. Column() {
  12899. // 时间调节模块
  12900. if (!isPip) {
  12901. this.BuildTimeControls()
  12902. }
  12903. // 字号控制模块
  12904. this.BuildFontControls(isPip)
  12905. }
  12906. }
  12907. // 歌词时间偏移状态
  12908. @State timeOffset: number = 0.0
  12909. @State currentLyricColor: string = '#FFFFFF'
  12910. @State currentLyricColorPip: string = '#FFFFFF'
  12911. @State currentHighLightLyricColor: string = '#FF4081'
  12912. @State currentHighLightLyricColorPip: string = '#FF4081'
  12913. // 歌词字号状态
  12914. @State currentLyricSize: number = 20
  12915. @State currentLyricSizePip: number = 20
  12916. // 高亮歌词放大倍数
  12917. @State currentHightLyricSize: number = 1.2
  12918. @State currentHightLyricSizePip: number = 1.2
  12919. @State currentLyricLineSpace: number = 10
  12920. @State currentLyricLineSpacePip: number = 10
  12921. @State currentLyricAlignMode: number = 1
  12922. @State currentLyricAlignModePip: number = 1
  12923. @State blurDegree: number = 2
  12924. @State blurDegreePip: number = 2
  12925. @State isShowSelectColor: boolean = false
  12926. @State isShowHLSelectColor: boolean = false
  12927. @State isShowPipBgSelectColor: boolean = false
  12928. @State pipLyWidth: number = 330
  12929. @State pipLyHeight: number = 120
  12930. // 构建颜色选择器
  12931. @Builder
  12932. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  12933. Row({ space: 10 }) {
  12934. HSBColorPicker({
  12935. color: '#FFFFFF',
  12936. radius: 8,
  12937. layout: HSBColorPickerLayout.COLUMN,
  12938. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  12939. '#fa7105'],
  12940. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  12941. this.changeLyricColor(value, isPip, isBGPip)
  12942. })
  12943. .height(250)
  12944. .layoutWeight(1)
  12945. .padding(25)
  12946. }
  12947. .width('66%')
  12948. }
  12949. @State isOpenPip: boolean = false
  12950. @State pipBgIndex: number = 0
  12951. // 构建字号控制器
  12952. @Builder
  12953. BuildFontControls(isPip: boolean) {
  12954. Column() {
  12955. if (isPip) {
  12956. Column() {
  12957. Row() {
  12958. Text('悬浮歌词')
  12959. .margin({ left: 18 })
  12960. .fontSize(15)
  12961. .fontColor(Color.White)
  12962. .fontWeight(480)
  12963. .layoutWeight(1)
  12964. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  12965. .selectedColor(this.themeColor)
  12966. .switchPointColor(Color.White)
  12967. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  12968. .margin({ right: 18 })
  12969. .onChange((checked: boolean) => {
  12970. this.isOpenPip = checked;
  12971. if (this.isOpenPip) {
  12972. this.startPip()
  12973. } else {
  12974. this.stopPip()
  12975. }
  12976. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  12977. })
  12978. .width(50)
  12979. .height(30);
  12980. }
  12981. .height(55)
  12982. }
  12983. .backgroundColor(Color.Transparent)
  12984. .borderRadius(15)
  12985. .margin({
  12986. left: 30,
  12987. right: 30,
  12988. top: 0,
  12989. bottom: 20
  12990. })
  12991. .padding(0)
  12992. .border({
  12993. color: Color.White,
  12994. width: 1.8
  12995. })
  12996. }else{
  12997. Row() {
  12998. Row() {
  12999. Text(`迷你歌词:`)
  13000. .fontSize(14)
  13001. .fontColor(Color.White)
  13002. .width(88)
  13003. Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
  13004. .selectedColor(this.themeColor)
  13005. .switchPointColor(Color.White)
  13006. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13007. .onChange((checked: boolean) => {
  13008. this.isShowSingleLineLyric = checked;
  13009. PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
  13010. })
  13011. .width(50)
  13012. .height(30)
  13013. .alignSelf(ItemAlign.Start)
  13014. .margin({ left: 12 })
  13015. Blank()
  13016. }
  13017. .layoutWeight(1)
  13018. Row() {
  13019. Text(`逐字歌词:`)
  13020. .fontSize(14)
  13021. .fontColor(Color.White)
  13022. .width(88)
  13023. Toggle({ type: ToggleType.Switch, isOn: this.isEnableWordByWordLyric })
  13024. .selectedColor(this.themeColor)
  13025. .switchPointColor(Color.White)
  13026. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13027. .onChange((checked: boolean) => {
  13028. this.isEnableWordByWordLyric = checked;
  13029. PreferencesUtil.putSync(SettingPage.IS_ENABLE_WORD_BY_WORD_LYRIC, this.isEnableWordByWordLyric)
  13030. this.syncWordByWordLyricMode()
  13031. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  13032. })
  13033. .width(50)
  13034. .height(30)
  13035. .alignSelf(ItemAlign.Start)
  13036. .margin({ left: 12 })
  13037. Blank()
  13038. }
  13039. .layoutWeight(1)
  13040. }
  13041. .width('100%')
  13042. .margin({
  13043. left: 20,
  13044. right: 15,
  13045. top: 10,
  13046. bottom: 10
  13047. })
  13048. }
  13049. if (!isPip) {
  13050. Row() {
  13051. Row() {
  13052. Text(`歌词发光:`)
  13053. .fontSize(14)
  13054. .fontColor(Color.White)
  13055. .width(88)
  13056. Toggle({ type: ToggleType.Switch, isOn: this.isLightText })
  13057. .selectedColor(this.themeColor)
  13058. .switchPointColor(Color.White)
  13059. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13060. .onChange((checked: boolean) => {
  13061. this.isLightText = checked;
  13062. PreferencesUtil.putSync(SettingPage.IS_LIGHT_TEXT, this.isLightText)
  13063. this.syncLyricLightTextMode()
  13064. })
  13065. .width(50)
  13066. .height(30)
  13067. .alignSelf(ItemAlign.Start)
  13068. .margin({ left: 12 })
  13069. Blank()
  13070. }
  13071. .layoutWeight(1)
  13072. Row() {
  13073. Text(`高亮居中:`)
  13074. .fontSize(14)
  13075. .fontColor(Color.White)
  13076. .width(88)
  13077. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  13078. .selectedColor(this.themeColor)
  13079. .switchPointColor(Color.White)
  13080. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13081. .onChange((checked: boolean) => {
  13082. this.isHightLightCenter = checked;
  13083. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  13084. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  13085. })
  13086. .width(50)
  13087. .height(30)
  13088. .alignSelf(ItemAlign.Start)
  13089. .margin({ left: 12 })
  13090. Blank()
  13091. }
  13092. .layoutWeight(1)
  13093. }
  13094. .width('100%')
  13095. .margin({
  13096. left: 20,
  13097. right: 15,
  13098. top: 10,
  13099. bottom: 10
  13100. })
  13101. }
  13102. Row() {
  13103. Text(`歌词居中:`)
  13104. .fontSize(14)
  13105. .fontColor(Color.White)
  13106. Row() {
  13107. ForEach(['居中', '居左'], (size: string, index: number) => {
  13108. Button(size)
  13109. .width(60)
  13110. .height(28)
  13111. .fontSize(12)
  13112. .fontColor('#FFFFFF')
  13113. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  13114. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  13115. .border({
  13116. color: (!isPip && this.currentLyricAlignMode === index) ||
  13117. (isPip && this.currentLyricAlignModePip === index) ?
  13118. '#007DFF' : '#DDDDDD',
  13119. width: 1.8
  13120. })
  13121. .onClick(() => {
  13122. this.setLyricAlignMode(index, isPip)
  13123. })
  13124. .margin({ left: 10, right: 8 })
  13125. })
  13126. }
  13127. .layoutWeight(1)
  13128. Blank()
  13129. }
  13130. .width('100%')
  13131. .margin({
  13132. top: 10,
  13133. bottom: 10,
  13134. right: 15,
  13135. left: 20
  13136. })
  13137. if (isPip) {
  13138. Row() {
  13139. Text(`悬浮背景:`)
  13140. .fontSize(14)
  13141. .fontColor(Color.White)
  13142. Select([
  13143. { value: CommonConstants.PIP_LYRIC_BG[0] },
  13144. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  13145. .font({ size: 13, weight: FontWeight.Medium })
  13146. .fontColor(Color.White)
  13147. .margin({ left: 10 })
  13148. .selected(this.pipBgIndex)
  13149. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  13150. .onSelect(async (_index: number, text?: string | undefined) => {
  13151. this.pipBgIndex = _index
  13152. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  13153. if (this.pipBgIndex === 0) {
  13154. if (this.cover) {
  13155. this.pipBg = this.cover
  13156. } else {
  13157. this.pipBg = this.imageColor
  13158. }
  13159. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  13160. } else {
  13161. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  13162. }
  13163. })
  13164. Column() {
  13165. }
  13166. .backgroundColor(this.pipBg)
  13167. .margin({ left: 10, right: 10 })
  13168. .borderRadius(20)
  13169. .height(28)
  13170. .width(28)
  13171. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13172. Row() {
  13173. SymbolGlyph($r('sys.symbol.paintbrush'))
  13174. .fontColor([Color.White])
  13175. .effectStrategy(1)
  13176. Text(`选择颜色`)
  13177. .fontSize(13)
  13178. .margin({ left: 10 })
  13179. .fontColor(Color.White)
  13180. }
  13181. }
  13182. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  13183. .backgroundColor(Color.Transparent)
  13184. .border({
  13185. color: '#FFFFFF',
  13186. radius: 20,
  13187. width: 1.8
  13188. })
  13189. .height(36)
  13190. .width(110)
  13191. .onClick(() => {
  13192. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  13193. })
  13194. .bindPopup(this.isShowPipBgSelectColor, {
  13195. builder: this.SelectColor(false, isPip, true),
  13196. placement: Placement.Top,
  13197. mask: { color: '#33000000' },
  13198. enableArrow: false, //是否显示箭头
  13199. showInSubWindow: false,
  13200. onStateChange: (e) => {
  13201. if (!e.isVisible) {
  13202. this.isShowPipBgSelectColor = false
  13203. }
  13204. }
  13205. })
  13206. }
  13207. .width('100%')
  13208. .margin({ bottom: 5, right: 15, left: 20 })
  13209. }
  13210. Row() {
  13211. Text(`歌词颜色:`)
  13212. .fontSize(14)
  13213. .fontColor(Color.White)
  13214. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  13215. .fontSize(15)
  13216. .fontColor(Color.White)
  13217. .margin({ left: 6, right: 6 })
  13218. Column() {
  13219. }
  13220. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  13221. .margin({ right: 12 })
  13222. .borderRadius(20)
  13223. .height(28)
  13224. .width(28)
  13225. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13226. Row() {
  13227. SymbolGlyph($r('sys.symbol.paintbrush'))
  13228. .fontColor([Color.White])
  13229. .effectStrategy(1)
  13230. Text(`选择颜色`)
  13231. .fontSize(13)
  13232. .margin({ left: 10 })
  13233. .fontColor(Color.White)
  13234. }
  13235. }
  13236. .backgroundColor(Color.Transparent)
  13237. .border({
  13238. color: '#FFFFFF',
  13239. radius: 20,
  13240. width: 1.8
  13241. })
  13242. .height(36)
  13243. .width(110)
  13244. .onClick(() => {
  13245. this.isShowSelectColor = !this.isShowSelectColor
  13246. })
  13247. .bindPopup(this.isShowSelectColor, {
  13248. builder: this.SelectColor(false, isPip),
  13249. placement: Placement.Top,
  13250. mask: { color: '#33000000' },
  13251. enableArrow: false, //是否显示箭头
  13252. showInSubWindow: false,
  13253. onStateChange: (e) => {
  13254. if (!e.isVisible) {
  13255. this.isShowSelectColor = false
  13256. }
  13257. }
  13258. })
  13259. }
  13260. .width('100%')
  13261. .margin({
  13262. top: 10,
  13263. bottom: 10,
  13264. right: 15,
  13265. left: 20
  13266. })
  13267. Row() {
  13268. Text(`高亮颜色:`)
  13269. .fontSize(14)
  13270. .fontColor(Color.White)
  13271. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  13272. .fontSize(15)
  13273. .fontColor(Color.White)
  13274. .margin({ left: 6, right: 6 })
  13275. Column() {
  13276. }
  13277. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  13278. .margin({ right: 12 })
  13279. .borderRadius(20)
  13280. .height(28)
  13281. .width(28)
  13282. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13283. Row() {
  13284. SymbolGlyph($r('sys.symbol.paintbrush'))
  13285. .fontColor([Color.White])
  13286. .effectStrategy(1)
  13287. Text(`选择颜色`)
  13288. .fontSize(13)
  13289. .margin({ left: 10 })
  13290. .fontColor(Color.White)
  13291. }
  13292. }
  13293. .backgroundColor(Color.Transparent)
  13294. .border({
  13295. color: '#FFFFFF',
  13296. radius: 20,
  13297. width: 1.8
  13298. })
  13299. .height(36)
  13300. .width(110)
  13301. .onClick(() => {
  13302. this.isShowHLSelectColor = !this.isShowHLSelectColor
  13303. })
  13304. .bindPopup(this.isShowHLSelectColor, {
  13305. builder: this.SelectColor(true, isPip),
  13306. placement: Placement.Top,
  13307. mask: { color: '#33000000' },
  13308. enableArrow: false, //是否显示箭头
  13309. showInSubWindow: false,
  13310. onStateChange: (e) => {
  13311. if (!e.isVisible) {
  13312. this.isShowHLSelectColor = false
  13313. }
  13314. }
  13315. })
  13316. }
  13317. .width('100%')
  13318. .margin({
  13319. top: 10,
  13320. bottom: 10,
  13321. right: 15,
  13322. left: 20
  13323. })
  13324. if (isPip) {
  13325. Row() {
  13326. Text(`显示宽度:`)
  13327. .fontSize(14)
  13328. .fontColor(Color.White)
  13329. Slider({
  13330. value: this.pipLyWidth,
  13331. min: 10,
  13332. max: 800,
  13333. step: 1,
  13334. style: SliderStyle.OutSet
  13335. })
  13336. .blockColor(this.themeColor)
  13337. .trackColor($r('app.color.speed_text_color'))
  13338. .selectedColor(Color.White)
  13339. .trackThickness(6)
  13340. .onChange((value: number) => {
  13341. this.pipLyWidth = value
  13342. if (this.pipController) {
  13343. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  13344. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  13345. }
  13346. })
  13347. .layoutWeight(1)
  13348. }
  13349. .justifyContent(FlexAlign.Start)
  13350. .margin({
  13351. left: 20,
  13352. right: 15,
  13353. top: 5,
  13354. bottom: 5
  13355. })
  13356. Row() {
  13357. Text(`显示高度:`)
  13358. .fontSize(14)
  13359. .fontColor(Color.White)
  13360. Slider({
  13361. value: this.pipLyHeight,
  13362. min: 10,
  13363. max: 1000,
  13364. step: 1,
  13365. style: SliderStyle.OutSet
  13366. })
  13367. .blockColor(this.themeColor)
  13368. .trackColor($r('app.color.speed_text_color'))
  13369. .selectedColor(Color.White)
  13370. .trackThickness(6)
  13371. .onChange((value: number) => {
  13372. this.pipLyHeight = value
  13373. if (this.pipController) {
  13374. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  13375. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  13376. }
  13377. })
  13378. .layoutWeight(1)
  13379. }
  13380. .justifyContent(FlexAlign.Start)
  13381. .margin({
  13382. left: 20,
  13383. right: 15,
  13384. top: 5,
  13385. bottom: 5
  13386. })
  13387. }
  13388. Row() {
  13389. Text(`歌词字号:`)
  13390. .fontSize(14)
  13391. .fontColor(Color.White)
  13392. Slider({
  13393. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  13394. min: 12,
  13395. max: 30,
  13396. step: 0.1,
  13397. style: SliderStyle.OutSet
  13398. })
  13399. .blockColor(this.themeColor)
  13400. .trackColor($r('app.color.speed_text_color'))
  13401. .selectedColor(Color.White)
  13402. .trackThickness(6)
  13403. .onChange((value: number) => {
  13404. this.setLyricTextSize(value, isPip)
  13405. })
  13406. .layoutWeight(1)
  13407. .margin({ right: 3 })
  13408. Text(this.getLyricSizeDisplayValue(isPip))
  13409. .fontSize(13)
  13410. .fontColor(Color.White)
  13411. .textAlign(TextAlign.Start)
  13412. }
  13413. .width('100%')
  13414. .margin({
  13415. left: 20,
  13416. right: 15,
  13417. top: 5,
  13418. bottom: 5
  13419. })
  13420. Row() {
  13421. Text(`高亮倍数:`)
  13422. .fontSize(14)
  13423. .fontColor(Color.White)
  13424. Slider({
  13425. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  13426. min: 1,
  13427. max: 2,
  13428. step: 0.1,
  13429. style: SliderStyle.OutSet
  13430. })
  13431. .blockColor(this.themeColor)
  13432. .trackColor($r('app.color.speed_text_color'))
  13433. .selectedColor(Color.White)
  13434. .trackThickness(6)
  13435. .onChange((value: number) => {
  13436. this.setHighLyricTextSize(value, isPip)
  13437. })
  13438. .layoutWeight(1)
  13439. .margin({ right: 3 })
  13440. Text(this.getHighLyricSizeDisplayValue(isPip))
  13441. .fontSize(13)
  13442. .fontColor(Color.White)
  13443. .textAlign(TextAlign.Start)
  13444. }
  13445. .width('100%')
  13446. .margin({
  13447. left: 20,
  13448. right: 15,
  13449. top: 5,
  13450. bottom: 5
  13451. })
  13452. Row() {
  13453. Text(`歌词间隙:`)
  13454. .fontSize(14)
  13455. .fontColor(Color.White)
  13456. Slider({
  13457. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  13458. min: 0,
  13459. max: 100,
  13460. step: 1,
  13461. style: SliderStyle.OutSet
  13462. })
  13463. .blockColor(this.themeColor)
  13464. .trackColor($r('app.color.speed_text_color'))
  13465. .selectedColor(Color.White)
  13466. .trackThickness(6)
  13467. .onChange((value: number) => {
  13468. this.setLyricLineSpace(value, isPip)
  13469. })
  13470. .layoutWeight(1)
  13471. .margin({ right: 3 })
  13472. Text(this.getLyricLineSpaceDisplayValue(isPip))
  13473. .fontSize(13)
  13474. .fontColor(Color.White)
  13475. .textAlign(TextAlign.Start)
  13476. }
  13477. .width('100%')
  13478. .margin({
  13479. left: 20,
  13480. right: 15,
  13481. top: 5,
  13482. bottom: 5
  13483. })
  13484. //取值间隔为100,默认为400,取值越大,字体越粗
  13485. Row() {
  13486. Text(`歌词字重:`)
  13487. .fontSize(14)
  13488. .fontColor(Color.White)
  13489. Slider({
  13490. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  13491. min: 100,
  13492. max: 900,
  13493. step: 100,
  13494. style: SliderStyle.OutSet
  13495. })
  13496. .blockColor(this.themeColor)
  13497. .trackColor($r('app.color.speed_text_color'))
  13498. .selectedColor(Color.White)
  13499. .trackThickness(6)
  13500. .onChange((value: number) => {
  13501. if (isPip) {
  13502. this.lyricTextWeightPip = value
  13503. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  13504. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  13505. } else {
  13506. this.lyricTextWeight = value
  13507. this.lyricController.setTextWeight(this.lyricTextWeight)
  13508. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  13509. }
  13510. })
  13511. .layoutWeight(1)
  13512. .margin({ right: 3 })
  13513. Text(this.getLyricTextWeightDisplayValue(isPip))
  13514. .fontSize(13)
  13515. .fontColor(Color.White)
  13516. .textAlign(TextAlign.Start)
  13517. }
  13518. .width('100%')
  13519. .margin({
  13520. left: 20,
  13521. right: 15,
  13522. top: 5,
  13523. bottom: 5
  13524. })
  13525. Row() {
  13526. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  13527. this.pushLyricButton($r('app.media.share2'), 2, '分享歌词')
  13528. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  13529. // this.pushLyricButton($r('app.media.white_search'), 1, '繁体转简体')
  13530. }
  13531. .justifyContent(FlexAlign.Center)
  13532. .margin({ top: 3, bottom: 10 })
  13533. }
  13534. .width('88%')
  13535. }
  13536. private getLyricSizeDisplayValue(isPip: boolean): string {
  13537. const lyricSize = isPip ? this.currentLyricSizePip : this.currentLyricSize;
  13538. return lyricSize.toFixed(1);
  13539. }
  13540. private getHighLyricSizeDisplayValue(isPip: boolean): string {
  13541. const highLyricSize = isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize;
  13542. return highLyricSize.toFixed(1);
  13543. }
  13544. private getLyricLineSpaceDisplayValue(isPip: boolean): string {
  13545. const lyricLineSpace = isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace;
  13546. return Math.round(lyricLineSpace).toString();
  13547. }
  13548. private getLyricTextWeightDisplayValue(isPip: boolean): string {
  13549. const lyricTextWeightValue = isPip ? this.lyricTextWeightPip : this.lyricTextWeight;
  13550. return Math.round(lyricTextWeightValue).toString();
  13551. }
  13552. private setBlurDegree(index: number, isPip: boolean) {
  13553. if (isPip) {
  13554. this.blurDegreePip = index
  13555. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  13556. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  13557. } else {
  13558. this.blurDegree = index
  13559. this.lyricController.setBlurDegree(this.blurDegree)
  13560. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  13561. }
  13562. }
  13563. private setLyricAlignMode(index: number, isPip: boolean) {
  13564. if (isPip) {
  13565. this.currentLyricAlignModePip = index
  13566. if (this.currentLyricAlignModePip === 1) {
  13567. this.lyricControllerXF.setAlignMode("left")
  13568. } else {
  13569. this.lyricControllerXF.setAlignMode("center")
  13570. }
  13571. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  13572. } else {
  13573. this.currentLyricAlignMode = index
  13574. if (this.currentLyricAlignMode === 1) {
  13575. this.lyricController.setAlignMode("left")
  13576. } else {
  13577. this.lyricController.setAlignMode("center")
  13578. }
  13579. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  13580. }
  13581. }
  13582. private setLyricTextSize(index: number, isPip: boolean) {
  13583. if (isPip) {
  13584. this.currentLyricSizePip = index
  13585. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  13586. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  13587. } else {
  13588. this.currentLyricSize = index
  13589. this.lyricController.setTextSize(this.currentLyricSize)
  13590. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  13591. }
  13592. }
  13593. private setHighLyricTextSize(scale: number, isPip: boolean) {
  13594. if (isPip) {
  13595. this.currentHightLyricSizePip = scale
  13596. this.lyricControllerXF
  13597. .setHighlightScale(this.currentHightLyricSizePip)
  13598. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  13599. } else {
  13600. this.currentHightLyricSize = scale
  13601. this.lyricController
  13602. .setHighlightScale(this.currentHightLyricSize)
  13603. PreferencesUtil.putSync('HighLyricTextSize', scale)
  13604. }
  13605. }
  13606. private setLyricLineSpace(index: number, isPip: boolean) {
  13607. if (isPip) {
  13608. this.currentLyricLineSpacePip = index
  13609. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  13610. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  13611. } else {
  13612. this.currentLyricLineSpace = index
  13613. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  13614. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  13615. }
  13616. }
  13617. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  13618. LogUtil.info('onecold isBG = ' + isBG)
  13619. if (isBG) { //如果是设置悬浮背景
  13620. this.pipBg = color
  13621. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  13622. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  13623. return
  13624. }
  13625. if (isPip) {
  13626. this.currentLyricColorPip = color
  13627. this.lyricControllerXF
  13628. .setTextColor(this.currentLyricColorPip)
  13629. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  13630. } else {
  13631. this.currentLyricColor = color
  13632. this.lyricController
  13633. .setTextColor(this.currentLyricColor)
  13634. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  13635. }
  13636. }
  13637. private changeLyricHightLightColor(color: string, isPip: boolean) {
  13638. if (isPip) {
  13639. this.currentHighLightLyricColorPip = color
  13640. this.lyricControllerXF
  13641. .setHighlightColor(this.currentHighLightLyricColorPip)
  13642. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  13643. } else {
  13644. this.currentHighLightLyricColor = color
  13645. this.lyricController
  13646. .setHighlightColor(this.currentHighLightLyricColor)
  13647. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  13648. }
  13649. }
  13650. // 构建时间控制器
  13651. @Builder
  13652. BuildTimeControls() {
  13653. Column() {
  13654. // 时间显示
  13655. Text(this.getTimeText())
  13656. .fontSize(18)
  13657. .fontColor(Color.White)
  13658. .margin({ bottom: 10 })
  13659. Row() {
  13660. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  13661. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  13662. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  13663. }
  13664. .justifyContent(FlexAlign.Center)
  13665. }
  13666. .margin({ top: 12, bottom: 8 })
  13667. }
  13668. // 精度按钮组件
  13669. @Builder
  13670. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  13671. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13672. Column() {
  13673. Image(icon)
  13674. .width(28)
  13675. .margin({ bottom: 5 })
  13676. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  13677. Text(label)
  13678. .fontSize(12)
  13679. .fontColor('#FFFFFF')
  13680. }
  13681. }
  13682. .backgroundColor(Color.Transparent)
  13683. .enabled(!this.isButtonDisabled(step))
  13684. .onClick(() => this.handlePrecisionAdjust(step))
  13685. .padding(5)
  13686. .width(66)
  13687. .height(66)
  13688. .margin({ left: 18, right: 18 })
  13689. .border({
  13690. color: '#FFFFFF',
  13691. width: 1.8
  13692. })
  13693. }
  13694. private handlePrecisionAdjust(step: number) {
  13695. if (step === 0) {
  13696. this.timeOffset = 0
  13697. this.saveLyricTimeOffset()
  13698. return
  13699. }
  13700. // 精度处理:保留1位小数
  13701. const newOffset = Number((this.timeOffset + step).toFixed(5))
  13702. // 边界保护(±15.0秒)
  13703. if (newOffset < -30.0 || newOffset > 30.0) {
  13704. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  13705. return
  13706. }
  13707. // 状态更新
  13708. this.timeOffset = newOffset
  13709. // 保存歌词时间偏移
  13710. this.saveLyricTimeOffset()
  13711. }
  13712. // 按钮禁用逻辑
  13713. private isButtonDisabled(step: number): boolean {
  13714. const futureOffset = this.timeOffset + step
  13715. return (futureOffset < -30.0) || (futureOffset > 30.0)
  13716. }
  13717. // 时间显示文本升级
  13718. private getTimeText(): string {
  13719. const absValue = Math.abs(this.timeOffset)
  13720. return this.timeOffset === 0
  13721. ? '歌词时间已重置'
  13722. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  13723. }
  13724. /**
  13725. * 获取当前歌曲的唯一标识key
  13726. * 使用歌曲的filePath作为唯一标识
  13727. */
  13728. private getLyricOffsetKey(): string {
  13729. if (this.currentSong && StrUtil.isNotEmpty(this.currentSong.filePath)) {
  13730. // 使用MD5对filePath进行加密,作为存储key
  13731. return 'lyric_offset_' + MD5.digestSync(this.currentSong.filePath)
  13732. }
  13733. return ''
  13734. }
  13735. /**
  13736. * 保存当前歌曲的歌词时间偏移
  13737. */
  13738. private saveLyricTimeOffset(): void {
  13739. try {
  13740. const key = this.getLyricOffsetKey()
  13741. if (StrUtil.isEmpty(key)) {
  13742. console.warn('heanup saveLyricTimeOffset: key is empty')
  13743. return
  13744. }
  13745. PreferencesUtil.putSync(key, this.timeOffset)
  13746. console.info('heanup saveLyricTimeOffset: key=' + key + ', offset=' + this.timeOffset)
  13747. } catch (e) {
  13748. console.error('heanup saveLyricTimeOffset error: ' + JSON.stringify(e))
  13749. }
  13750. }
  13751. /**
  13752. * 加载当前歌曲的歌词时间偏移
  13753. */
  13754. private loadLyricTimeOffset(): void {
  13755. try {
  13756. const key = this.getLyricOffsetKey()
  13757. if (StrUtil.isEmpty(key)) {
  13758. console.warn('heanup loadLyricTimeOffset: key is empty')
  13759. return
  13760. }
  13761. const savedOffset = PreferencesUtil.getNumberSync(key, 0)
  13762. if (savedOffset !== 0) {
  13763. this.timeOffset = savedOffset
  13764. console.info('heanup loadLyricTimeOffset: key=' + key + ', offset=' + savedOffset)
  13765. }else{
  13766. this.timeOffset = 0
  13767. }
  13768. } catch (e) {
  13769. console.error('heanup loadLyricTimeOffset error: ' + JSON.stringify(e))
  13770. }
  13771. }
  13772. // 导入 本地歌词 搜索歌词
  13773. @Builder
  13774. pushLyricButton(icon: Resource, step: number, label: string) {
  13775. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13776. Row() {
  13777. Image(icon)
  13778. .width(14)
  13779. .margin({ left: 13 })
  13780. Text(label)
  13781. .fontSize(12)
  13782. .margin({ left: 6 })
  13783. .fontColor('#FFFFFF')
  13784. }
  13785. }
  13786. .onClick(() => {
  13787. switch (step) {
  13788. case 0:
  13789. this.callFilePickerSelectFileForLyric()
  13790. break;
  13791. case 1:
  13792. //判断有没有设置api
  13793. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  13794. this.isLyricSetting = false
  13795. this.showTipsDialog()
  13796. return
  13797. }
  13798. if (StrUtil.isNotEmpty(this.videoUrl)) {
  13799. ToastUtil.showToast('正在获取')
  13800. this.isLyricSetting = false
  13801. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  13802. this.initLyric(lyricPath, true);
  13803. }
  13804. break;
  13805. case 2:
  13806. this.isLyricSetting = false
  13807. this.openLyricCopySheet()
  13808. break;
  13809. }
  13810. })
  13811. .padding(5)
  13812. .layoutWeight(1)
  13813. .backgroundColor(Color.Transparent)
  13814. .height(40)
  13815. .margin({ left: 4, right: 4 })
  13816. .border({
  13817. color: '#FFFFFF',
  13818. radius: 20,
  13819. width: 1.8
  13820. })
  13821. }
  13822. showVipDialog() {
  13823. DialogHelper.showCustomContentDialog({
  13824. dialogId: 'vip',
  13825. title: "友情提示",
  13826. autoCancel: false, //点击遮障层时,不关闭弹窗
  13827. backCancel: true, //点击返回键,不关闭弹窗
  13828. contentBuilder: () => {
  13829. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  13830. },
  13831. buttons: [],
  13832. })
  13833. }
  13834. //去赞助的自定义内容
  13835. @Builder
  13836. customVipBuilder(content: string) {
  13837. Column() {
  13838. Text(content)
  13839. .fontColor(Color.Gray)
  13840. .fontSize(16)
  13841. .alignSelf(ItemAlign.Start)
  13842. .margin({ bottom: 15 })
  13843. .fontSize(16)
  13844. Row() {
  13845. Button('取消')
  13846. .fontColor(Color.White)
  13847. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  13848. .height(50)
  13849. .layoutWeight(1)
  13850. .stateEffect(true)
  13851. .margin({ right: 6 })
  13852. .onClick(() => {
  13853. DialogHelper.closeDialog('vip'); //关闭弹框
  13854. })
  13855. Button('开通')
  13856. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  13857. .layoutWeight(1)
  13858. .height(50)
  13859. .backgroundColor(this.themeColor)
  13860. .stateEffect(true)
  13861. .margin({ left: 6 })
  13862. .onClick(() => {
  13863. DialogHelper.closeDialog('vip'); //关闭弹框
  13864. this.isShowPlay = false
  13865. this.mType = 1 //跳转到用户中心
  13866. // router.pushUrl({
  13867. // url: 'pages/VipPage'
  13868. // }, router.RouterMode.Single);
  13869. })
  13870. }
  13871. }
  13872. .width("100%")
  13873. .padding(10)
  13874. }
  13875. showTipsDialog() {
  13876. DialogHelper.showCustomContentDialog({
  13877. dialogId: 'tips',
  13878. title: "友情提示",
  13879. autoCancel: false, //点击遮障层时,不关闭弹窗
  13880. backCancel: true, //点击返回键,不关闭弹窗
  13881. contentBuilder: () => {
  13882. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  13883. },
  13884. buttons: [],
  13885. })
  13886. }
  13887. @Builder
  13888. customTipsBuilder(content: string) {
  13889. Column() {
  13890. Text(content)
  13891. .fontColor(Color.Gray)
  13892. .fontSize(16)
  13893. .alignSelf(ItemAlign.Start)
  13894. .margin({ bottom: 15 })
  13895. .fontSize(16)
  13896. Row() {
  13897. Button('取消')
  13898. .fontColor(Color.White)
  13899. .backgroundColor(this.themeColor)
  13900. .height(50)
  13901. .layoutWeight(1)
  13902. .stateEffect(true)
  13903. .margin({ right: 6 })
  13904. .onClick(() => {
  13905. DialogHelper.closeDialog('tips'); //关闭弹框
  13906. })
  13907. Button('跳转')
  13908. .fontColor(Color.White)//
  13909. .layoutWeight(1)
  13910. .height(50)
  13911. .backgroundColor(this.themeColor)
  13912. .stateEffect(true)
  13913. .margin({ left: 6 })
  13914. .onClick(() => {
  13915. DialogHelper.closeDialog('tips'); //关闭弹框
  13916. this.isShowEdit = false
  13917. this.longItemFilePath = ''
  13918. // if(this.isGridMusic&&!this.isShowPlay){
  13919. // this.longItemFilePath== ''
  13920. // }else{
  13921. // this.isShowEdit = false
  13922. // }
  13923. this.isShowMoreView = false;
  13924. this.isShowPlay = false
  13925. this.mType = 4
  13926. // router.pushUrl({
  13927. // url: 'pages/SettingPage'
  13928. // }, router.RouterMode.Single);
  13929. })
  13930. }
  13931. }
  13932. .width("100%")
  13933. .padding(10)
  13934. }
  13935. @Builder
  13936. PlayMoreSheet() {
  13937. Column() {
  13938. this.MoreList()
  13939. }
  13940. .width('100%')
  13941. .height('100%')
  13942. }
  13943. @Builder
  13944. MoreList() {
  13945. Scroll() {
  13946. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  13947. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  13948. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13949. Row() {
  13950. if (more.id === 3&&this.currentSong) {
  13951. Image(more.image)
  13952. .width(24)
  13953. .height(24)
  13954. .margin({ left: 10, right: 10 })
  13955. Text(more.title)
  13956. .fontSize(16)
  13957. .fontColor(Color.White)
  13958. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  13959. height: '99%',
  13960. dragBar: true,
  13961. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  13962. showClose: true,
  13963. blurStyle: BlurStyle.Thin,
  13964. backgroundColor: Color.Transparent,
  13965. title: { title: '歌曲信息' }
  13966. })
  13967. } else if (more.id === 15 && this.currentSong) { //编辑标签
  13968. Image(more.image)
  13969. .width(24)
  13970. .height(24)
  13971. .margin({ left: 10, right: 10 })
  13972. Text(more.title)
  13973. .fontSize(16)
  13974. .fontColor(Color.White)
  13975. } else if (more.id === 5) { //定时关闭
  13976. Image(more.image)
  13977. .width(24)
  13978. .height(24)
  13979. .margin({ left: 10, right: 10 })
  13980. Text(more.title)
  13981. .fontSize(16)
  13982. .fontColor(Color.White)
  13983. .onClick(() => {
  13984. this.doMore(more.id)
  13985. })
  13986. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  13987. height: this.isCoverOpacity() ? '95%' : '95%',
  13988. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  13989. dragBar: true,
  13990. showClose: true,
  13991. title: { title: $r('app.string.time_close') }
  13992. })
  13993. } else if (more.id === 2) { //歌词设置
  13994. Image(more.image)
  13995. .width(24)
  13996. .height(24)
  13997. .margin({ left: 10, right: 10 })
  13998. Text(more.title)
  13999. .fontSize(16)
  14000. .fontColor(Color.White)
  14001. } else if (more.id === 16) { //悬浮歌词设置
  14002. Image(more.image)
  14003. .width(24)
  14004. .height(24)
  14005. .margin({ left: 10, right: 10 })
  14006. Text(more.title)
  14007. .fontSize(16)
  14008. .fontColor(Color.White)
  14009. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  14010. height: '99%',
  14011. dragBar: true,
  14012. preferType: SheetType.CENTER,
  14013. showClose: true,
  14014. blurStyle: BlurStyle.Thin,
  14015. backgroundColor: Color.Transparent,
  14016. title: { title: '悬浮歌词' }
  14017. })
  14018. } else if (more.id === 11) {
  14019. Image(more.image)
  14020. .width(24)
  14021. .height(24)
  14022. .margin({ left: 10, right: 10 })
  14023. Text(more.title)
  14024. .fontSize(16)
  14025. .fontColor(Color.White)
  14026. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  14027. height: this.isCoverOpacity() ? '95%' : '60%',
  14028. dragBar: true,
  14029. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  14030. showClose: true,
  14031. blurStyle: BlurStyle.Thin,
  14032. backgroundColor: Color.Transparent,
  14033. title: { title: '跳过头尾' }
  14034. })
  14035. } else if (more.id === 12) { //投播
  14036. AVCastPicker({
  14037. customPicker: (): void => this.TPImageBuilder(more),
  14038. onStateChange: (state) => {
  14039. if (state == AVCastPickerState.STATE_APPEARING) {
  14040. console.log(' The picker starts showing.');
  14041. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  14042. console.log(' The picker finishes presenting.');
  14043. }
  14044. },
  14045. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  14046. sessionType: 'video'
  14047. })
  14048. .id('AVCastPicker')
  14049. } else {
  14050. if(more.id >= 22){
  14051. SymbolGlyph(more.image)
  14052. .fontSize(24)
  14053. .fontColor([Color.White])
  14054. .alignSelf(ItemAlign.Center)
  14055. .margin({ left: 10, right: 10,bottom:5})
  14056. // .padding({bottom:4})
  14057. .onClick(() => {
  14058. this.doMore(more.id)
  14059. })
  14060. }else{
  14061. Image(more.image)
  14062. .width(24)
  14063. .height(24)
  14064. .fillColor(Color.White)
  14065. .margin({ left: 10, right: 10 })
  14066. .onClick(() => {
  14067. this.doMore(more.id)
  14068. })
  14069. }
  14070. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  14071. .fontSize(16)
  14072. .margin({top:more.id >= 22?3:0})
  14073. .fontColor(Color.White)
  14074. .onClick(() => {
  14075. this.doMore(more.id)
  14076. })
  14077. Select([//倍速
  14078. { value: '0.25x' },
  14079. { value: '0.5x' },
  14080. { value: '0.75x' },
  14081. { value: '1x' },
  14082. { value: '1.25x' },
  14083. { value: '1.5x' },
  14084. { value: '1.75x' },
  14085. { value: '2x' },
  14086. { value: '3x' }])
  14087. .font({ size: 16, weight: FontWeight.Medium })
  14088. .fontColor($r('sys.color.white'))
  14089. .margin({ left: 25 })
  14090. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  14091. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  14092. .value(Utility.optimizedFormat(this.playSpeed))
  14093. .onSelect(async (_index: number, text?: string | undefined) => {
  14094. let speed = parseFloat(text?.replace('x', '') || '1');
  14095. if (!CommonConstants.video_speed_list.includes(speed)) {
  14096. speed = 1;
  14097. }
  14098. this.playSpeed = speed
  14099. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  14100. })
  14101. Slider({
  14102. value: this.volume,
  14103. min: 0,
  14104. max: 1,
  14105. step: 0.1,
  14106. style: SliderStyle.OutSet
  14107. })
  14108. .margin({ left: 18, right: 8 })
  14109. .blockColor(this.themeColor)
  14110. .trackColor($r('app.color.speed_text_color'))
  14111. .selectedColor(Color.White)
  14112. .trackThickness(9)
  14113. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  14114. .onChange((value: number) => {
  14115. this.volume = value;
  14116. this.applyCurrentVolume();
  14117. PreferencesUtil.putSync('DefalutVolume',this.volume)
  14118. })
  14119. .layoutWeight(1)
  14120. Slider({
  14121. value: this.volumeBoostPercent,
  14122. min: 0,
  14123. max: this.volumeBoostMaxPercent,
  14124. step: 1,
  14125. style: SliderStyle.OutSet
  14126. })
  14127. .margin({ left: 18, right: 8 })
  14128. .blockColor(this.themeColor)
  14129. .trackColor($r('app.color.speed_text_color'))
  14130. .selectedColor(Color.White)
  14131. .trackThickness(9)
  14132. .visibility(more.id === 28 ? Visibility.Visible : Visibility.None)
  14133. .onChange((value: number) => {
  14134. this.volumeBoostPercent = Math.round(value);
  14135. this.applyCurrentVolume();
  14136. PreferencesUtil.putSync(this.volumeBoostPreferenceKey, this.volumeBoostPercent);
  14137. })
  14138. .layoutWeight(1)
  14139. Text(`${Math.round(this.volumeBoostPercent)}%`)
  14140. .fontSize(13)
  14141. .fontColor(Color.White)
  14142. .margin({ left: 8, right: 8 })
  14143. .visibility(more.id === 28 ? Visibility.Visible : Visibility.None)
  14144. Text(`${Math.round(this.volume*100)}%`)
  14145. .fontSize(13)
  14146. .fontColor(Color.White)
  14147. .margin({ left: 8, right: 8 })
  14148. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  14149. Blank()
  14150. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  14151. .selectedColor(this.themeColor)
  14152. .switchPointColor(Color.White)
  14153. .margin({ right: 15 })
  14154. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14155. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  14156. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14157. if (more.id == 6) {
  14158. this.isMusicMemoryPlay = checked;
  14159. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  14160. if (this.isMusicMemoryPlay) {
  14161. ToastUtil.showToast('记忆播放已开启')
  14162. } else {
  14163. ToastUtil.showToast('记忆播放已关闭')
  14164. }
  14165. }
  14166. })
  14167. .width(48)
  14168. .height(24);
  14169. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  14170. .selectedColor(this.themeColor)
  14171. .switchPointColor(Color.White)
  14172. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14173. .margin({ right: 15 })
  14174. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  14175. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14176. if (more.id == 7) {
  14177. this.isMusicBGCover = checked;
  14178. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  14179. if (this.isMusicBGCover) {
  14180. ToastUtil.showToast('播放背景随音乐封面已开启')
  14181. } else {
  14182. ToastUtil.showToast('播放背景随音乐封面已关闭')
  14183. }
  14184. }
  14185. })
  14186. .width(48)
  14187. .height(24);
  14188. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  14189. .selectedColor(this.themeColor)
  14190. .switchPointColor(Color.White)
  14191. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14192. .margin({ right: 15 })
  14193. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  14194. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14195. if (more.id == 8) {
  14196. this.isSavePlayMode = checked;
  14197. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  14198. if (this.isSavePlayMode) {
  14199. ToastUtil.showToast('保存播放模式已开启')
  14200. } else {
  14201. ToastUtil.showToast('保存播放模式已关闭')
  14202. }
  14203. }
  14204. })
  14205. .width(48)
  14206. .height(24);
  14207. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  14208. .selectedColor(this.themeColor)
  14209. .switchPointColor(Color.White)
  14210. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14211. .margin({ right: 15 })
  14212. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  14213. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14214. if (more.id == 13) {
  14215. this.isCoverRectangle = checked;
  14216. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  14217. if (this.isCoverRectangle) {
  14218. ToastUtil.showToast('封面方形已开启,双指缩放封面可以调整封面大小')
  14219. this.animationRoFun()
  14220. } else {
  14221. ToastUtil.showToast('封面圆形已开启,双指缩放封面可以调整封面大小')
  14222. this.animationRoFun()
  14223. }
  14224. }
  14225. })
  14226. .width(48)
  14227. .height(24);
  14228. Toggle({ type: ToggleType.Switch, isOn: this.isShowSpectrum })
  14229. .selectedColor(this.themeColor)
  14230. .switchPointColor(Color.White)
  14231. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14232. .margin({ right: 15 })
  14233. .visibility(more.id == 25 ? Visibility.Visible : Visibility.None)
  14234. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14235. if (more.id == 25) {
  14236. this.isShowSpectrum = checked;
  14237. PreferencesUtil.put("isShowSpectrum", this.isShowSpectrum)
  14238. }
  14239. })
  14240. .width(48)
  14241. .height(24);
  14242. // 频谱特效类型选择器
  14243. Select([
  14244. { value: '柱状' },
  14245. { value: '波形' },
  14246. { value: '水波纹' },
  14247. { value: '圆形' },
  14248. { value: '粒子' },
  14249. { value: '脉冲' },
  14250. { value: '镜像柱' },
  14251. { value: '影子柱' },
  14252. { value: '轨道线' },
  14253. { value: '点阵' },
  14254. { value: '星爆' },
  14255. { value: '心电图' },
  14256. { value: '特效' }
  14257. ])
  14258. .font({ size: 14, weight: FontWeight.Medium })
  14259. .fontColor(Color.White)
  14260. .margin({ left: 25 })
  14261. .margin({top:more.id >= 22?3:0})
  14262. .visibility(more.id === 26 ? Visibility.Visible : Visibility.None)
  14263. .selected(this.spectrumModeIndex)
  14264. .value(['柱状', '波形', '水波纹', '圆形', '粒子', '脉冲', '镜像柱', '影子柱', '轨道线', '点阵', '星爆', '心电图', '特效'][this.spectrumModeIndex])
  14265. .onSelect((index: number, _text?: string) => {
  14266. this.spectrumModeIndex = index;
  14267. // 使用同步方法保存,确保立即生效
  14268. PreferencesUtil.putSync('spectrumModeIndex', this.spectrumModeIndex);
  14269. AppStorage.setOrCreate<number>('spectrumMode', this.spectrumModeIndex);
  14270. const modeNames = ['柱状', '波形', '水波纹', '圆形', '粒子', '脉冲', '镜像柱', '影子柱', '轨道线', '点阵', '星爆', '心电图', '特效'];
  14271. Logger.info('heanup-LocalMusic', '频谱特效已切换为: ' + modeNames[index]);
  14272. });
  14273. Toggle({ type: ToggleType.Switch, isOn: this.showSimple })
  14274. .selectedColor(this.themeColor)
  14275. .switchPointColor(Color.White)
  14276. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14277. .margin({ right: 15 })
  14278. .visibility(more.id == 22 ? Visibility.Visible : Visibility.None)
  14279. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14280. if (more.id == 22) {
  14281. this.showSimple = checked;
  14282. PreferencesUtil.put('showSimple', this.showSimple)
  14283. }
  14284. })
  14285. .width(48)
  14286. .height(24);
  14287. Toggle({ type: ToggleType.Switch, isOn: this.enablePointLight })
  14288. .selectedColor(this.themeColor)
  14289. .switchPointColor(Color.White)
  14290. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14291. .margin({ right: 15 })
  14292. .visibility(more.id == 23 ? Visibility.Visible : Visibility.None)
  14293. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14294. if (more.id == 23) {
  14295. this.enablePointLight = checked;
  14296. PreferencesUtil.put('enablePointLight', this.enablePointLight)
  14297. AppStorage.setOrCreate('EnablePointLight', this.enablePointLight);
  14298. }
  14299. })
  14300. .width(48)
  14301. .height(24);
  14302. Toggle({ type: ToggleType.Switch, isOn: this.isGeKongPlayNext })
  14303. .selectedColor(this.themeColor)
  14304. .switchPointColor(Color.White)
  14305. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14306. .margin({ right: 15 })
  14307. .visibility(more.id == 27 ? Visibility.Visible : Visibility.None)
  14308. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14309. if (more.id == 27) {
  14310. this.isGeKongPlayNext = checked;
  14311. PreferencesUtil.put('isGeKongPlayNext', this.isGeKongPlayNext)
  14312. }
  14313. })
  14314. .width(48)
  14315. .height(24);
  14316. Toggle({ type: ToggleType.Switch, isOn: this.isShowBgLiuGUANG })
  14317. .selectedColor(this.themeColor)
  14318. .switchPointColor(Color.White)
  14319. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14320. .margin({ right: 15 })
  14321. .visibility(more.id == 21 ? Visibility.Visible : Visibility.None)
  14322. .onChange((checked: boolean) => { // 是否开启背景流光效果
  14323. if (more.id == 21) {
  14324. this.isShowBgLiuGUANG = checked;
  14325. PreferencesUtil.putSync('isShowBgLiuGUANG',this.isShowBgLiuGUANG)
  14326. }
  14327. })
  14328. .width(48)
  14329. .height(24);
  14330. }
  14331. }
  14332. .width('100%')
  14333. .height(45)
  14334. .padding(15)
  14335. .backgroundColor(Color.Transparent)
  14336. .borderRadius(12)
  14337. .margin({ bottom: 6 })
  14338. }
  14339. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  14340. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  14341. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  14342. .backgroundColor(Color.Transparent)
  14343. .onClick(() => {
  14344. this.doMore(more.id)
  14345. })
  14346. });
  14347. }
  14348. .width('100%')
  14349. .padding(16)
  14350. }.margin({ bottom: 18 })
  14351. }
  14352. @Builder
  14353. TPImageBuilder(more: MoreItem): void {
  14354. Row() {
  14355. Image($r('app.media.tuoping'))
  14356. .width(22)
  14357. .height(22)
  14358. .margin({ left: 10, right: 10 })
  14359. Text(more.title)
  14360. .fontSize(16)
  14361. .fontColor(Color.White)
  14362. }
  14363. .width('100%')
  14364. .layoutWeight(1)
  14365. .alignItems(VerticalAlign.Center)
  14366. .justifyContent(FlexAlign.Start)
  14367. }
  14368. private moreItems: MoreItem[] = [
  14369. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  14370. { id: 30, image: $r('sys.symbol.lyrics_square'), title: '歌词' },
  14371. { id: 24, image: $r('sys.symbol.slider_vertical_3'), title: '均衡器' },
  14372. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  14373. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  14374. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  14375. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  14376. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  14377. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  14378. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  14379. { id:20,image: $r("app.media.a_b"), title: 'AB循环' },
  14380. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  14381. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  14382. { id: 4, image: $r('app.media.share2'), title: '分享' },
  14383. { id: 9, image: $r('app.media.volume_white'), title: '音量减弱' },
  14384. { id: 28, image: $r('sys.symbol.speaker_wave_3'), title: '音量增强' },
  14385. { id: 25, image: $r('sys.symbol.ranking'), title: '音乐频谱' },
  14386. { id: 26, image: $r('sys.symbol.eight_diagram'), title: '频谱类型' },
  14387. { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  14388. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  14389. { id : 22, image: $r('sys.symbol.satellite_map'), title: '沉浸式' },
  14390. { id : 23, image: $r('sys.symbol.lightbulb'), title: '点光源效果' },
  14391. { id : 21, image: $r('app.media.kp_music'), title: '背景双边流光' },
  14392. { id : 27, image: $r('sys.symbol.hand'), title: '隔空手势切歌' },
  14393. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  14394. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  14395. ];
  14396. @State isShowBgLiuGUANG: boolean = false;
  14397. @State isShowMoreView: boolean = false;
  14398. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  14399. @State isShowTimeCloseMore: boolean = false
  14400. @State isShowDetailMore: boolean = false
  14401. @State isMusicBGCover: boolean = true
  14402. @State isSavePlayMode: boolean = true
  14403. @State isLyricSetting: boolean = false
  14404. @State isJumpSetting: boolean = false
  14405. @State isShowEdit: boolean = false
  14406. @State showPipLyric: boolean = false
  14407. @State isShowSpectrum: boolean = false//是否显示频谱
  14408. @State spectrumModeIndex: number = 0 //选中的频谱特效索引
  14409. private getSafeBoostPercent(): number {
  14410. const rawBoostPercent = Math.max(0, Math.min(this.volumeBoostPercent, this.volumeBoostMaxPercent));
  14411. if (rawBoostPercent <= 150) {
  14412. return rawBoostPercent;
  14413. }
  14414. if (rawBoostPercent <= 300) {
  14415. return 150 + (rawBoostPercent - 150) * 0.45;
  14416. }
  14417. return 217.5 + (rawBoostPercent - 300) * 0.15;
  14418. }
  14419. private getVolumeBoostFactor(): number {
  14420. return 1 + this.getSafeBoostPercent() / 100;
  14421. }
  14422. private getCurrentOutputVolume(): number {
  14423. const baseVolume = Math.max(0, Math.min(this.volume, 1));
  14424. const boostedVolume = baseVolume * this.getVolumeBoostFactor();
  14425. const maxOutputVolume = this.getVolumeBoostFactor();
  14426. return Math.max(0, Math.min(boostedVolume, maxOutputVolume));
  14427. }
  14428. private applyCurrentVolume(forceDsfSafeVolume: boolean = false): void {
  14429. if (!this.mIjkMediaPlayer) {
  14430. return;
  14431. }
  14432. if (forceDsfSafeVolume && this.volumeSmall && this.videoUrl.toLowerCase().endsWith('.dsf')) {
  14433. this.mIjkMediaPlayer.setVolume('1', '1');
  14434. return;
  14435. }
  14436. const outputVolume = this.getCurrentOutputVolume();
  14437. this.mIjkMediaPlayer.setVolume(outputVolume.toString(), outputVolume.toString());
  14438. }
  14439. async setRingTone() {
  14440. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  14441. return
  14442. }
  14443. // 确定后的逻辑
  14444. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  14445. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  14446. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  14447. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  14448. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  14449. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  14450. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  14451. , this.videoUrl, this.name).then(res => {
  14452. LogUtil.info('onecold setFlag :' + res);
  14453. });
  14454. }
  14455. doMore(moreId: number) {
  14456. switch (moreId) {
  14457. case 30: //歌词
  14458. this.isLyricSetting = !this.isLyricSetting;
  14459. this.isShowMoreView = false
  14460. break;
  14461. case 3: //详情
  14462. this.isShowDetailMore = !this.isShowDetailMore;
  14463. break;
  14464. case 4: //分享
  14465. if (this.currentSong !== undefined) {
  14466. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  14467. }
  14468. this.isShowMoreView = false
  14469. break;
  14470. case 5: //定时关闭
  14471. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  14472. break;
  14473. case 10: //设为铃声
  14474. this.setRingTone()
  14475. this.isShowMoreView = false
  14476. break;
  14477. case 11: //跳过头尾
  14478. this.isJumpSetting = !this.isJumpSetting;
  14479. break;
  14480. case 13: //倍速
  14481. break;
  14482. case 14: //搜索封面
  14483. if (this.currentSong !== undefined) {
  14484. this.doSearchCover(this.currentSong)
  14485. }
  14486. this.isShowMoreView = false
  14487. break;
  14488. case 15: //编辑标签
  14489. this.initEditFields(this.currentSong)
  14490. this.tempLyricContent = this.lyricContent
  14491. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  14492. this.lyricConStr = this.tempLyricContent
  14493. }
  14494. this.isShowEdit = !this.isShowEdit;
  14495. break;
  14496. case 16: //悬浮歌词
  14497. this.showPipLyric = !this.showPipLyric;
  14498. break;
  14499. case 17: //横屏模式
  14500. if (this.isLandscape) {
  14501. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  14502. } else {
  14503. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  14504. }
  14505. this.isShowMoreView = false
  14506. break;
  14507. case 20://AB循环
  14508. this.isABSheet = !this.isABSheet
  14509. break;
  14510. case 24://均衡器
  14511. this.isEqualizerSheet = !this.isEqualizerSheet
  14512. break;
  14513. }
  14514. }
  14515. //AB循环
  14516. @State isOpenAB:boolean = false
  14517. @State jumpATime:number = 0
  14518. @State jumpBTime:number = 0
  14519. @State isABSheet:boolean = false
  14520. @State isEqualizerSheet: boolean = false
  14521. @State eqApplying: boolean = false
  14522. @State eqAppliedAt: number = 0
  14523. @State eqCurrentPresetName: string = '正常'
  14524. @State eqCurrentEnabled: boolean = false
  14525. @Builder
  14526. ABLoopSheet() {
  14527. ABLoopComptent({
  14528. jumpATime:this.jumpATime,
  14529. jumpBTime:this.jumpBTime,
  14530. onClickAItem: async ()=>{
  14531. if(this.mIjkMediaPlayer){
  14532. this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
  14533. }
  14534. },
  14535. onClickBItem: async ()=>{
  14536. if(this.mIjkMediaPlayer){
  14537. this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
  14538. if(this.jumpBTime<=this.jumpATime){
  14539. ToastUtil.showToast('设置B点时间不能小于A点时间')
  14540. this.jumpBTime = 0
  14541. }
  14542. }
  14543. },
  14544. onCancleButtonClick: async ()=>{
  14545. this.isOpenAB = false
  14546. this.isABSheet = false
  14547. },
  14548. onStartButtonClick: async ()=>{
  14549. if(this.jumpBTime<=this.jumpATime||this.stringForTime(this.jumpATime)==this.stringForTime(this.jumpBTime)){
  14550. ToastUtil.showToast('设置B点时间不能小于或等于A点时间')
  14551. return
  14552. }
  14553. this.isABSheet = false
  14554. this.startABLoop()
  14555. },
  14556. })
  14557. }
  14558. private syncEqualizerUi(): void {
  14559. const equalizerManager = EqualizerManager.getInstance();
  14560. this.eqCurrentEnabled = equalizerManager.enabled;
  14561. this.eqCurrentPresetName = equalizerManager.getPresetDisplayName(equalizerManager.currentPresetId);
  14562. if (this.CONTROL_PlayStatus === PlayStatus.INIT) {
  14563. this.eqAppliedAt = 0;
  14564. }
  14565. }
  14566. private markEqualizerApplied(): void {
  14567. const equalizerManager = EqualizerManager.getInstance();
  14568. this.eqCurrentEnabled = equalizerManager.enabled;
  14569. this.eqCurrentPresetName = equalizerManager.getPresetDisplayName(equalizerManager.currentPresetId);
  14570. this.eqAppliedAt = Date.now();
  14571. this.eqApplying = false;
  14572. }
  14573. private applyEqualizerToCurrentPlayback(): void {
  14574. if (this.eqApplying) {
  14575. return;
  14576. }
  14577. if (this.castControllerWrapper && this.isCastPlaying) {
  14578. ToastUtil.showToast('投播模式暂不支持实时均衡器');
  14579. return;
  14580. }
  14581. if (!this.currentSong || !this.mIjkMediaPlayer) {
  14582. ToastUtil.showToast('暂无可应用的播放');
  14583. return;
  14584. }
  14585. this.eqApplying = true;
  14586. try {
  14587. const equalizerManager = EqualizerManager.getInstance();
  14588. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  14589. this.markEqualizerApplied();
  14590. ToastUtil.showToast('均衡器已实时生效');
  14591. } catch (error) {
  14592. this.eqApplying = false;
  14593. Logger.warn(TAG, `heanup 应用均衡器失败: ${(error as Error).message}`);
  14594. }
  14595. }
  14596. @Builder
  14597. private EqualizerApplyStatusBar(): void {
  14598. Row() {
  14599. Column() {
  14600. Text(`均衡器:${this.eqCurrentEnabled ? '开' : '关'} · ${this.eqCurrentPresetName}`)
  14601. .fontSize(12)
  14602. .fontColor($r('app.color.text_color'))
  14603. Text(this.eqAppliedAt > 0 ? '当前播放:已生效' : '当前播放:未应用')
  14604. .fontSize(10)
  14605. .fontColor(this.eqAppliedAt > 0 ? this.themeColor : Color.Gray)
  14606. }
  14607. .alignItems(HorizontalAlign.Start)
  14608. Blank()
  14609. Button('重新应用')
  14610. .fontSize(12)
  14611. .fontColor(Color.White)
  14612. .backgroundColor('#666666')
  14613. .height(28)
  14614. .padding({ left: 14, right: 14 })
  14615. .borderRadius(14)
  14616. .enabled(!this.eqApplying && this.CONTROL_PlayStatus !== PlayStatus.INIT)
  14617. .onClick(() => {
  14618. this.applyEqualizerToCurrentPlayback();
  14619. })
  14620. }
  14621. .width('100%')
  14622. .padding({ left: 12, right: 12, top: 8, bottom: 8 })
  14623. .backgroundColor($r('app.color.settings_background_main'))
  14624. .borderRadius(12)
  14625. }
  14626. @Builder
  14627. EqualizerSheet() {
  14628. Column() {
  14629. Column() {
  14630. EqualizerViewWithCallback({
  14631. onEqualizerChanged: () => {
  14632. this.syncEqualizerUi();
  14633. if (this.mIjkMediaPlayer) {
  14634. const equalizerManager = EqualizerManager.getInstance();
  14635. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  14636. this.markEqualizerApplied();
  14637. }
  14638. }
  14639. })
  14640. }
  14641. .margin({ top: 8 })
  14642. Column() {
  14643. this.EqualizerApplyStatusBar()
  14644. }
  14645. .margin({ top: 8 })
  14646. }
  14647. .padding({ left: 12, right: 12, bottom: 20 })
  14648. .width('100%')
  14649. }
  14650. //开始AB循环
  14651. startABLoop(){
  14652. if(this.mIjkMediaPlayer){
  14653. this.seekTo(this.jumpATime+'')
  14654. this.isOpenAB = true
  14655. }
  14656. }
  14657. /**
  14658. * 切换横竖屏
  14659. *
  14660. */
  14661. setOrientation(orientation: number) {
  14662. this.windowClass.setPreferredOrientation(orientation).then(() => {
  14663. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  14664. }).catch((err: BusinessError) => {
  14665. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  14666. });
  14667. }
  14668. /**
  14669. * 画中画功能(悬浮歌词功能)
  14670. *
  14671. */
  14672. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  14673. pipController?: PiPWindow.PiPController;
  14674. navigationId: string = '';
  14675. @State curState: string = '';
  14676. @State curError: ResourceStr = '';
  14677. @State pipBg: string = '#E8E8E8'
  14678. @State buttonAction: string = '';
  14679. //开启画中画功能
  14680. async startPip() {
  14681. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  14682. if (!this.pipController) {
  14683. await this.createPipController();
  14684. }
  14685. if (!this.pipController) {
  14686. Logger.info(`[${TAG}] pipController create error`);
  14687. return;
  14688. }
  14689. await this.pipController.startPiP();
  14690. }
  14691. async stopPip() {
  14692. if (!this.pipController) {
  14693. Logger.info(`[${TAG}] pipController is not exist`);
  14694. return;
  14695. }
  14696. this.isOpenPip = false
  14697. await this.pipController.stopPiP();
  14698. }
  14699. async createPipController() {
  14700. this.pipController = await PiPWindow.create({
  14701. context: getContext(this),
  14702. componentController: this.xcomponentController,
  14703. navigationId: this.navigationId,
  14704. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  14705. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  14706. customUIController: this.nodeController,
  14707. });
  14708. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  14709. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  14710. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  14711. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  14712. this.onStateChange(state, reason);
  14713. });
  14714. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  14715. this.onActionEvent(event, status);
  14716. });
  14717. }
  14718. destroyPipController() {
  14719. if (!this.pipController) {
  14720. return;
  14721. }
  14722. this.pipController.off('stateChange');
  14723. this.pipController.off('controlPanelActionEvent');
  14724. this.pipController = undefined;
  14725. }
  14726. onStateChange(state: PiPWindow.PiPState, reason: string) {
  14727. switch (state) {
  14728. case PiPWindow.PiPState.ABOUT_TO_START:
  14729. this.curState = 'ABOUT_TO_START';
  14730. this.curError = $r('app.string.current_error_hint');
  14731. break;
  14732. case PiPWindow.PiPState.STARTED:
  14733. this.curState = 'STARTED';
  14734. this.curError = $r('app.string.current_error_hint');
  14735. break;
  14736. case PiPWindow.PiPState.ABOUT_TO_STOP:
  14737. this.curState = 'ABOUT_TO_STOP';
  14738. this.curError = $r('app.string.current_error_hint');
  14739. break;
  14740. case PiPWindow.PiPState.STOPPED:
  14741. this.curState = 'STOPPED';
  14742. this.curError = $r('app.string.current_error_hint');
  14743. this.stopPip()
  14744. this.destroyPipController()
  14745. break;
  14746. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  14747. this.curState = 'ABOUT_TO_RESTORE';
  14748. this.curError = $r('app.string.current_error_hint');
  14749. break;
  14750. case PiPWindow.PiPState.ERROR:
  14751. this.curState = 'ERROR';
  14752. this.curError = reason;
  14753. break;
  14754. default:
  14755. break;
  14756. }
  14757. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  14758. }
  14759. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  14760. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  14761. switch (event) {
  14762. case 'playbackStateChanged':
  14763. if (status === 0) {
  14764. this.pause();
  14765. } else {
  14766. console.info('onecold startPlayOrResumePlay 9869')
  14767. this.startPlayOrResumePlay();
  14768. }
  14769. break;
  14770. case 'nextVideo':
  14771. // 切换到下一个视频
  14772. this.playNext().catch(() => {
  14773. Logger.error('heanup onActionEvent playNext', `播放下一首失败`);
  14774. });
  14775. break;
  14776. case 'previousVideo':
  14777. // 切换到上一个视频
  14778. this.playPrevious().catch(() => {
  14779. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败`);
  14780. });
  14781. break;
  14782. case 'previousVideo':
  14783. // 切换到上一个视频
  14784. this.playPrevious().catch(() => {
  14785. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败:`);
  14786. });
  14787. break;
  14788. default:
  14789. }
  14790. this.buttonAction = event + `-status:${status}`;
  14791. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  14792. }
  14793. /**
  14794. * 画中画功能(悬浮歌词功能)结束
  14795. *
  14796. */
  14797. async doSearchCover(item: VideoItem,title?:string,artist?:string): Promise<string> {
  14798. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  14799. this.isShowMoreView = false;
  14800. this.showTipsDialog();
  14801. return ''; // Return empty string when no API is configured
  14802. }
  14803. if (!item) {
  14804. return ''; // Return empty string if item is undefined
  14805. }
  14806. const titleS = title||item?.name || '';
  14807. const artistS = artist||item?.artist || ''; // Use empty string if artist is missing
  14808. return this.searchCover(item, titleS, artistS, true); // Await is not needed here as we return the promise directly
  14809. }
  14810. /**
  14811. *api搜索封面
  14812. *item,根据title和artist
  14813. */
  14814. searchCover(item: VideoItem, title: string, artist: string, markAsCustomCover: boolean = false): Promise<string> {
  14815. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  14816. LogUtil.debug("onecold res =" + res);
  14817. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  14818. if (item.filePath == this.currentSong?.filePath) {
  14819. if (this.currentSong) {
  14820. mergeCoverWithPriority(this.currentSong, res, markAsCustomCover ? 1 : 0);
  14821. this.cover = this.currentSong.pixelMapPath || res;
  14822. }
  14823. }
  14824. if (isRemoteCloudType(item.type)) {
  14825. mergeCoverWithPriority(item, res, markAsCustomCover ? 1 : 0);
  14826. this.syncRemoteManagerSong(item);
  14827. try {
  14828. await this.persistRemoteMetadataToDb(item);
  14829. this.emitRemoteMetadataUpdated(item);
  14830. } catch (error) {
  14831. Logger.error(TAG, `searchCover 持久化网盘封面失败: ${(error as Error).message}`);
  14832. }
  14833. } else {
  14834. // Update pixel map path but always return res regardless of success
  14835. if (markAsCustomCover) {
  14836. item.isCustomCover = 1;
  14837. this.table.updateCustomCoverPath(item.filePath, res, (success: boolean, error?: string) => {
  14838. if (success) {
  14839. this.doUpdateData();
  14840. console.log("onecold 更新音乐封面成功,数据库已同步");
  14841. } else {
  14842. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  14843. }
  14844. });
  14845. } else {
  14846. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  14847. if (success) {
  14848. this.doUpdateData();
  14849. console.log("onecold 更新音乐封面成功,数据库已同步");
  14850. } else {
  14851. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  14852. }
  14853. });
  14854. }
  14855. }
  14856. LogUtil.debug("onecold this.cover =" + this.cover);
  14857. }
  14858. return res; // Always return res regardless of updatePixelMapPath result
  14859. });
  14860. }
  14861. @State jumpTopTime: number = 0
  14862. @State jumpEndTime: number = 0
  14863. @State isOpenJump: boolean = false
  14864. @Builder
  14865. JumpTopEndSheet() {
  14866. Scroll() {
  14867. Column() {
  14868. Column() {
  14869. Text('仅对本播放列表有效')
  14870. .fontSize(16)
  14871. .fontColor($r('app.color.text_color'))
  14872. // 跳过头尾
  14873. Column() {
  14874. Row() {
  14875. Text('跳过片头:')
  14876. .fontSize(16)
  14877. .fontColor($r('app.color.text_color'))
  14878. Text(this.jumpTopTime + 's')
  14879. .fontSize(16)
  14880. .fontColor($r('app.color.text_color'))
  14881. }
  14882. .margin({ bottom: 5 })
  14883. Row() {
  14884. Slider({
  14885. value: this.jumpTopTime,
  14886. min: 0,
  14887. max: 120,
  14888. step: 1,
  14889. style: SliderStyle.OutSet
  14890. })
  14891. .blockColor(this.themeColor)
  14892. .trackColor($r('app.color.speed_text_color'))
  14893. .selectedColor(Color.White)
  14894. .trackThickness(8)
  14895. .onChange((value: number) => {
  14896. this.jumpTopTime = value;
  14897. })
  14898. .width('85%')
  14899. }
  14900. .alignItems(VerticalAlign.Top)
  14901. }
  14902. .margin({ top: 10, bottom: 10 })
  14903. // 跳过头尾
  14904. Column() {
  14905. Row() {
  14906. Text('跳过片尾:')
  14907. .fontSize(16)
  14908. .fontColor($r('app.color.text_color'))
  14909. Text(this.jumpEndTime + 's')
  14910. .fontSize(16)
  14911. .fontColor($r('app.color.text_color'))
  14912. }
  14913. .margin({ bottom: 5 })
  14914. Row() {
  14915. Slider({
  14916. value: this.jumpEndTime,
  14917. min: 0,
  14918. max: 120,
  14919. step: 1,
  14920. style: SliderStyle.OutSet
  14921. })
  14922. .blockColor(this.themeColor)
  14923. .trackColor($r('app.color.speed_text_color'))
  14924. .selectedColor(Color.White)
  14925. .trackThickness(8)
  14926. .onChange((value: number) => {
  14927. this.jumpEndTime = value;
  14928. })
  14929. .width('85%')
  14930. }
  14931. .alignItems(VerticalAlign.Top)
  14932. }
  14933. .margin({ top: 10, bottom: 10 })
  14934. Row() {
  14935. Button('保存设置')
  14936. .fontColor(Color.White)
  14937. .layoutWeight(1)
  14938. .height(40)
  14939. .width(80)
  14940. .backgroundColor(this.themeColor)
  14941. .stateEffect(true)
  14942. .margin({ left: 0, bottom: 20 })
  14943. .onClick(async () => {
  14944. if (!Utility.isNoble()) {
  14945. this.isJumpSetting = false
  14946. this.isShowMoreView = false
  14947. this.showVipDialog()
  14948. return
  14949. }
  14950. if (this.currentSong === undefined) {
  14951. return
  14952. }
  14953. if (this.modeType === 0) {
  14954. let parentPath = FileUtil.getParentPath(this.videoUrl)
  14955. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  14956. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  14957. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  14958. } else if (this.modeType === 1) { //媒体库
  14959. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  14960. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  14961. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  14962. } else if (this.modeType === 2) { //艺术家
  14963. if (this.currentSong?.artist) {
  14964. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  14965. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  14966. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  14967. }
  14968. } else if (this.modeType === 3) { //专辑
  14969. if (this.currentSong?.album) {
  14970. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  14971. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  14972. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  14973. }
  14974. }
  14975. ToastUtil.showShort("保存成功")
  14976. this.isJumpSetting = false
  14977. })
  14978. }
  14979. .margin({
  14980. left: 38,
  14981. right: 38,
  14982. top: 10,
  14983. bottom: 10
  14984. })
  14985. .width(120)
  14986. .height(50)
  14987. }
  14988. }
  14989. }
  14990. .width('100%')
  14991. .height('100%')
  14992. }
  14993. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  14994. private onStateVastChange(state: AVCastPickerState) {
  14995. if (state == AVCastPickerState.STATE_APPEARING) {
  14996. console.log('The picker starts showing.');
  14997. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  14998. console.log('The picker finishes presenting.');
  14999. }
  15000. }
  15001. private showSelectLyric() {
  15002. DialogHelper.showActionSheetDialog({
  15003. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  15004. // sheets: ["本地歌词", "搜索歌词"],
  15005. sheets: [
  15006. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  15007. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  15008. ],
  15009. maskColor: Color.Transparent,
  15010. backgroundColor: $r('app.color.bg_card'),
  15011. transition: AnimationHelper.transitionInDown(666),
  15012. onAction: (index) => {
  15013. switch (index) {
  15014. case 0:
  15015. this.callFilePickerSelectFileForLyric()
  15016. break;
  15017. case 1:
  15018. if (StrUtil.isNotEmpty(this.videoUrl)) {
  15019. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  15020. this.initLyric(lyricPath);
  15021. }
  15022. break;
  15023. }
  15024. }
  15025. })
  15026. }
  15027. // 拉起picker选择文件管理器
  15028. async callFilePickerSelectFileForLyric(): Promise<void> {
  15029. try {
  15030. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  15031. DocumentSelectOptions.maxSelectNumber = 1
  15032. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  15033. let documentPicker = new picker.DocumentViewPicker();
  15034. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  15035. Logger.info(TAG,
  15036. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  15037. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  15038. this.saveVideoDatasLyric(DocumentSelectResult)
  15039. }
  15040. }).catch((err: BusinessError) => {
  15041. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  15042. });
  15043. } catch (err) {
  15044. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  15045. }
  15046. }
  15047. async saveVideoDatasLyric(uris: string[]) {
  15048. if (ArrayUtil.isEmpty(uris)) {
  15049. return
  15050. }
  15051. let newUris: string[] = [];
  15052. for (let i = 0; i < uris.length; i++) {
  15053. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  15054. Logger.info(TAG, 'filePath uri: ' + filePath);
  15055. newUris.push(filePath)
  15056. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  15057. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  15058. fileIo.copyFileSync(file.fd, file2.fd)
  15059. fileIo.closeSync(file);
  15060. fileIo.closeSync(file2);
  15061. this.initLyric(filePath,false,false,true)
  15062. }
  15063. }
  15064. private initDelayPlay(context: object) {
  15065. this.mContext = context;
  15066. }
  15067. startPipLyric() {
  15068. if (this.pipController) {
  15069. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  15070. PiPWindow.PiPControlStatus.PLAY);
  15071. }
  15072. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  15073. if (this.isOpenPip) {
  15074. this.startPip()
  15075. } else {
  15076. this.stopPip()
  15077. }
  15078. }
  15079. //startOffset 从cue分轨时间开始播
  15080. private startPlayOrResumePlay(startOffset?:number) {
  15081. let finalStartOffset = startOffset
  15082. if ((finalStartOffset === undefined || finalStartOffset === null) && this.currentSong && isCueSplitItem(this.currentSong)) {
  15083. finalStartOffset = 0
  15084. }
  15085. //新版本ijkplayer可以直接播放dsf歌,不需要转格式了。所以注释掉代码
  15086. //针对dsf文件高采样率,统一转wav播放
  15087. // const sampleRate = this.currentSong?.sampleRate||0
  15088. // if(this.videoUrl.toLowerCase().endsWith('.dsf')&&sampleRate>=441000){
  15089. // console.info('onecold 采样率 ='+sampleRate)
  15090. // let newDsfPath = this.context.filesDir + '/'+FileUtil.getFileName(this.videoUrl)+'.wav'
  15091. // console.info('onecold newDsfPath ='+newDsfPath)
  15092. // if(!FileUtil.accessSync(newDsfPath)){
  15093. // const task = new taskpool.Task(convertDsfToWav,this.videoUrl,newDsfPath);
  15094. // taskpool.execute(task, taskpool.Priority.HIGH).then((data)=>{
  15095. // this.videoUrl = newDsfPath
  15096. // this.startPlay(startOffset)
  15097. // }).catch((e:object)=>{
  15098. // console.info("task1 catch e: " + e);
  15099. // })
  15100. // }else{
  15101. // this.videoUrl = newDsfPath
  15102. // this.startPlay(startOffset)
  15103. // }
  15104. //
  15105. // }else{
  15106. // this.startPlay(startOffset)
  15107. // }
  15108. this.startPlay(finalStartOffset)
  15109. // 仅当前播放的是网盘歌曲时,才提前缓存下一首
  15110. // 排除用户拖动进度条的情况
  15111. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !this.isSeekTo) {
  15112. void this.preloadNextSongInternal();
  15113. }
  15114. }
  15115. startPlay(startOffset?:number) {
  15116. this.startPipLyric()
  15117. this.mDestroyPage = false;
  15118. this.animationState = AnimationStatus.Running
  15119. LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  15120. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  15121. this.stopProgressTask();
  15122. this.startProgressTask();
  15123. this.clearInitialSeekGuardTimer();
  15124. this.activePlaybackMemoryKey = this.getPlaybackMemoryKey();
  15125. this.remoteRestoreSeekToken++;
  15126. const shouldMemoryPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)
  15127. || (this.isMemoryLastPlay && this.isFirstStartPlay);
  15128. this.pendingMemorySeekPosition = shouldMemoryPlay ? PreferencesUtil.getNumberSync(this.getPlaybackMemoryKey(), 0) : 0;
  15129. const isRemoteStreamSong = this.currentSong && isRemoteCloudType(this.currentSong.type) &&
  15130. this.videoUrl.includes('://');
  15131. this.waitInitialSeekBeforeStart = !!isRemoteStreamSong && this.pendingMemorySeekPosition > 0;
  15132. // 网盘歌曲起播阶段统一显示加载圈,prepared/首帧后再收起
  15133. this.isPlayerLoading = !!isRemoteStreamSong;
  15134. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  15135. Logger.info(
  15136. TAG,
  15137. `[remote-play] startPlay type=${this.currentSong.type}, memory=${this.pendingMemorySeekPosition}, ` +
  15138. `waitInitial=${this.waitInitialSeekBeforeStart}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  15139. );
  15140. }
  15141. this.play(this.videoUrl.toString(),startOffset);
  15142. }
  15143. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  15144. this.mIjkMediaPlayer.start();
  15145. this.setProgress()
  15146. this.CONTROL_PlayStatus = PlayStatus.PLAY
  15147. }
  15148. this.setIsPlaying(true)
  15149. this.updateSessionPlayState(true)
  15150. this.watchStatus();
  15151. this.updateLastPlayTimeStr(this.videoUrl)
  15152. }
  15153. updateLastPlayTimeStr(filePath: string) {
  15154. // 检查是否为网络音频(WebDAV),如果是则不更新本地数据库
  15155. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  15156. Logger.info(`heanup 检测到网络音频播放,跳过数据库更新: ${filePath}`)
  15157. return;
  15158. }
  15159. const targetFilePath = this.currentSong?.filePath || filePath;
  15160. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  15161. this.table.updateLastPlayedStrByFilePath(targetFilePath, lastPlayTime, (success: boolean, error?: string) => {
  15162. if (success) {
  15163. this.getHistoryList(false)
  15164. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  15165. } else {
  15166. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  15167. }
  15168. });
  15169. }
  15170. private completionNum(num: number): string | number {
  15171. if (num < 10) {
  15172. return '0' + num;
  15173. } else {
  15174. return num;
  15175. }
  15176. }
  15177. private parseDurationToMs(duration?: string): number {
  15178. if (!duration) {
  15179. return 0;
  15180. }
  15181. const parts = duration.split(':').map((item) => Number(item));
  15182. if (parts.some((item) => Number.isNaN(item))) {
  15183. return 0;
  15184. }
  15185. if (parts.length === 2) {
  15186. return Math.floor((parts[0] * 60 + parts[1]) * 1000);
  15187. }
  15188. if (parts.length === 3) {
  15189. return Math.floor((parts[0] * 3600 + parts[1] * 60 + parts[2]) * 1000);
  15190. }
  15191. return 0;
  15192. }
  15193. private sanitizePlaybackUrl(url?: string): string {
  15194. if (!url) {
  15195. return '';
  15196. }
  15197. let sanitized = url.replace(/(access_token=)[^&]+/ig, '$1***');
  15198. sanitized = sanitized.replace(/(refresh_token=)[^&]+/ig, '$1***');
  15199. sanitized = sanitized.replace(/(Authorization=)[^&]+/ig, '$1***');
  15200. if (sanitized.length > 220) {
  15201. return `${sanitized.substring(0, 220)}...`;
  15202. }
  15203. return sanitized;
  15204. }
  15205. private async resolvePlaybackUrlForCurrentSong(source: string): Promise<string | null> {
  15206. const song = this.currentSong;
  15207. if (!song) {
  15208. Logger.warn(TAG, `[play-url] skip source=${source}, currentSong is null`);
  15209. return null;
  15210. }
  15211. const expectedFilePath = song.filePath || '';
  15212. const requestSerial = ++this.playbackUrlRequestSerial;
  15213. Logger.info(
  15214. TAG,
  15215. `[play-url] begin serial=${requestSerial}, source=${source}, song=${song.name}, path=${expectedFilePath}`
  15216. );
  15217. const resolvedUrl = await setVideoUrlForSong(song, {
  15218. context: this.context,
  15219. autoParseMusicName: this.autoParseMusicName
  15220. });
  15221. const currentFilePath = this.currentSong?.filePath || '';
  15222. if (requestSerial !== this.playbackUrlRequestSerial || currentFilePath !== expectedFilePath) {
  15223. Logger.warn(
  15224. TAG,
  15225. `[play-url] stale serial=${requestSerial}, source=${source}, expected=${expectedFilePath}, ` +
  15226. `current=${currentFilePath}, drop=${this.sanitizePlaybackUrl(resolvedUrl)}`
  15227. );
  15228. return null;
  15229. }
  15230. Logger.info(
  15231. TAG,
  15232. `[play-url] apply serial=${requestSerial}, source=${source}, song=${song.name}, ` +
  15233. `url=${this.sanitizePlaybackUrl(resolvedUrl)}`
  15234. );
  15235. return resolvedUrl;
  15236. }
  15237. private beginSeekTrace(source: string, requestMs: number): void {
  15238. this.lastSeekSource = source;
  15239. this.lastSeekRequestMs = requestMs;
  15240. this.seekTraceUntilTs = Date.now() + this.seekTraceLogWindowMs;
  15241. this.lastSeekTraceLogTs = 0;
  15242. }
  15243. private isSeekTraceActive(): boolean {
  15244. return this.seekTraceUntilTs > 0 && Date.now() <= this.seekTraceUntilTs;
  15245. }
  15246. private logSeekTrace(stage: string, position?: number, playerDuration?: number, force: boolean = false): void {
  15247. if (!force && !this.isSeekTraceActive()) {
  15248. return;
  15249. }
  15250. const now = Date.now();
  15251. if (!force && now - this.lastSeekTraceLogTs < this.seekTraceLogIntervalMs) {
  15252. return;
  15253. }
  15254. this.lastSeekTraceLogTs = now;
  15255. const currentPosition = typeof position === 'number' ? position : this.mIjkMediaPlayer.getCurrentPosition();
  15256. const resolvedPlayerDuration = typeof playerDuration === 'number' ? playerDuration : this.mIjkMediaPlayer.getDuration();
  15257. Logger.info(
  15258. TAG,
  15259. `[seek-trace] stage=${stage}, source=${this.lastSeekSource || 'unknown'}, req=${this.lastSeekRequestMs}, ` +
  15260. `current=${currentPosition}, playerDuration=${resolvedPlayerDuration}, uiDuration=${this.duration}, ` +
  15261. `activeDuration=${this.getActiveDuration()}, isPlaying=${this.mIjkMediaPlayer.isPlaying()}, ` +
  15262. `isSeekTo=${this.isSeekTo}, waitInitial=${this.waitInitialSeekBeforeStart}, ` +
  15263. `songType=${this.currentSong?.type ?? -1}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  15264. );
  15265. }
  15266. private stringForTime(timeMs: number): string {
  15267. let totalSeconds: number | string = (timeMs / 1000);
  15268. let newSeconds: number | string = totalSeconds % 60;
  15269. let minutes: number | string = (totalSeconds / 60) % 60;
  15270. let hours: number | string = totalSeconds / 3600;
  15271. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  15272. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  15273. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  15274. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  15275. if (this.isCurrentTime) {
  15276. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  15277. this.oldSeconds = newSeconds
  15278. } else {
  15279. newSeconds = this.oldSeconds
  15280. }
  15281. }
  15282. newSeconds = this.completionNum(newSeconds);
  15283. if (hours > 0) {
  15284. return hours + ":" + minutes + ":" + newSeconds;
  15285. } else {
  15286. return minutes + ":" + newSeconds;
  15287. }
  15288. }
  15289. private getPlayerSwiperDisplayCount(): number {
  15290. return new BreakpointType<number>({
  15291. sm: 1,
  15292. md: 2,
  15293. lg: 2,
  15294. xl: 2,
  15295. xxl: 2
  15296. }).getValue(this.currentBreakpoint) ?? 1
  15297. }
  15298. private shouldUpdateMainLyricPanel(): boolean {
  15299. return this.getPlayerSwiperDisplayCount() > 1 || this.currentSwiperIndex === 1
  15300. }
  15301. private getActivePlaybackPositionMs(): number {
  15302. if (this.castControllerWrapper && this.isCastPlaying) {
  15303. return this.currentTime2 * 1000
  15304. }
  15305. return this.mIjkMediaPlayer.getCurrentPosition()
  15306. }
  15307. private syncLyricPositionNow(): void {
  15308. const position = this.getActivePlaybackPositionMs()
  15309. if (position < 0) {
  15310. return
  15311. }
  15312. this.updateLyricPosition(position + this.timeOffset * 1000)
  15313. }
  15314. private updateLyricPosition(lyricPosition: number): void {
  15315. if (!this.isAppForeground || !this.isPageVisible) {
  15316. return;
  15317. }
  15318. const shouldUpdateMainLyric = this.shouldUpdateMainLyricPanel()
  15319. const shouldUpdatePipLyric = this.showPipLyric
  15320. const shouldUpdateSingleLineLyric = this.isShowSingleLineLyric
  15321. if (!shouldUpdateMainLyric && !shouldUpdatePipLyric && !shouldUpdateSingleLineLyric) {
  15322. return
  15323. }
  15324. if (!Number.isNaN(this.lastLyricRenderPosition) &&
  15325. Math.abs(lyricPosition - this.lastLyricRenderPosition) < this.lyricUpdateMinDeltaMs) {
  15326. return;
  15327. }
  15328. this.lastLyricRenderPosition = lyricPosition;
  15329. if (shouldUpdateMainLyric) {
  15330. this.lyricController.updatePosition(lyricPosition);
  15331. }
  15332. if (shouldUpdatePipLyric) {
  15333. this.lyricControllerXF.updatePosition(lyricPosition);
  15334. }
  15335. if (shouldUpdateSingleLineLyric) {
  15336. this.lyricControllerSingle.updatePosition(lyricPosition);
  15337. }
  15338. }
  15339. private setProgress() {
  15340. if (this.castControllerWrapper && this.isCastPlaying) {
  15341. return;
  15342. }
  15343. const shouldRefreshUi = this.isAppForeground && this.isPageVisible;
  15344. const rawPosition = this.mIjkMediaPlayer.getCurrentPosition();
  15345. const rawDuration = this.mIjkMediaPlayer.getDuration();
  15346. const cueTrackItem = this.currentSong && isCueSplitItem(this.currentSong) ? this.currentSong : undefined;
  15347. const cueTrackStartOffset = cueTrackItem ? getCueTrackStartOffset(cueTrackItem) : 0;
  15348. const cueTrackEndOffset = cueTrackItem ? getCueTrackEndOffset(cueTrackItem) : 0;
  15349. const cueTrackDuration = cueTrackItem ? getCueTrackDuration(cueTrackItem) : 0;
  15350. let position = rawPosition;
  15351. let duration = rawDuration;
  15352. if (cueTrackItem) {
  15353. position = Math.max(0, rawPosition - cueTrackStartOffset);
  15354. if (cueTrackDuration > 0) {
  15355. duration = cueTrackDuration;
  15356. } else if (cueTrackEndOffset > cueTrackStartOffset) {
  15357. duration = cueTrackEndOffset - cueTrackStartOffset;
  15358. } else if (rawDuration > cueTrackStartOffset) {
  15359. duration = rawDuration - cueTrackStartOffset;
  15360. }
  15361. if (duration > 0 && position > duration) {
  15362. position = duration;
  15363. }
  15364. }
  15365. if (duration <= 0 && this.duration > 0) {
  15366. duration = this.duration;
  15367. }
  15368. let pos = 0;
  15369. if (duration > 0) {
  15370. this.slideEnable = true;
  15371. let curPercent = position / duration;
  15372. pos = curPercent * 100;
  15373. if (shouldRefreshUi) {
  15374. if (pos > this.PROGRESS_MAX_VALUE) {
  15375. this.progressValue = this.PROGRESS_MAX_VALUE
  15376. } else {
  15377. this.progressValue = pos;
  15378. }
  15379. }
  15380. }
  15381. this.logSeekTrace('progress-tick', position, duration);
  15382. // LogUtils.getInstance()
  15383. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  15384. if (shouldRefreshUi) {
  15385. this.totalTime = this.stringForTime(duration);
  15386. }
  15387. if (position > duration) {
  15388. position = duration;
  15389. }
  15390. if (shouldRefreshUi) {
  15391. const lyricPosition = (cueTrackItem ? rawPosition : position) + this.timeOffset * 1000;
  15392. this.isCurrentTime = true;
  15393. this.updateLyricPosition(lyricPosition);
  15394. // 蓝牙歌词更新逻辑
  15395. if (this.bluetoothLyricEnabled && this.isBluetoothConnected && this.lyricContent && this.currentSong) {
  15396. const currentLyricLine = LyricUtil.getCurrentLyricLine(this.lyricContent, lyricPosition);
  15397. // 仅在歌词行变化时更新,避免频繁调用
  15398. if (currentLyricLine !== this.lastBluetoothLyricLine) {
  15399. this.lastBluetoothLyricLine = currentLyricLine;
  15400. this.avSessionController.updateBluetoothLyric(
  15401. currentLyricLine,
  15402. this.currentSong.name || '',
  15403. this.currentSong.artist || '',
  15404. this.bluetoothLyricMode
  15405. );
  15406. }
  15407. }
  15408. this.currentTime = this.stringForTime(position);
  15409. this.isCurrentTime = false
  15410. }
  15411. if (this.mIjkMediaPlayer.isPlaying()) {
  15412. const isCueTrackCompleted = cueTrackItem &&
  15413. cueTrackEndOffset > cueTrackStartOffset &&
  15414. rawPosition >= cueTrackEndOffset;
  15415. //如果是开启AB循环
  15416. if(this.isOpenAB){
  15417. if(position >=this.jumpBTime){
  15418. this.seekTo(this.jumpATime+'')
  15419. return
  15420. }
  15421. }
  15422. // 判断是否播放到结束时间
  15423. if ((this.isOpenJump && duration > this.jumpEndTime * 1000 &&
  15424. position >= duration - this.jumpEndTime * 1000) || isCueTrackCompleted) {
  15425. if(this.playType == 1){//跳过尾部如果是单曲循环就选择单曲循环
  15426. this.CONTROL_PlayStatus = PlayStatus.INIT
  15427. this.startPlayOrResumePlay();
  15428. }else if (this.playType == 2) { //2:正常播放,单片播完
  15429. this.showRePlay();
  15430. this.currentTime = this.stringForTime(duration);
  15431. this.progressValue = this.PROGRESS_MAX_VALUE;
  15432. this.slideEnable = false;
  15433. this.stop();
  15434. // ToastUtil.showToast('开始重新播放')
  15435. }else if (this.playType == 4) { //4:连续播放不循环
  15436. // 检查是否是最后一首
  15437. if (this.curIndex >= this.songList.length - 1) {
  15438. // 已经是最后一首,停止播放
  15439. Logger.info('heanup setProgress', '连续播放不循环模式:已到达最后一首,停止播放');
  15440. ToastUtil.showToast('已经是最后一首了');
  15441. this.showRePlay();
  15442. this.currentTime = this.stringForTime(duration);
  15443. this.progressValue = this.PROGRESS_MAX_VALUE;
  15444. this.slideEnable = false;
  15445. this.stop();
  15446. } else {
  15447. // 不是最后一首,继续播放下一首
  15448. this.playNext().catch(() => {
  15449. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  15450. });
  15451. }
  15452. }else{
  15453. this.playNext().catch(() => {
  15454. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  15455. });
  15456. }
  15457. }
  15458. }
  15459. }
  15460. private startProgressTask() {
  15461. let that = this;
  15462. if (this.updateProgressTimer) {
  15463. clearInterval(this.updateProgressTimer);
  15464. this.updateProgressTimer = 0;
  15465. }
  15466. this.updateProgressTimer = setInterval(() => {
  15467. //LogUtils.getInstance().LOGI("startProgressTask");
  15468. if (!that.mDestroyPage) {
  15469. that.setProgress();
  15470. }
  15471. }, this.progressUpdateIntervalMs);
  15472. }
  15473. private stopProgressTask() {
  15474. LogUtils.getInstance().LOGI("stopProgressTask");
  15475. clearInterval(this.updateProgressTimer);
  15476. this.updateProgressTimer = 0;
  15477. }
  15478. private showLoadIng() {
  15479. this.isPlayerLoading = true;
  15480. this.loadingVisible = Visibility.Visible;
  15481. this.replayVisible = Visibility.None;
  15482. }
  15483. private hideLoadIng() {
  15484. this.isPlayerLoading = false;
  15485. this.loadingVisible = Visibility.None;
  15486. this.replayVisible = Visibility.None;
  15487. }
  15488. private showRePlay() {
  15489. this.isPlayerLoading = false;
  15490. this.loadingVisible = Visibility.None;
  15491. this.replayVisible = Visibility.Visible;
  15492. }
  15493. private beginRemoteSongSwitchLoading(song?: VideoItem): boolean {
  15494. const shouldShow = !!song && isRemoteCloudType(song.type);
  15495. if (shouldShow) {
  15496. this.showLoadIng();
  15497. }
  15498. return shouldShow;
  15499. }
  15500. private clearInitialSeekGuardTimer(): void {
  15501. if (this.initialSeekGuardTimer) {
  15502. clearTimeout(this.initialSeekGuardTimer);
  15503. this.initialSeekGuardTimer = 0;
  15504. }
  15505. }
  15506. private ensurePlayerStartedAfterInitialSeek(reason: string): void {
  15507. try {
  15508. if (!this.mIjkMediaPlayer.isPlaying()) {
  15509. this.mIjkMediaPlayer.start();
  15510. }
  15511. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  15512. this.setIsPlaying(true);
  15513. this.updateSessionPlayState(true);
  15514. Logger.info(TAG, `记忆播放恢复开播: ${reason}`);
  15515. } catch (error) {
  15516. Logger.error(TAG, `记忆播放恢复开播失败(${reason}): ${(error as Error).message}`);
  15517. }
  15518. }
  15519. private finishInitialSeekWait(reason: string, shouldStart: boolean): void {
  15520. this.clearInitialSeekGuardTimer();
  15521. const wasWaiting = this.waitInitialSeekBeforeStart;
  15522. this.waitInitialSeekBeforeStart = false;
  15523. this.pendingMemorySeekPosition = 0;
  15524. this.isPlayerLoading = false;
  15525. this.hideLoadIng();
  15526. if (wasWaiting) {
  15527. Logger.info(TAG, `结束记忆seek等待: ${reason}`);
  15528. }
  15529. if (shouldStart) {
  15530. this.ensurePlayerStartedAfterInitialSeek(reason);
  15531. }
  15532. }
  15533. private startInitialSeekGuardTimer(scene: string): void {
  15534. this.clearInitialSeekGuardTimer();
  15535. if (!this.waitInitialSeekBeforeStart || this.pendingMemorySeekPosition <= 0) {
  15536. return;
  15537. }
  15538. const token = this.remoteRestoreSeekToken;
  15539. this.initialSeekGuardTimer = setTimeout(() => {
  15540. if (token !== this.remoteRestoreSeekToken || !this.waitInitialSeekBeforeStart) {
  15541. return;
  15542. }
  15543. Logger.warn(TAG, `记忆seek超时兜底开播, scene=${scene}, pos=${this.pendingMemorySeekPosition}`);
  15544. this.finishInitialSeekWait('seek-timeout', true);
  15545. }, this.initialSeekGuardTimeoutMs);
  15546. }
  15547. private async play(url: string,startOffset?:number) {
  15548. this.lyricController.setLyric(null)
  15549. this.lyricControllerSingle.setLyric(null)
  15550. this.lastLyricRenderPosition = Number.NaN;
  15551. this.isShowBgLiuGUANG = PreferencesUtil.getBooleanSync('isShowBgLiuGUANG', false)
  15552. console.info('onecold this.url 1= '+url)
  15553. if(!url.toLowerCase().startsWith('http')){
  15554. let hasPermission = await PermissionUtil.activatePermission(url)
  15555. console.info('onecold this.hasPermission 1= '+hasPermission)
  15556. if(!url.includes(this.packName)){
  15557. const file = fs.openSync(url)
  15558. this.videoUrl = file.path
  15559. url= this.videoUrl
  15560. }
  15561. console.info('onecold this.hasPermission 1= '+hasPermission)
  15562. console.info('onecold this.videoUrl 1= '+this.videoUrl)
  15563. }
  15564. let that = this;
  15565. const isBaiduStreamingPlaybackUrl = this.isBaiduStreamingUrl(url);
  15566. if (this.waitInitialSeekBeforeStart) {
  15567. that.showLoadIng();
  15568. } else {
  15569. that.hideLoadIng();
  15570. }
  15571. const startOnPreparedOption = this.waitInitialSeekBeforeStart ? "0" : "1";
  15572. this.isOpenAB = false
  15573. //设置XComponent回调的context
  15574. if (!!this.mContext) {
  15575. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  15576. }
  15577. // 每次播放前都先 reset,防止快速切换歌曲时崩溃
  15578. // 修复 SIGSEGV 崩溃:确保播放器在设置新数据源前完全停止并释放资源
  15579. try {
  15580. this.mIjkMediaPlayer.reset();
  15581. Logger.info(TAG, 'IjkPlayer reset 成功');
  15582. } catch (error) {
  15583. Logger.error(TAG, `IjkPlayer reset 失败: ${(error as Error).message}`);
  15584. }
  15585. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  15586. //设置debug模式(用于EQ日志采集)
  15587. this.mIjkMediaPlayer.setDebug(true);
  15588. //初始化配置
  15589. this.mIjkMediaPlayer.native_setup();
  15590. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  15591. this.applyCurrentVolume(true);
  15592. // 构建规范的HTTP请求头(统一一次性设置,避免未带认证提前发起连接)
  15593. const headers = new Map<string, string>();
  15594. headers.set("User-Agent", "TTMusic-WebDAV/1.0");
  15595. headers.set("Accept", "*/*");
  15596. if (this.currentSong&&StrUtil.isEmpty(this.currentSong.pixelMapPath)
  15597. &&PreferencesUtil.getStringSync('COVER_API', '') != '') {
  15598. //如果封面为空,则搜索封面
  15599. this.searchCover(this.currentSong, this.currentSong.name, this.currentSong.artist||'')
  15600. }
  15601. // 如果是WebDAV网络音频,使用webdav_account_id获取认证信息(等待完成后再设置一次性头部)
  15602. // SMB类型通过本地HTTP代理播放,不需要认证头,排除SMB和百度类型
  15603. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !isBaiduType(this.currentSong.type) && !isSmbType(this.currentSong.type)) {
  15604. Logger.info(`heanup WebDAV歌曲认证 - 歌曲名: ${this.currentSong.name}, webdav_account_id: ${this.currentSong.webdav_account_id || '未设置'}`);
  15605. if (this.currentSong.webdav_account_id) {
  15606. try {
  15607. const webdavManager = RemoteDriveManager.getInstance();
  15608. const webDavHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  15609. if (webDavHeaders && webDavHeaders.size > 0) {
  15610. webDavHeaders.forEach((value, key) => headers.set(key, value));
  15611. Logger.info(`heanup 成功通过webdav_account_id获取并合并WebDAV认证头`);
  15612. } else {
  15613. Logger.warn(`heanup 通过webdav_account_id获取认证头失败,播放可能无法继续`);
  15614. }
  15615. } catch (error) {
  15616. const err = error as Error;
  15617. Logger.error(`heanup 获取WebDAV认证头时出错: ${err.message}`);
  15618. }
  15619. } else {
  15620. Logger.error(`heanup WebDAV歌曲 "${this.currentSong.name}" 缺少webdav_account_id,无法进行认证`);
  15621. }
  15622. } else if (this.currentSong && isSmbType(this.currentSong.type)) {
  15623. Logger.info(`heanup SMB歌曲通过HTTP代理播放,无需认证头`);
  15624. }
  15625. // 统一设置带认证的请求头
  15626. // 百度类型也需要特殊请求头
  15627. if (this.currentSong && isBaiduType(this.currentSong.type)) {
  15628. try {
  15629. const webdavManager = RemoteDriveManager.getInstance();
  15630. const baiduHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  15631. baiduHeaders.forEach((value, key) => headers.set(key, value));
  15632. const headerSnapshot: Record<string, string> = {};
  15633. headers.forEach((value, key) => headerSnapshot[key] = value);
  15634. Logger.info(TAG, `Baidu播放请求头: ${JSON.stringify(headerSnapshot)}`);
  15635. } catch (error) {
  15636. Logger.error(`heanup 构建百度请求头失败: ${(error as Error).message}`);
  15637. }
  15638. }
  15639. //设置视频源(先准备好认证头,再设置数据源)
  15640. Logger.info(TAG, `IjkPlayer setDataSource url=${url}`);
  15641. this.mIjkMediaPlayer.setDataSource(url);
  15642. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  15643. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !isBaiduType(this.currentSong.type)) {
  15644. console.log(`heanup 为WebDAV播放设置IjkPlayer选项`);
  15645. // 网络超时设置(单位:微秒,文档显示应该是字符串格式)
  15646. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "30000000"); // 30秒
  15647. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "30000000"); // 连接超时30秒
  15648. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "listen_timeout", "30000000"); // 监听超时30秒
  15649. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "30000000"); // DNS缓存超时30秒
  15650. // 缓冲和播放优化设置
  15651. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "1024000"); // 增大缓冲区
  15652. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "50"); // 减少最小帧数
  15653. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", startOnPreparedOption); // 预加载启动
  15654. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0"); // 无缓冲播放
  15655. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "30000"); // 最大缓存30秒
  15656. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1"); // 无限制收流
  15657. // 网络相关设置
  15658. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1"); // 启用HTTP重定向
  15659. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", "TTMusic-WebDAV/1.0"); // 用户代理
  15660. // 重连设置
  15661. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "reconnect", "3"); // 重连3次
  15662. console.log(`heanup WebDAV IjkPlayer选项设置完成`);
  15663. } else if ((this.currentSong && isBaiduType(this.currentSong.type)) || isBaiduStreamingPlaybackUrl) {
  15664. console.log(`heanup 为百度网盘播放设置IjkPlayer选项`);
  15665. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "15000000");
  15666. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "15000000");
  15667. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1");
  15668. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "1");
  15669. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "2097152");
  15670. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "25");
  15671. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", BaiduConstants.USER_AGENT);
  15672. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", "3");
  15673. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http-detect-range-support", "1");
  15674. console.log(`heanup 百度网盘 IjkPlayer 选项设置完成`);
  15675. }
  15676. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  15677. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  15678. // }
  15679. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  15680. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  15681. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  15682. let bufferSize = 50 * 1024 ; // 默认缓冲区大小为1MB
  15683. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  15684. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  15685. //停止预读的最小帧数
  15686. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  15687. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  15688. // 设置其他缓冲相关选项
  15689. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  15690. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  15691. //启动预加载
  15692. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", startOnPreparedOption);
  15693. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  15694. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  15695. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  15696. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  15697. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  15698. // 因此需要播放器丢包,才不会累积延时
  15699. // 这个和第三个参数packet-buffering无关。
  15700. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  15701. // 无限制收流
  15702. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  15703. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  15704. // 屏幕常亮
  15705. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  15706. // 开启hls起播优化 默认是关闭的
  15707. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "fetch_first", "on");
  15708. // 设置超时
  15709. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  15710. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  15711. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  15712. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  15713. // 变速播放
  15714. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  15715. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  15716. let Speed = this.mIjkMediaPlayer.getSpeed()
  15717. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  15718. //是否开启循环播放
  15719. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  15720. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = new ImplOnVideoSizeChangedListener(
  15721. (width: number, height: number, sar_num: number, sar_den: number) => {
  15722. if (height === 0) {
  15723. return;
  15724. }
  15725. const va = width / height;
  15726. const vpa = that.videoParentAspectRatio;
  15727. if (vpa > va) {
  15728. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  15729. } else {
  15730. that.videoWidth = '100%';
  15731. }
  15732. if (width && height) {
  15733. that.videoAspectRatio = width / height;
  15734. }
  15735. LogUtils.getInstance()
  15736. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  15737. if (!that.waitInitialSeekBeforeStart) {
  15738. that.hideLoadIng();
  15739. }
  15740. }
  15741. );
  15742. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  15743. let mOnPreparedListener: OnPreparedListener = new ImplOnPreparedListener(
  15744. async () => {
  15745. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  15746. Logger.info(
  15747. TAG,
  15748. `[seek] prepared enter, waitInitial=${this.waitInitialSeekBeforeStart}, pendingMemory=${this.pendingMemorySeekPosition}, ` +
  15749. `songType=${this.currentSong?.type ?? -1}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  15750. );
  15751. if (!this.waitInitialSeekBeforeStart) {
  15752. // 无记忆seek时,prepared后可直接隐藏加载
  15753. this.isPlayerLoading = false;
  15754. }
  15755. try {
  15756. //保存碰一碰分享的当前的歌曲
  15757. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  15758. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  15759. await this.initLyric(lyricPath);
  15760. const applyDuration = (durationMs: number): void => {
  15761. const cueTrackDuration = this.currentSong && isCueSplitItem(this.currentSong)
  15762. ? getCueTrackDuration(this.currentSong)
  15763. : 0;
  15764. const effectiveDuration = cueTrackDuration > 0 ? cueTrackDuration : durationMs;
  15765. if (effectiveDuration <= 0) {
  15766. return;
  15767. }
  15768. this.duration = effectiveDuration;
  15769. this.durationTime = Math.floor(effectiveDuration / 1000);
  15770. this.durationStringTime = secondToTime(this.durationTime);
  15771. this.totalTime = this.stringForTime(effectiveDuration);
  15772. if (this.currentSong) {
  15773. this.currentSong.duration = this.totalTime;
  15774. try {
  15775. this.avSessionController.setAVMetadataMusic(this.currentSong, effectiveDuration, this.lyricContent);
  15776. } catch (metaError) {
  15777. Logger.warn(TAG, `heanup 首次播放写入AVSession失败: ${(metaError as Error).message}`);
  15778. }
  15779. }
  15780. };
  15781. const fetchBaiduM3u8Duration = async (url: string): Promise<number> => {
  15782. if (!url || !isBaiduType(this.currentSong?.type ?? -1)) {
  15783. return 0;
  15784. }
  15785. const httpRequest = http.createHttp();
  15786. try {
  15787. const response = await httpRequest.request(url, {
  15788. method: http.RequestMethod.GET,
  15789. connectTimeout: 8000,
  15790. readTimeout: 8000,
  15791. expectDataType: http.HttpDataType.STRING,
  15792. header: {
  15793. 'User-Agent': BaiduConstants.STREAMING_USER_AGENT,
  15794. 'Host': 'pan.baidu.com',
  15795. 'Referer': 'https://pan.baidu.com/disk/home',
  15796. 'Accept-Encoding': 'identity'
  15797. }
  15798. });
  15799. if (response.responseCode !== 200 || typeof response.result !== 'string') {
  15800. return 0;
  15801. }
  15802. const text = response.result;
  15803. if (text.indexOf('#EXTM3U') < 0) {
  15804. return 0;
  15805. }
  15806. const lines = text.split('\n');
  15807. let totalSeconds = 0;
  15808. for (let i = 0; i < lines.length; i++) {
  15809. const line = lines[i].trim();
  15810. if (line.startsWith('#EXTINF:')) {
  15811. const colonIndex = line.indexOf(':');
  15812. if (colonIndex < 0) {
  15813. continue;
  15814. }
  15815. const content = line.substring(colonIndex + 1);
  15816. const commaIndex = content.indexOf(',');
  15817. const numberPart = commaIndex >= 0 ? content.substring(0, commaIndex) : content;
  15818. const seconds = Number(numberPart);
  15819. if (!Number.isNaN(seconds) && seconds > 0) {
  15820. totalSeconds += seconds;
  15821. }
  15822. }
  15823. }
  15824. if (totalSeconds > 0) {
  15825. return Math.floor(totalSeconds * 1000);
  15826. }
  15827. return 0;
  15828. } catch (fetchError) {
  15829. Logger.warn(TAG, `heanup 解析百度M3U8时长失败: ${(fetchError as Error).message}`);
  15830. return 0;
  15831. } finally {
  15832. httpRequest.destroy();
  15833. }
  15834. };
  15835. const fetchDurationFallback = async (): Promise<void> => {
  15836. const durationMs = await fetchBaiduM3u8Duration(this.videoUrl);
  15837. if (durationMs > 0) {
  15838. Logger.info(TAG, `heanup 通过M3U8推导出时长: ${durationMs}ms`);
  15839. applyDuration(durationMs);
  15840. return;
  15841. }
  15842. Logger.warn(TAG, 'heanup 首次播放未拿到时长,保持未知');
  15843. };
  15844. const preparedDuration = this.mIjkMediaPlayer.getDuration();
  15845. Logger.info(
  15846. TAG,
  15847. `[seek] prepared duration snapshot, playerDuration=${preparedDuration}, metaDuration=${this.currentSong?.duration ?? ''}, ` +
  15848. `url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  15849. );
  15850. if (preparedDuration > 0) {
  15851. applyDuration(preparedDuration);
  15852. if (this.videoUrl.includes('method=streaming') && isBaiduType(this.currentSong?.type ?? -1)) {
  15853. const durationMs = await fetchBaiduM3u8Duration(this.videoUrl);
  15854. if (durationMs > 0 && Math.abs(durationMs - preparedDuration) > 1000) {
  15855. Logger.info(TAG, `heanup 使用M3U8时长覆盖播放器时长: ${preparedDuration}ms -> ${durationMs}ms`);
  15856. applyDuration(durationMs);
  15857. }
  15858. }
  15859. } else {
  15860. const metaDurationMs = this.parseDurationToMs(this.currentSong?.duration);
  15861. if (metaDurationMs > 0) {
  15862. Logger.info(TAG, `heanup 使用元数据时长: ${metaDurationMs}ms`);
  15863. applyDuration(metaDurationMs);
  15864. } else {
  15865. fetchDurationFallback();
  15866. }
  15867. }
  15868. setTimeout(() => {
  15869. this.avSessionController.initAvSession(false);
  15870. if (this.duration > 0) {
  15871. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  15872. }
  15873. this.setAvSessionListener();
  15874. this.updateSessionPlayState(true)
  15875. this.setCurrentPlayMode()
  15876. const cueTrackStartOffset = this.currentSong && isCueSplitItem(this.currentSong)
  15877. ? getCueTrackStartOffset(this.currentSong)
  15878. : 0;
  15879. if ((startOffset && startOffset > 0) || cueTrackStartOffset > 0) {//cue分轨播放
  15880. const cueSeekValue = cueTrackStartOffset > 0 && (!startOffset || startOffset <= 0) ? 0 : startOffset;
  15881. this.seekTo((cueSeekValue || 0) + "");
  15882. this.saveLastPlayList()
  15883. return
  15884. }
  15885. }, 500)
  15886. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  15887. let timeoutPlay = 0
  15888. if (StrUtil.isNotEmpty(this.videoUrl) &&
  15889. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  15890. timeoutPlay = 400
  15891. }
  15892. // 网盘流地址在prepare后立刻seek容易触发底层不稳定,统一延后记忆恢复
  15893. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.videoUrl.includes('://')) {
  15894. timeoutPlay = Math.max(timeoutPlay,
  15895. this.waitInitialSeekBeforeStart ? this.remoteMemorySeekInitialDelayMs : 700);
  15896. }
  15897. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  15898. if (this.modeType === 0) { //文件夹
  15899. let parentPath = FileUtil.getParentPath(this.videoUrl)
  15900. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  15901. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  15902. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  15903. } else if (this.modeType === 1) { //媒体库
  15904. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  15905. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  15906. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  15907. } else if (this.modeType === 2) { //艺术家
  15908. if (this.currentSong?.artist) {
  15909. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  15910. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  15911. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  15912. }
  15913. } else if (this.modeType === 3) { //专辑
  15914. if (this.currentSong?.album) {
  15915. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  15916. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  15917. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  15918. }
  15919. }
  15920. const playerDuration = this.mIjkMediaPlayer.getDuration()
  15921. if (playerDuration > 0 && (!this.currentSong || !isCueSplitItem(this.currentSong))) {
  15922. this.duration = playerDuration
  15923. }
  15924. const memoryPosition = this.pendingMemorySeekPosition > 0 ?
  15925. this.pendingMemorySeekPosition : PreferencesUtil.getNumberSync(this.getPlaybackMemoryKey(), 0);
  15926. if (this.waitInitialSeekBeforeStart && memoryPosition > 0) {
  15927. let targetSeekPosition = memoryPosition;
  15928. if (this.isOpenJump) {
  15929. targetSeekPosition = Math.max(targetSeekPosition, this.jumpTopTime * 1000);
  15930. }
  15931. this.pendingMemorySeekPosition = targetSeekPosition;
  15932. this.startInitialSeekGuardTimer('prepared-memory-seek');
  15933. Logger.info(TAG, `准备记忆播放seek: ${targetSeekPosition}ms, timeout=${timeoutPlay}ms`);
  15934. setTimeout(() => {
  15935. if (!this.waitInitialSeekBeforeStart) {
  15936. return;
  15937. }
  15938. this.restorePlaybackPosition();
  15939. }, timeoutPlay);
  15940. this.isFirstStartPlay = false
  15941. this.saveLastPlayList()
  15942. return
  15943. }
  15944. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  15945. if (this.mIjkMediaPlayer != null) {
  15946. let jumpTopTimeMs = this.jumpTopTime*1000;
  15947. if (jumpTopTimeMs <= this.duration) {
  15948. // 调用 seekTo 方法,跳到指定时间
  15949. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  15950. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  15951. this.seekTo(jumpTopTimeMs + ""); // 跳到开头或记忆进度中更靠后的位置
  15952. }
  15953. }, timeoutPlay)
  15954. } else {
  15955. // 提示用户无法跳过
  15956. ToastUtil.showToast('跳过时间超过视频时长');
  15957. }
  15958. }
  15959. } else {
  15960. this.jumpTopTime = 0
  15961. this.jumpEndTime = 0
  15962. // console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  15963. // console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  15964. // console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  15965. // PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  15966. //记忆播放(每一首都会记忆播放)
  15967. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  15968. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  15969. if (this.pendingMemorySeekPosition > 0 ||
  15970. PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  15971. this.restorePlaybackPosition() //读取播放记忆功能
  15972. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  15973. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  15974. this.restorePlaybackPosition() //读取播放记忆功能
  15975. }
  15976. this.isFirstStartPlay = false
  15977. }, timeoutPlay)
  15978. } else {
  15979. this.isFirstStartPlay = false
  15980. }
  15981. }
  15982. this.saveLastPlayList()
  15983. } catch (error) {
  15984. let err: BusinessError = error as BusinessError;
  15985. console.error('onecold failed with err: ' + JSON.stringify(err));
  15986. if (this.waitInitialSeekBeforeStart) {
  15987. this.finishInitialSeekWait('prepared-exception', true);
  15988. }
  15989. }
  15990. }
  15991. );
  15992. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  15993. let mOnTimedTextListener: OnTimedTextListener = new ImplOnTimedTextListener(
  15994. (text: string) => {
  15995. }
  15996. );
  15997. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  15998. let mOnCompletionListener: OnCompletionListener = new ImplOnCompletionListener(
  15999. () => {
  16000. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  16001. if (this.playType == 0) { //0:连续循环播放 1:单片重复播放 2:正常播放 4:连续播放不循环
  16002. // 异步调用playNext
  16003. this.playNext().catch(() => {
  16004. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  16005. });
  16006. } else if (this.playType == 1) { //1:单片重复播放
  16007. this.CONTROL_PlayStatus = PlayStatus.INIT
  16008. that.startPlayOrResumePlay();
  16009. } else if (this.playType == 2) { //2:正常播放,单曲播完
  16010. that.showRePlay();
  16011. that.currentTime = that.stringForTime(that.getActiveDuration());
  16012. that.progressValue = this.PROGRESS_MAX_VALUE;
  16013. that.slideEnable = false;
  16014. that.stop();
  16015. // ToastUtil.showToast('开始重新播放')
  16016. } else if (this.playType == 3) { //3:随机播放
  16017. // 异步调用randomPlay
  16018. this.randomPlay().catch(() => {
  16019. Logger.error('heanup OnCompletionListener randomPlay', `随机播放失败`);
  16020. });
  16021. } else if (this.playType == 4) { //4:连续播放不循环
  16022. // 异步调用playNext
  16023. this.playNext().catch(() => {
  16024. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  16025. });
  16026. }
  16027. }
  16028. );
  16029. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  16030. let mOnBufferingUpdateListener: OnBufferingUpdateListener = new ImplOnBufferingUpdateListener(
  16031. (percent: number) => {
  16032. if (this.isDebug) {
  16033. const now = Date.now();
  16034. if (now - this.lastBufferingLogTs > this.bufferingLogIntervalMs) {
  16035. this.lastBufferingLogTs = now;
  16036. Logger.info(TAG, `OnBufferingUpdateListener percent=${percent}`);
  16037. }
  16038. }
  16039. }
  16040. );
  16041. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  16042. let mOnSeekCompleteListener: OnSeekCompleteListener = new ImplOnSeekCompleteListener(
  16043. () => {
  16044. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  16045. that.logSeekTrace('seek-complete', undefined, undefined, true);
  16046. // seek 完成,延迟恢复播放,确保 ijkplayer 内部状态完全稳定
  16047. setTimeout(() => {
  16048. const waitingInitialSeek = that.waitInitialSeekBeforeStart;
  16049. that.isSeekTo = false;
  16050. if (waitingInitialSeek) {
  16051. that.finishInitialSeekWait('seek-complete', true);
  16052. } else {
  16053. that.hideLoadIng();
  16054. }
  16055. }, 200); // 延迟200ms,确保ijkplayer内部状态稳定
  16056. }
  16057. );
  16058. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  16059. let mOnInfoListener: OnInfoListener = new ImplOnInfoListener(
  16060. (what: number, extra: number) => {
  16061. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  16062. if (that.isSeekTraceActive()) {
  16063. Logger.info(
  16064. TAG,
  16065. `[seek] onInfo what=${what}, extra=${extra}, source=${that.lastSeekSource || 'unknown'}, ` +
  16066. `req=${that.lastSeekRequestMs}, url=${that.sanitizePlaybackUrl(that.videoUrl)}`
  16067. );
  16068. that.logSeekTrace(`info-${what}`, undefined, undefined, true);
  16069. }
  16070. if (!that.waitInitialSeekBeforeStart) {
  16071. that.hideLoadIng();
  16072. }
  16073. }
  16074. );
  16075. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  16076. let mOnErrorListener: OnErrorListener = new ImplOnErrorListener(
  16077. (what: number, extra: number) => {
  16078. this.finishInitialSeekWait('player-error', false);
  16079. this.stopProgressTask();
  16080. this.logSeekTrace(`error-${what}-${extra}`, undefined, undefined, true);
  16081. Logger.error(
  16082. TAG,
  16083. `[seek] onError what=${what}, extra=${extra}, url=${this.sanitizePlaybackUrl(this.videoUrl)}, ` +
  16084. `song=${JSON.stringify(this.currentSong)}`
  16085. );
  16086. // 检查是否为WebDAV播放错误
  16087. let isWebDavError = false;
  16088. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.currentSong.filePath) {
  16089. try {
  16090. const globalContext = GlobalContext.getContext();
  16091. const webDavAuthInfo = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
  16092. if (webDavAuthInfo) {
  16093. isWebDavError = true;
  16094. }
  16095. } catch (error) {
  16096. console.error('OnErrorListener-->go: 获取WebDAV认证信息失败');
  16097. }
  16098. }
  16099. if (isWebDavError) {
  16100. console.info(`heanup WebDAV播放错误 - what: ${what}, extra: ${extra}, URL: ${this.videoUrl}`);
  16101. // 播放失败时清空实例变量中的WebDAV认证信息,防止错误账户持续使用
  16102. // this.currentWebDavAuthInfo = null;
  16103. console.info('heanup WebDAV播放失败,保留认证信息用于后续歌曲切换');
  16104. // 根据错误代码提供更具体的错误信息
  16105. let errorMessage = "WebDAV播放失败";
  16106. if (what === -1) { // 网络错误
  16107. errorMessage = "网络连接失败,请检查WebDAV服务器连接";
  16108. } else if (what === -1004) { // HTTP 404
  16109. errorMessage = "文件未找到,请检查WebDAV服务器上的文件";
  16110. } else if (what === -1001) { // 超时
  16111. errorMessage = "连接超时,请检查网络或WebDAV服务器状态";
  16112. } else if (what === -1003) { // 无法解析主机
  16113. errorMessage = "无法连接到WebDAV服务器";
  16114. }
  16115. ToastUtil.showToast(errorMessage);
  16116. } else {
  16117. if (StrUtil.isNotEmpty(this.videoUrl) &&
  16118. !this.videoUrl.startsWith('http') &&
  16119. this.currentSong &&this.currentSong.type==CommonConstants.TYPE_LOCAL&&
  16120. !FileUtil.accessSync(this.videoUrl)) {
  16121. console.info('heanup 播放.文件不存在');
  16122. ToastUtil.showToast(Utility.resourceToString(this.context, $r('app.string.file_not_exist')))
  16123. }
  16124. }
  16125. that.hideLoadIng();
  16126. }
  16127. );
  16128. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  16129. this.mIjkMediaPlayer.setMessageListener();
  16130. // 应用均衡器设置
  16131. try {
  16132. const equalizerManager = EqualizerManager.getInstance();
  16133. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  16134. Logger.info(TAG, 'heanup 均衡器设置已应用');
  16135. this.markEqualizerApplied();
  16136. } catch (eqError) {
  16137. Logger.warn(TAG, `heanup 应用均衡器失败: ${(eqError as Error).message}`);
  16138. this.eqApplying = false;
  16139. }
  16140. this.mIjkMediaPlayer.prepareAsync();
  16141. this.mIjkMediaPlayer.start();
  16142. }
  16143. //保存最后播放的那首歌和已经对应的播放列表
  16144. saveLastPlayList() {
  16145. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  16146. PreferencesUtil.putSync('LastMusicList', this.songList)
  16147. PreferencesUtil.putSync('LastPlayQueueScope', this.playQueueScope)
  16148. PreferencesUtil.putSync('LastPlayModeType', this.modeType)
  16149. PreferencesUtil.putSync('LastPlayTotalCount', this.totalCount)
  16150. }
  16151. // 清空播放记录
  16152. clearVideoHistory() {
  16153. this.table.clearPlayHistory((success: boolean, error?: string) => {
  16154. if (success) {
  16155. this.historyList = [];
  16156. this.updateListData(this.historyList)
  16157. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  16158. ToastUtil.showToast('清空播放记录成功')
  16159. } else {
  16160. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  16161. }
  16162. });
  16163. }
  16164. public async setAvSessionListener() {
  16165. if (!this.avSessionController) {
  16166. return;
  16167. }
  16168. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  16169. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  16170. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  16171. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  16172. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  16173. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  16174. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  16175. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  16176. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  16177. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  16178. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  16179. }
  16180. setLoopMode() {
  16181. let itype = this.playType + 1
  16182. if (itype >= 5) {
  16183. this.playType = 0
  16184. ToastUtil.showToast('连续循环播放')
  16185. } else if (itype === 1) {
  16186. this.playType = 1
  16187. ToastUtil.showToast('单曲循环')
  16188. } else if (itype === 2) {
  16189. this.playType = 2
  16190. ToastUtil.showToast('单曲播完')
  16191. } else if (itype === 3) {
  16192. this.playType = 3
  16193. ToastUtil.showToast('随机播放')
  16194. } else if (itype === 4) {
  16195. this.playType = 4
  16196. ToastUtil.showToast('连续播放不循环')
  16197. } else if (itype === 0) {
  16198. this.playType = 0
  16199. ToastUtil.showToast('连续循环播放')
  16200. }
  16201. PreferencesUtil.putSync('musicPlayType', this.playType)
  16202. this.setCurrentPlayMode()
  16203. }
  16204. private sessionSetLoopModeCallback = (mode: number) => {
  16205. if (this.mIjkMediaPlayer != null) {
  16206. ToastUtil.showToast('当前播放模式:' + mode)
  16207. Logger.info('onecold 当前播放模式= ' + mode)
  16208. let hmPlayMode = mode + 1
  16209. if (hmPlayMode >= 4) {
  16210. hmPlayMode = 0
  16211. }
  16212. if (hmPlayMode === 1) {
  16213. this.playType = 1
  16214. ToastUtil.showToast('单曲循环')
  16215. } else if (hmPlayMode === 0) {
  16216. this.playType = 2
  16217. ToastUtil.showToast('单曲播完')
  16218. } else if (hmPlayMode === 3) {
  16219. this.playType = 3
  16220. ToastUtil.showToast('随机播放')
  16221. } else if (hmPlayMode === 2) {
  16222. this.playType = 0
  16223. ToastUtil.showToast('连续循环播放')
  16224. } else if (hmPlayMode === 4) {
  16225. this.playType = 4
  16226. ToastUtil.showToast('连续播放不循环')
  16227. }
  16228. PreferencesUtil.putSync('musicPlayType', this.playType)
  16229. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  16230. let playBackState: avSession.AVPlaybackState = {
  16231. loopMode: hmPlayMode,
  16232. };
  16233. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  16234. console.info(`set setLoopMode AVPlaybackState successfully`);
  16235. }).catch((err: BusinessError) => {
  16236. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  16237. });
  16238. }
  16239. }
  16240. setCurrentPlayMode() {
  16241. if (!this.avSessionController) {
  16242. return;
  16243. }
  16244. let mLoopMode = 0
  16245. switch (this.playType) {
  16246. case 0:
  16247. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续循环播放
  16248. break;
  16249. case 1:
  16250. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  16251. break;
  16252. case 2:
  16253. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  16254. break;
  16255. case 3:
  16256. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  16257. break;
  16258. case 4:
  16259. mLoopMode = avSession.LoopMode.LOOP_MODE_CUSTOM //连续播放不循环
  16260. break;
  16261. }
  16262. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  16263. let playBState: avSession.AVPlaybackState = {
  16264. loopMode: mLoopMode,
  16265. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  16266. };
  16267. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  16268. console.info(`set setLoopMode AVPlaybackState successfully`);
  16269. }).catch((err: BusinessError) => {
  16270. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  16271. });
  16272. }
  16273. private sessionToggleFavoriteCallback = (assetId: string) => {
  16274. if (this.mIjkMediaPlayer != null && this.currentSong) {
  16275. console.info(`on toggleFavorite `);
  16276. // 应用收到收藏命令,进行收藏处理。
  16277. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  16278. this.doFav(this.currentSong)
  16279. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  16280. let playbackState: avSession.AVPlaybackState = {
  16281. isFavorite: !this.isFac,
  16282. };
  16283. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  16284. console.info(`SetAVPlaybackState successfully`);
  16285. }).catch((err: BusinessError) => {
  16286. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  16287. });
  16288. }
  16289. }
  16290. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  16291. device: avSession.OutputDeviceInfo) => {
  16292. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  16293. // 将 connectState 转换为可读的字符串
  16294. let stateName = 'UNKNOWN';
  16295. switch (connectState) {
  16296. case avSession.ConnectionState.STATE_CONNECTED:
  16297. stateName = 'CONNECTED(1)';
  16298. break;
  16299. case avSession.ConnectionState.STATE_DISCONNECTED:
  16300. stateName = 'DISCONNECTED(2)';
  16301. break;
  16302. case avSession.ConnectionState.STATE_CONNECTING:
  16303. stateName = 'CONNECTING(3)';
  16304. break;
  16305. default:
  16306. stateName = `OTHER(${connectState})`;
  16307. }
  16308. Logger.info('heanup sessionOutputDeviceChange', `设备状态变化: connectState=${stateName}, castCategory=${currentDevice?.castCategory}, isCastPlaying=${this.isCastPlaying}`);
  16309. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  16310. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  16311. await this.startCasting();
  16312. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  16313. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  16314. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  16315. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  16316. if (device) {
  16317. Logger.info('heanup sessionOutputDeviceChange', '设备断开连接');
  16318. Logger.info('heanup sessionOutputDeviceChange', '用户主动断开连接或已停止播放,调用endCasting');
  16319. this.endCasting();
  16320. }
  16321. }
  16322. };
  16323. private async startCasting() {
  16324. try {
  16325. Logger.info('heanup startCasting', '========== 开始投播初始化 ==========');
  16326. // 获取原始的 AVCastController
  16327. let avCastCtrl = await this.avSessionController.getAvSession()?.getAVCastController();
  16328. if (!avCastCtrl) {
  16329. Logger.error('heanup startCasting', '获取 AVCastController 失败');
  16330. return;
  16331. }
  16332. this.castController = avCastCtrl;
  16333. Logger.info('heanup startCasting', '✅ 获取 AVCastController 成功');
  16334. // 创建新的 CastController 封装器
  16335. this.castControllerWrapper = new CastController(avCastCtrl);
  16336. Logger.info('heanup startCasting', '✅ 创建 CastController 成功');
  16337. // 设置回调函数
  16338. let callbacks: CastControllerCallbacks = {
  16339. onPlayNext: () => {
  16340. Logger.info('heanup CastController', '收到 playNext 回调');
  16341. this.playNext();
  16342. },
  16343. onPlayPrevious: () => {
  16344. Logger.info('heanup CastController', '收到 playPrevious 回调');
  16345. this.playPrevious();
  16346. },
  16347. onPositionChanged: (position: number) => {
  16348. this.positionChange(position);
  16349. },
  16350. onDurationChanged: (duration: number) => {
  16351. this.playDurationChange(duration);
  16352. }
  16353. };
  16354. this.castControllerWrapper.setCallbacks(callbacks);
  16355. Logger.info('heanup startCasting', '✅ 设置回调成功');
  16356. // 暂停本地播放
  16357. this.pause();
  16358. Logger.info('heanup startCasting', '✅ 暂停本地播放成功');
  16359. // 初始化投播会话
  16360. Logger.info('heanup startCasting', `准备调用 initAVCast: songList.length=${this.songList.length}, curIndex=${this.curIndex}, videoUrl=${this.videoUrl}`);
  16361. await this.castControllerWrapper.initAVCast(
  16362. this.songList,
  16363. this.curIndex,
  16364. this.mIjkMediaPlayer.getCurrentPosition(),
  16365. this.videoUrl,
  16366. this.getActiveDuration()
  16367. );
  16368. Logger.info('heanup startCasting', '✅ initAVCast 调用完成');
  16369. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  16370. refToIsCasting?.set(true);
  16371. this.castSeek = true;
  16372. // 从 CastController 获取投播状态
  16373. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  16374. if (this.isCastPlaying) {
  16375. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  16376. this.setIsPlaying(true);
  16377. this.updateSessionPlayState(true);
  16378. }
  16379. Logger.info('heanup startCasting', `✅ 投播初始化完成, isCastPlaying=${this.isCastPlaying}`);
  16380. } catch (error) {
  16381. Logger.error('heanup startCasting', `❌ 投播初始化失败: ${error}`);
  16382. }
  16383. }
  16384. async changeCasting() {
  16385. Logger.info('heanup changeCasting', '切换投播');
  16386. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  16387. this.initQueueItem();
  16388. await this.prepare();
  16389. this.setPlaybackStateChangeListener();
  16390. // isCastPlaying 会在 playbackStateChangeListener 中根据实际状态更新
  16391. this.castSeek = true;
  16392. }
  16393. public endCasting() {
  16394. Logger.info('heanup endCasting', 'endCasting被调用');
  16395. this.avSessionController.getAvSession()?.stopCasting();
  16396. this.stopCast();
  16397. // 关闭文件描述符
  16398. if (this.castFile) {
  16399. try {
  16400. fs.closeSync(this.castFile);
  16401. this.castFile = undefined;
  16402. Logger.info('heanup endCasting', '关闭投播文件描述符');
  16403. } catch (error) {
  16404. Logger.warn('heanup endCasting', `关闭文件描述符失败: ${error}`);
  16405. }
  16406. }
  16407. this.isCastPlaying = false;
  16408. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  16409. refToIsCasting?.set(false);
  16410. this.pause();
  16411. this.setIsPlaying(false);
  16412. // if (this.curIndex === this.curSource.index) {
  16413. // this.play
  16414. // this.seek(this.currentTime * 1000);
  16415. // this.setIsPlaying(true);
  16416. // } else {
  16417. // this.pauseVideo();
  16418. // this.setIsPlaying(false);
  16419. // }
  16420. }
  16421. public setIsPlaying(isPlayer: boolean) {
  16422. this.isPlaying = isPlayer;
  16423. // 发送播放状态变化事件给歌单详情页面
  16424. try {
  16425. const eventPlaybackStatus: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYBACK_STATUS }
  16426. const currentFilePath = this.currentSong?.filePath || ''
  16427. const eventData: emitter.EventData = {
  16428. data: {
  16429. isPlaying: this.isPlaying,
  16430. curIndex: this.curIndex,
  16431. currentFilePath: currentFilePath
  16432. }
  16433. };
  16434. emitter.emit(eventPlaybackStatus, eventData)
  16435. Logger.info(`heanup 发送播放状态变化事件: isPlaying=${this.isPlaying}, curIndex=${this.curIndex}, currentFilePath=${currentFilePath}`)
  16436. } catch (error) {
  16437. Logger.error('heanup 发送播放状态变化事件失败: ' + error)
  16438. }
  16439. }
  16440. private setPlaybackStateChangeListener(): void {
  16441. // 注意: HarmonyOS 的投播控制器可能不返回 state 字段
  16442. // 我们需要通过其他方式来判断播放状态
  16443. // 1. 监听位置变化
  16444. this.castController?.on('playbackStateChange', ['position'], (playbackState: avSession.AVPlaybackState) => {
  16445. if (playbackState.position && typeof playbackState.position.elapsedTime !== 'undefined') {
  16446. Logger.info('heanup playbackStateChange[position]', `elapsedTime=${playbackState.position.elapsedTime}`);
  16447. this.positionChange(playbackState.position.elapsedTime);
  16448. }
  16449. });
  16450. // 2. 监听时长变化
  16451. this.castController?.on('playbackStateChange', ['extras'], (playbackState: avSession.AVPlaybackState) => {
  16452. const duration = playbackState?.extras?.duration;
  16453. if (typeof duration === 'number') {
  16454. this.playDurationChange(duration);
  16455. }
  16456. });
  16457. // 3. 监听所有状态变化(用于调试和状态判断)
  16458. this.castController?.on('playbackStateChange', 'all', (playbackState: avSession.AVPlaybackState) => {
  16459. Logger.info('heanup playbackStateChange[all]', `完整状态=${JSON.stringify(playbackState)}`);
  16460. // 检查是否有 state 字段(某些设备可能返回)
  16461. if (playbackState.state !== undefined) {
  16462. Logger.info('heanup playbackStateChange', `state字段存在: ${playbackState.state}`);
  16463. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  16464. this.isCastPlaying = true;
  16465. }
  16466. }
  16467. });
  16468. // 4. 监听播放完成事件
  16469. this.castController?.on('endOfStream', this.playNextCallback);
  16470. this.castController?.on('playNext', this.playNextCallback);
  16471. this.castController?.on('playPrevious', this.playPreviousCallback);
  16472. // 5. 监听错误事件
  16473. this.castController?.on('error', (error: BusinessError) => {
  16474. Logger.error('heanup playbackStateChange', `投播错误: code=${error.code}, message=${error.message}`);
  16475. this.isCastPlaying = false;
  16476. });
  16477. }
  16478. private updateSessionPlayState(isPlay: boolean): void {
  16479. // if(!this.isBgPlayOpen)
  16480. // return
  16481. const elapsedTime = (this.castControllerWrapper && this.isCastPlaying) ? this.currentTime2 * 1000
  16482. : this.mIjkMediaPlayer.getCurrentPosition();
  16483. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  16484. this.setAVSessionPlayState({
  16485. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  16486. position: {
  16487. elapsedTime: elapsedTime,
  16488. updateTime: new Date().getTime()
  16489. }
  16490. });
  16491. }
  16492. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  16493. this.avSessionController.setAvSessionPlayState(playbackState)
  16494. }
  16495. private positionChange(position: number) {
  16496. this.currentTime2 = position / 1000;
  16497. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  16498. if (this.castControllerWrapper && this.isCastPlaying) {
  16499. this.updateCastProgress(position);
  16500. if (this.isSeekTo) {
  16501. this.isSeekTo = false;
  16502. }
  16503. }
  16504. }
  16505. private playDurationChange(duration: number) {
  16506. this.duration = duration;
  16507. this.durationTime = Math.floor(this.duration / 1000);
  16508. this.durationStringTime = secondToTime((this.durationTime));
  16509. if (this.castControllerWrapper && this.isCastPlaying) {
  16510. this.totalTime = this.stringForTime(this.duration);
  16511. }
  16512. }
  16513. // playbackStateChangeListener 方法已被删除,改用 setPlaybackStateChangeListener 中的内联函数
  16514. private reloadCasting = async () => {
  16515. Logger.info('heanup reloadCasting', '重新加载投播');
  16516. // 使用 initQueueItem() 方法来准备投播项目,保持逻辑一致
  16517. this.initQueueItem();
  16518. await this.prepare();
  16519. };
  16520. public playNextCallback = (): void => {
  16521. this.playNext().catch(() => {
  16522. Logger.error('heanup playNextCallback', `播放下一首失败`);
  16523. });
  16524. };
  16525. public playPreviousCallback = (): void => {
  16526. this.playPrevious().catch(() => {
  16527. Logger.error('heanup playNextCallback', `播放上一首失败`);
  16528. });
  16529. };
  16530. async prepare() {
  16531. try {
  16532. Logger.info('heanup prepare', `开始准备投播: ${this.castItem?.description?.title}`);
  16533. await this.castController?.prepare(this.castItem);
  16534. Logger.info('heanup prepare', '投播prepare成功');
  16535. await this.castController?.start(this.castItem);
  16536. Logger.info('heanup prepare', '投播start成功');
  16537. // 投播启动成功,设置为投播状态
  16538. this.isCastPlaying = true;
  16539. Logger.info('heanup prepare', '投播启动成功,设置isCastPlaying=true');
  16540. } catch (error) {
  16541. Logger.error('heanup prepare', `投播准备失败: ${error}`);
  16542. this.isCastPlaying = false;
  16543. }
  16544. }
  16545. public initQueueItem() {
  16546. let item = this.songList[this.curIndex];
  16547. // 判断是否是流媒体地址 - 使用 videoUrl 判断而不是 filePath
  16548. // 因为 filePath 可能是 navidrome:// 等自定义协议,而 videoUrl 才是真实的流地址
  16549. let isStreaming = this.isUrl(this.videoUrl);
  16550. Logger.info('heanup initQueueItem', `准备投播歌曲: ${item.name}, 是否流媒体: ${isStreaming}, videoUrl: ${this.videoUrl}`);
  16551. // 关闭之前的文件描述符
  16552. if (this.castFile) {
  16553. try {
  16554. fs.closeSync(this.castFile);
  16555. Logger.info('heanup initQueueItem', '关闭之前的文件描述符');
  16556. } catch (error) {
  16557. Logger.warn('heanup initQueueItem', `关闭文件描述符失败: ${error}`);
  16558. }
  16559. }
  16560. let description: avSession.AVMediaDescription = {
  16561. assetId: 'AUDIO-' + item.filePath,
  16562. title: item.name,
  16563. artist: item.artist || '',
  16564. // 该字段大写,音频'AUDIO',视频'VIDEO'
  16565. mediaType: 'AUDIO',
  16566. mediaSize: item.videoSize,
  16567. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  16568. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  16569. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  16570. duration: this.duration,
  16571. albumCoverUri: item.pixelMapPath, // 本地路径电视可能无法访问,暂时注释
  16572. appName: this.appName,
  16573. lyricContent: item.lyricContent,
  16574. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  16575. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  16576. };
  16577. console.log('heanup initQueueItem this.lyricContent', item.lyricContent);
  16578. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  16579. if (isStreaming) {
  16580. // 流媒体地址使用 mediaUri
  16581. description.mediaUri = this.videoUrl;
  16582. Logger.info('heanup initQueueItem', `使用流媒体地址投播: ${this.videoUrl}`);
  16583. } else {
  16584. // 本地文件使用 fdSrc
  16585. const localPath = this.videoUrl || item.filePath;
  16586. let uri = fileUri.getUriFromPath(localPath);
  16587. this.castFile = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  16588. let fdSrc: media.AVFileDescriptor = {
  16589. fd: this.castFile.fd
  16590. };
  16591. description.fdSrc = fdSrc;
  16592. Logger.info('heanup initQueueItem', `使用本地文件投播: ${localPath}, fd: ${this.castFile.fd}`);
  16593. }
  16594. this.castItem = {
  16595. itemId: this.curIndex,
  16596. description: description
  16597. };
  16598. Logger.info('heanup initQueueItem', `投播项目创建完成: ${JSON.stringify({
  16599. title: description.title,
  16600. mediaType: description.mediaType,
  16601. hasMediaUri: !!description.mediaUri,
  16602. hasFdSrc: !!description.fdSrc,
  16603. duration: description.duration
  16604. })}`);
  16605. }
  16606. // 判断是否是 URL 或流媒体地址
  16607. private isUrl(str: string): boolean {
  16608. if (!str) {
  16609. return false;
  16610. }
  16611. // 检查常见的流媒体协议
  16612. if (str.startsWith('http://') || str.startsWith('https://') ||
  16613. str.startsWith('rtmp://') || str.startsWith('rtsp://') ||
  16614. str.startsWith('rtp://') || str.startsWith('mms://')) {
  16615. return true;
  16616. }
  16617. // 扩展的URL正则表达式,支持多种协议
  16618. const urlPattern = new RegExp(
  16619. '^((https?|ftp|rtmp|rtsp|mms|ws|rtp|wss):\\/\\/)?' + // 支持多种协议
  16620. '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // 域名
  16621. '((\\d{1,3}\\.){3}\\d{1,3})|' + // 或IPv4地址
  16622. '\\[([a-f\\d]{1,4}:){7}[a-f\\d]{1,4}\\]|' + // 或IPv6地址
  16623. 'localhost)' + // 或localhost
  16624. '(\\:\\d+)?' + // 端口号(可选)
  16625. '(\\/[-a-z\\d%_.~+]*)*' + // 路径
  16626. '(\\?[;&a-z\\d%_.~+=-]*)?' + // 查询字符串(可选)
  16627. '(\\#[-a-z\\d_]*)?$', // 片段标识符(可选)
  16628. 'i' // 不区分大小写
  16629. );
  16630. return urlPattern.test(str);
  16631. }
  16632. async stopCast() {
  16633. try {
  16634. // 使用 CastController 释放资源
  16635. if (this.castControllerWrapper) {
  16636. await this.castControllerWrapper.releaseAVCast();
  16637. Logger.info('heanup stopCast', 'CastController 释放投播控制器成功');
  16638. }
  16639. // 清空引用
  16640. this.castControllerWrapper = undefined;
  16641. this.castController = undefined;
  16642. this.castItem = undefined;
  16643. this.castFile = undefined;
  16644. } catch (error) {
  16645. Logger.error('heanup stopCast', `停止投播失败: ${error}`);
  16646. }
  16647. }
  16648. private sessionPlayCallback = (): void => {
  16649. this.playOrPause()
  16650. };
  16651. private sessionPauseCallback = (): void => {
  16652. this.pause()
  16653. };
  16654. private async playOrPause() {
  16655. if (!this.debounce()) {
  16656. return;
  16657. }
  16658. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  16659. await this.pause();
  16660. } else {
  16661. // 如果是投播模式,使用 CastController 的 play 方法
  16662. if (this.castControllerWrapper && this.isCastPlaying) {
  16663. try {
  16664. Logger.info('heanup playOrPause', '投播模式播放');
  16665. await this.castControllerWrapper.setPlaying();
  16666. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  16667. this.setIsPlaying(true);
  16668. this.updateSessionPlayState(true);
  16669. Logger.info('heanup playOrPause', '投播播放成功');
  16670. this.playChange();
  16671. } catch (error) {
  16672. Logger.error('heanup playOrPause', `投播播放失败: ${error}`);
  16673. }
  16674. } else {
  16675. console.info('onecold startPlayOrResumePlay 11064')
  16676. this.startPlayOrResumePlay();
  16677. this.playChange()
  16678. }
  16679. }
  16680. }
  16681. private sessionPlayNextCallback = (): void => {
  16682. this.playNext().catch(() => {
  16683. Logger.error('heanup sessionPlayPreviousCallback', `播放下 一首失败`);
  16684. });
  16685. };
  16686. private sessionPlayPreviousCallback = (): void => {
  16687. this.playPrevious().catch(() => {
  16688. Logger.error('heanup sessionPlayPreviousCallback', `播放上一首失败`);
  16689. });
  16690. };
  16691. private sessionStopCallback = (): void => {
  16692. this.stop()
  16693. };
  16694. private sessionFastForwardCallback = async (time?: number) => {
  16695. if (!time) {
  16696. return;
  16697. }
  16698. let curPosition: number;
  16699. if (this.castController && this.isCastPlaying) {
  16700. // 投播模式,使用UI显示的时间
  16701. curPosition = this.currentTime2 * 1000;
  16702. } else if (this.mIjkMediaPlayer != null) {
  16703. // 本地播放器模式
  16704. curPosition = this.mIjkMediaPlayer.getCurrentPosition();
  16705. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  16706. curPosition = Math.max(0, curPosition - getCueTrackStartOffset(this.currentSong));
  16707. }
  16708. } else {
  16709. return;
  16710. }
  16711. let seeTime = curPosition + time * 1000;
  16712. // 限制 seekValue 在合法范围内
  16713. if (seeTime < 0) {
  16714. seeTime = 0;
  16715. } else if (seeTime > this.duration) {
  16716. seeTime = this.duration;
  16717. }
  16718. Logger.info('heanup sessionFastForwardCallback', `快进: ${time}秒, 目标位置: ${seeTime}ms`);
  16719. this.setSeekToActionProgress(seeTime);
  16720. await this.seekTo(seeTime + "");
  16721. };
  16722. private getActiveDuration(): number {
  16723. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  16724. const cueDuration = getCueTrackDuration(this.currentSong);
  16725. if (cueDuration > 0) {
  16726. return cueDuration;
  16727. }
  16728. }
  16729. let duration = this.mIjkMediaPlayer.getDuration();
  16730. if (this.castControllerWrapper && this.isCastPlaying) {
  16731. return this.duration > 0 ? this.duration : duration;
  16732. }
  16733. if (duration <= 0 && this.duration > 0) {
  16734. duration = this.duration;
  16735. }
  16736. return duration;
  16737. }
  16738. private isBaiduStreamingUrl(url: string): boolean {
  16739. if (StrUtil.isEmpty(url)) {
  16740. return false;
  16741. }
  16742. const lowerUrl = url.toLowerCase();
  16743. return lowerUrl.includes('pan.baidu.com/rest/2.0/xpan/file') && lowerUrl.includes('method=streaming');
  16744. }
  16745. @Builder
  16746. InlineSpectrumView() {
  16747. SpectrumView({
  16748. isVisible: this.currentSwiperIndex === 0,
  16749. isPlaying: this.CONTROL_PlayStatus === PlayStatus.PLAY
  16750. })
  16751. .width( '83%')
  16752. .height(this.isCoverOpacity() ? 80 : 100)
  16753. .margin({bottom: 3 })
  16754. .clip(true)
  16755. .zIndex(-2)
  16756. .onClick(()=>{
  16757. this.cycleSpectrumMode();
  16758. })
  16759. }
  16760. private cycleSpectrumMode(): void {
  16761. const modeNames: string[] = ['柱状', '波形', '水波纹', '圆形', '粒子', '脉冲', '镜像柱', '影子柱', '轨道线', '点阵', '星爆', '心电图', '特效'];
  16762. if (modeNames.length <= 0) {
  16763. return;
  16764. }
  16765. const nextIndex: number = (this.spectrumModeIndex + 1) % modeNames.length;
  16766. this.spectrumModeIndex = nextIndex;
  16767. PreferencesUtil.putSync('spectrumModeIndex', nextIndex);
  16768. AppStorage.setOrCreate<number>('spectrumMode', nextIndex);
  16769. Logger.info('heanup-LocalMusic', `频谱特效已顺序切换为: ${modeNames[nextIndex]}`);
  16770. }
  16771. private getSongDurationMs(song?: VideoItem): number {
  16772. if (!song || !song.duration) {
  16773. return 0;
  16774. }
  16775. const raw = song.duration.trim();
  16776. if (!raw) {
  16777. return 0;
  16778. }
  16779. const parts = raw.split(':').map((part) => Number(part));
  16780. if (parts.some((part) => Number.isNaN(part))) {
  16781. return 0;
  16782. }
  16783. let seconds = 0;
  16784. if (parts.length === 3) {
  16785. seconds = parts[0] * 3600 + parts[1] * 60 + parts[2];
  16786. } else if (parts.length === 2) {
  16787. seconds = parts[0] * 60 + parts[1];
  16788. } else if (parts.length === 1) {
  16789. seconds = parts[0];
  16790. }
  16791. return seconds > 0 ? seconds * 1000 : 0;
  16792. }
  16793. private updateCastProgress(position: number): void {
  16794. const duration = this.getActiveDuration();
  16795. if (duration <= 0) {
  16796. return;
  16797. }
  16798. this.slideEnable = true;
  16799. let pos = (position / duration) * 100;
  16800. if (pos > this.PROGRESS_MAX_VALUE) {
  16801. this.progressValue = this.PROGRESS_MAX_VALUE;
  16802. } else if (pos < 0) {
  16803. this.progressValue = 0;
  16804. } else {
  16805. this.progressValue = pos;
  16806. }
  16807. this.totalTime = this.stringForTime(duration);
  16808. if (position > duration) {
  16809. position = duration;
  16810. }
  16811. this.isCurrentTime = true;
  16812. this.currentTime = this.stringForTime(position);
  16813. this.isCurrentTime = false;
  16814. const lyricPosition = position + this.timeOffset * 1000;
  16815. this.updateLyricPosition(lyricPosition);
  16816. }
  16817. /**
  16818. * Gesture method onActionUpdate.
  16819. *
  16820. * @param event Gesture event.手势拖动设置快进和后退
  16821. */
  16822. private setSeekToActionProgress(position: number) {
  16823. // 投播模式使用this.duration,本地模式使用播放器获取
  16824. let duration = this.getActiveDuration();
  16825. let pos = 0;
  16826. if (duration > 0) {
  16827. this.slideEnable = true;
  16828. let curPercent = position / duration;
  16829. pos = curPercent * 100;
  16830. if (pos > this.PROGRESS_MAX_VALUE) {
  16831. this.progressValue = this.PROGRESS_MAX_VALUE
  16832. } else {
  16833. this.progressValue = pos;
  16834. }
  16835. }
  16836. // LogUtils.getInstance()
  16837. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  16838. this.totalTime = this.stringForTime(duration);
  16839. if (position > duration) {
  16840. position = duration;
  16841. }
  16842. this.isCurrentTime = true;
  16843. this.currentTime = this.stringForTime(position);
  16844. this.isCurrentTime = false
  16845. }
  16846. private sessionRewindCallback = async (time?: number) => {
  16847. if (!time) {
  16848. return;
  16849. }
  16850. let curPosition: number;
  16851. if (this.castController && this.isCastPlaying) {
  16852. // 投播模式,使用UI显示的时间
  16853. curPosition = this.currentTime2 * 1000;
  16854. } else if (this.mIjkMediaPlayer != null) {
  16855. // 本地播放器模式
  16856. curPosition = this.mIjkMediaPlayer.getCurrentPosition();
  16857. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  16858. curPosition = Math.max(0, curPosition - getCueTrackStartOffset(this.currentSong));
  16859. }
  16860. } else {
  16861. return;
  16862. }
  16863. let seeTime = curPosition - time * 1000;
  16864. // 限制 seekValue 在合法范围内
  16865. if (seeTime < 0) {
  16866. seeTime = 0;
  16867. } else if (seeTime > this.duration) {
  16868. seeTime = this.duration;
  16869. }
  16870. Logger.info('heanup sessionRewindCallback', `快退: ${time}秒, 目标位置: ${seeTime}ms`);
  16871. this.setSeekToActionProgress(seeTime);
  16872. await this.seekTo(seeTime + "");
  16873. };
  16874. private sessionSeekCallback = async (seekTime: number) => {
  16875. Logger.info('heanup sessionSeekCallback', `收到seek请求: ${seekTime}ms, 投播模式: ${this.isCastPlaying}`);
  16876. // 投播模式直接调用seekTo,它会自动处理投播控制器的seek命令
  16877. await this.seekTo(seekTime + "");
  16878. };
  16879. private async getFileSize(filePath: string): Promise<number> {
  16880. try {
  16881. const stat = await fs.stat(filePath);
  16882. return stat.size;
  16883. } catch (err) {
  16884. console.error('Failed to get file size: ' + err.message);
  16885. return 0;
  16886. }
  16887. }
  16888. private async pause() {
  16889. // 如果是投播模式,使用 CastController 的 pause 方法
  16890. if (this.castControllerWrapper && this.isCastPlaying) {
  16891. try {
  16892. Logger.info('heanup pause', '投播模式暂停');
  16893. await this.castControllerWrapper.setPause();
  16894. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  16895. this.setIsPlaying(false);
  16896. this.updateSessionPlayState(false);
  16897. Logger.info('heanup pause', '投播暂停成功');
  16898. } catch (error) {
  16899. Logger.error('heanup pause', `投播暂停失败: ${error}`);
  16900. }
  16901. } else if (this.mIjkMediaPlayer.isPlaying()) {
  16902. // 本地播放器模式
  16903. this.savePlaybackPosition();
  16904. this.mIjkMediaPlayer.pause();
  16905. this.setProgress();
  16906. this.mDestroyPage = true;
  16907. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  16908. this.updateSessionPlayState(false)
  16909. this.playChange()
  16910. if (this.pipController) {
  16911. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  16912. PiPWindow.PiPControlStatus.PAUSE);
  16913. }
  16914. }
  16915. }
  16916. private stop() {
  16917. this.clearInitialSeekGuardTimer();
  16918. this.waitInitialSeekBeforeStart = false;
  16919. this.pendingMemorySeekPosition = 0;
  16920. this.isPlayerLoading = false;
  16921. this.savePlaybackPosition();
  16922. this.CONTROL_PlayStatus = PlayStatus.INIT;
  16923. this.mIjkMediaPlayer.stop();
  16924. this.mIjkMediaPlayer.release();
  16925. this.stopProgressTask();
  16926. this.updateSessionPlayState(false)
  16927. this.playChange()
  16928. this.watchStatus();
  16929. }
  16930. //保持记忆播放功能
  16931. private savePlaybackPosition() {
  16932. if (this.mIjkMediaPlayer != null) {
  16933. let position = this.mIjkMediaPlayer.getCurrentPosition();
  16934. // ToastUtil.showToast('保存记忆播放 = ' + position)
  16935. let duration = this.mIjkMediaPlayer.getDuration();
  16936. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  16937. position = Math.max(0, position - getCueTrackStartOffset(this.currentSong));
  16938. const cueDuration = getCueTrackDuration(this.currentSong);
  16939. if (cueDuration > 0) {
  16940. duration = cueDuration;
  16941. }
  16942. }
  16943. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  16944. // 如果播放位置接近视频末尾,则保存 position 为 0
  16945. const playbackPosition = (duration - position < threshold) ? 0 : position;
  16946. const memoryKey = this.activePlaybackMemoryKey || this.getPlaybackMemoryKey();
  16947. PreferencesUtil.putSync(memoryKey, playbackPosition);
  16948. }
  16949. }
  16950. private buildPlaybackMemoryKey(song?: VideoItem, playbackUrl?: string): string {
  16951. if (song && isRemoteCloudType(song.type)) {
  16952. const accountId = song.webdav_account_id || 'unknown';
  16953. const stablePath = song.remote_rel_path || song.id || song.baiduFsId || song.filePath || playbackUrl || '';
  16954. return `memory_play_remote:${song.type}:${accountId}:${stablePath}`;
  16955. }
  16956. if (song && isCueSplitItem(song)) {
  16957. return `memory_play_local_cue:${song.filePath}`;
  16958. }
  16959. return playbackUrl || '';
  16960. }
  16961. private getPlaybackMemoryKey(): string {
  16962. return this.buildPlaybackMemoryKey(this.currentSong, this.videoUrl);
  16963. }
  16964. private restoreRemotePlaybackPositionSafely(position: number, token: number, retryCount: number = 0): void {
  16965. if (token !== this.remoteRestoreSeekToken) {
  16966. return;
  16967. }
  16968. if (!this.mIjkMediaPlayer || position <= 0) {
  16969. if (this.waitInitialSeekBeforeStart) {
  16970. this.finishInitialSeekWait('invalid-memory-position', true);
  16971. }
  16972. return;
  16973. }
  16974. const duration = this.getActiveDuration();
  16975. const currentPos = this.mIjkMediaPlayer.getCurrentPosition();
  16976. let safePosition = position;
  16977. if (duration > 0) {
  16978. safePosition = Math.max(0, Math.min(position, duration - 500));
  16979. } else {
  16980. safePosition = Math.max(0, position);
  16981. }
  16982. if (safePosition <= 0) {
  16983. if (this.waitInitialSeekBeforeStart) {
  16984. this.finishInitialSeekWait('memory-position-too-small', true);
  16985. }
  16986. return;
  16987. }
  16988. if (retryCount === 0 && duration <= 0 && currentPos <= 0) {
  16989. Logger.info(TAG, `远程记忆seek提前尝试: pos=${safePosition}, duration=${duration}, current=${currentPos}`);
  16990. }
  16991. this.seekTo(safePosition + "", retryCount === 0 ? 'remote-memory-restore' : 'remote-memory-retry');
  16992. if (retryCount >= this.remoteMemorySeekMaxRetryCount) {
  16993. return;
  16994. }
  16995. setTimeout(() => {
  16996. if (token !== this.remoteRestoreSeekToken || !this.waitInitialSeekBeforeStart || !this.mIjkMediaPlayer) {
  16997. return;
  16998. }
  16999. const latestPos = this.mIjkMediaPlayer.getCurrentPosition();
  17000. if (Math.abs(latestPos - safePosition) <= 1500) {
  17001. return;
  17002. }
  17003. this.restoreRemotePlaybackPositionSafely(position, token, retryCount + 1);
  17004. }, this.remoteMemorySeekRetryIntervalMs);
  17005. }
  17006. //获取记忆播放功能
  17007. private restorePlaybackPosition() {
  17008. const position: number = this.pendingMemorySeekPosition > 0 ?
  17009. this.pendingMemorySeekPosition : PreferencesUtil.getNumberSync(this.getPlaybackMemoryKey(), 0);
  17010. if (!this.mIjkMediaPlayer || position <= 0) {
  17011. if (this.waitInitialSeekBeforeStart) {
  17012. this.finishInitialSeekWait('no-memory-position', true);
  17013. }
  17014. return;
  17015. }
  17016. const isRemoteSong = this.currentSong ? isRemoteCloudType(this.currentSong.type) : false;
  17017. if (isRemoteSong && this.videoUrl.includes('://')) {
  17018. const token = this.remoteRestoreSeekToken;
  17019. this.restoreRemotePlaybackPositionSafely(position, token);
  17020. return;
  17021. }
  17022. const duration = this.getActiveDuration();
  17023. let safePosition = position;
  17024. if (duration > 0) {
  17025. safePosition = Math.max(0, Math.min(position, duration - 500));
  17026. } else {
  17027. safePosition = Math.max(0, position);
  17028. }
  17029. if (safePosition <= 0) {
  17030. if (this.waitInitialSeekBeforeStart) {
  17031. this.finishInitialSeekWait('memory-position-too-small', true);
  17032. }
  17033. return;
  17034. }
  17035. this.seekTo(safePosition + "", isRemoteSong ? 'remote-memory-restore' : 'memory-restore');
  17036. }
  17037. private async seekTo(value: string, source: string = 'internal') {
  17038. // if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  17039. // ToastUtil.showToast('wma格式不支持拖动快进。')
  17040. // return
  17041. // }
  17042. // 如果是投播模式,使用 CastController 的 seek 方法
  17043. if (this.castControllerWrapper && this.isCastPlaying) {
  17044. try {
  17045. let seekPos = Number.parseInt(value);
  17046. const cueTrackItem = this.currentSong && isCueSplitItem(this.currentSong) ? this.currentSong : undefined;
  17047. const cueTrackStartOffset = cueTrackItem ? getCueTrackStartOffset(cueTrackItem) : 0;
  17048. const cueTrackEndOffset = cueTrackItem ? getCueTrackEndOffset(cueTrackItem) : 0;
  17049. const duration = this.getActiveDuration();
  17050. if (duration > 0) {
  17051. seekPos = Math.max(0, Math.min(seekPos, duration - 200));
  17052. }
  17053. if (cueTrackItem) {
  17054. seekPos += cueTrackStartOffset;
  17055. if (cueTrackEndOffset > cueTrackStartOffset) {
  17056. seekPos = Math.min(seekPos, cueTrackEndOffset - 200);
  17057. }
  17058. }
  17059. this.beginSeekTrace(source, seekPos);
  17060. this.isSeekTo = true;
  17061. Logger.info(
  17062. TAG,
  17063. `[seek] cast dispatch, source=${source}, target=${seekPos}, duration=${duration}, ` +
  17064. `uiDuration=${this.duration}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  17065. );
  17066. // 检查是否接近末尾
  17067. if (this.duration > 0 && seekPos >= this.duration - 500) {
  17068. Logger.warn('heanup seekTo', `快进位置接近末尾(${seekPos}ms >= ${this.duration}ms),可能触发播放完成`);
  17069. }
  17070. await this.castControllerWrapper.seek(seekPos);
  17071. Logger.info('heanup seekTo', `投播seek命令发送成功,位置: ${seekPos}ms`);
  17072. } catch (error) {
  17073. Logger.error('heanup seekTo', `投播seek失败: ${error}`);
  17074. }
  17075. } else {
  17076. // 本地播放器模式
  17077. let seekPos = Number.parseInt(value);
  17078. if (Number.isNaN(seekPos)) {
  17079. return;
  17080. }
  17081. const cueTrackItem = this.currentSong && isCueSplitItem(this.currentSong) ? this.currentSong : undefined;
  17082. const cueTrackStartOffset = cueTrackItem ? getCueTrackStartOffset(cueTrackItem) : 0;
  17083. const cueTrackEndOffset = cueTrackItem ? getCueTrackEndOffset(cueTrackItem) : 0;
  17084. const duration = this.getActiveDuration();
  17085. const isRemoteSong = this.currentSong ? isRemoteCloudType(this.currentSong.type) : false;
  17086. if (duration > 0) {
  17087. seekPos = Math.max(0, Math.min(seekPos, duration - 200));
  17088. } else if (seekPos < 0) {
  17089. seekPos = 0;
  17090. }
  17091. if (cueTrackItem) {
  17092. seekPos += cueTrackStartOffset;
  17093. if (cueTrackEndOffset > cueTrackStartOffset) {
  17094. seekPos = Math.min(seekPos, cueTrackEndOffset - 200);
  17095. }
  17096. }
  17097. if (isRemoteSong && duration <= 0 && seekPos > 0) {
  17098. Logger.warn(TAG, `seekTo 跳过未知时长远程seek: ${seekPos}ms`);
  17099. return;
  17100. }
  17101. if (isRemoteSong && duration <= 0) {
  17102. Logger.info(TAG, `seekTo 远程歌曲时长未知,仅允许起点seek: ${seekPos}ms`);
  17103. }
  17104. if (source !== 'internal') {
  17105. this.beginSeekTrace(source, seekPos);
  17106. }
  17107. this.isSeekTo = true
  17108. try {
  17109. if (isRemoteSong || source !== 'internal' || this.isSeekTraceActive()) {
  17110. Logger.info(
  17111. TAG,
  17112. `[seek] player dispatch, source=${source}, target=${seekPos}, activeDuration=${duration}, ` +
  17113. `playerDuration=${this.mIjkMediaPlayer.getDuration()}, current=${this.mIjkMediaPlayer.getCurrentPosition()}, ` +
  17114. `isPlaying=${this.mIjkMediaPlayer.isPlaying()}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  17115. );
  17116. }
  17117. this.mIjkMediaPlayer.seekTo(seekPos + "");
  17118. this.logSeekTrace('seek-dispatched', this.mIjkMediaPlayer.getCurrentPosition(), this.mIjkMediaPlayer.getDuration(), true);
  17119. this.setProgress()
  17120. } catch (error) {
  17121. Logger.error(TAG, `本地播放器seek失败: ${error}`);
  17122. this.logSeekTrace('seek-dispatch-error', undefined, undefined, true);
  17123. } finally {
  17124. this.isSeekTo = false
  17125. }
  17126. }
  17127. }
  17128. // 添加到下一首播放
  17129. private addToNextPlay(song: VideoItem) {
  17130. if (!this.debounce()) {
  17131. return;
  17132. }
  17133. if (this.currentSong) {
  17134. if (this.currentSong === song) {
  17135. ToastUtil.showToast('当前已经在播放这首歌了!')
  17136. return
  17137. }
  17138. }
  17139. // 如果未开始播放或队列为空
  17140. if (this.curIndex === -1 || this.songList.length === 0) {
  17141. this.songList = [song];
  17142. this.curIndex = 0;
  17143. this.doPlay(song)
  17144. return;
  17145. }
  17146. // 插入到当前索引+1的位置
  17147. const insertPos = this.curIndex + 1;
  17148. this.songList.splice(insertPos, 0, song);
  17149. this.songList = [...this.songList]; // 触发状态更新
  17150. this.sonDataSource.pushArrayData(this.songList)
  17151. ToastUtil.showToast('已添加至下一首播放')
  17152. }
  17153. //后退10s,可再设置设置默认几秒
  17154. async backForward() {
  17155. // 如果是投播模式,从currentTime2获取当前位置
  17156. let pos: number;
  17157. if (this.castController && this.isCastPlaying) {
  17158. pos = this.currentTime2 * 1000; // 使用秒转毫秒
  17159. Logger.info('heanup backForward', `投播模式当前位置: ${pos}ms`);
  17160. } else if (this.mIjkMediaPlayer) {
  17161. pos = this.mIjkMediaPlayer.getCurrentPosition();
  17162. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17163. pos = Math.max(0, pos - getCueTrackStartOffset(this.currentSong));
  17164. }
  17165. } else {
  17166. return;
  17167. }
  17168. let value = pos - Number(this.fastForwardSeconds) * 1000;
  17169. if (value < 0) {
  17170. value = 0;
  17171. }
  17172. await this.seekTo(value + "");
  17173. }
  17174. //快进10s,可再设置设置默认几秒
  17175. async fastForward() {
  17176. // 如果是投播模式,从currentTime2获取当前位置
  17177. let pos: number;
  17178. if (this.castController && this.isCastPlaying) {
  17179. pos = this.currentTime2 * 1000; // 使用秒转毫秒
  17180. Logger.info('heanup fastForward', `投播模式当前位置: ${pos}ms`);
  17181. } else if (this.mIjkMediaPlayer) {
  17182. pos = this.mIjkMediaPlayer.getCurrentPosition();
  17183. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17184. pos = Math.max(0, pos - getCueTrackStartOffset(this.currentSong));
  17185. }
  17186. } else {
  17187. return;
  17188. }
  17189. let value = pos + Number(this.fastForwardSeconds) * 1000;
  17190. // 限制不超过总时长
  17191. if (this.duration > 0 && value > this.duration) {
  17192. value = this.duration;
  17193. }
  17194. await this.seekTo(value + "");
  17195. }
  17196. //下一个
  17197. private async playNext() {
  17198. this.lyricController.setLyric(null)
  17199. this.lyricControllerXF.setLyric(null)
  17200. this.lyricControllerSingle.setLyric(null)
  17201. Logger.info('heanup playNext', '========== playNext 开始 ==========');
  17202. Logger.info('heanup playNext', `isCastPlaying=${this.isCastPlaying}, castControllerWrapper存在=${!!this.castControllerWrapper}`);
  17203. if (!this.debounce()) {
  17204. Logger.warn('heanup playNext', 'debounce() 返回 false,退出');
  17205. return;
  17206. }
  17207. Logger.info('heanup playNext', `playType=${this.playType}`);
  17208. if (this.playType == 3) { //3:随机播放
  17209. Logger.info('heanup playNext', '随机播放模式');
  17210. await this.randomPlay()
  17211. return;
  17212. }
  17213. if (ArrayUtil.isNotEmpty(this.songList)) {
  17214. if (this.curIndex >= this.songList.length - 1) {
  17215. // playType=0 或 3: 尝试加载更多或循环
  17216. // playType=4: 不循环,检查是否是最后一首
  17217. if (this.playType == 4) {
  17218. // 连续播放不循环模式:到达最后一首时停止播放
  17219. Logger.info('heanup playNext', '连续播放不循环模式:已到达最后一首,停止播放');
  17220. ToastUtil.showToast('已经是最后一首了');
  17221. this.showRePlay();
  17222. this.currentTime = this.stringForTime(this.getActiveDuration());
  17223. this.progressValue = this.PROGRESS_MAX_VALUE;
  17224. this.slideEnable = false;
  17225. this.stop();
  17226. return;
  17227. }
  17228. await this.tryLoadNextPageForPlayback();
  17229. }
  17230. if (this.curIndex >= this.songList.length - 1) {
  17231. // playType=4 不应该执行到这里,因为上面已经return了
  17232. this.curIndex = 0;
  17233. } else {
  17234. this.curIndex++;
  17235. }
  17236. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  17237. this.currentSong = this.songList[this.curIndex];
  17238. console.info('heanup playNext', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  17239. const nextLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  17240. const nextUrl = await this.resolvePlaybackUrlForCurrentSong('playNext');
  17241. if (!nextUrl) {
  17242. if (nextLoading) {
  17243. this.hideLoadIng();
  17244. }
  17245. return;
  17246. }
  17247. this.videoUrl = nextUrl;
  17248. this.artist = this.songList[this.curIndex].artist
  17249. this.name = this.songList[this.curIndex].name
  17250. //this.cover = this.songList[this.curIndex].pixelMapPath
  17251. console.info('heanup playNext 1 ', `this.isCastPlaying: ${ this.isCastPlaying}`)
  17252. console.info('heanup playNext 2 ', `this.castControllerWrapper: ${this.castControllerWrapper}`)
  17253. // 如果是投播模式,使用 CastController 播放下一首
  17254. if (this.castControllerWrapper) {
  17255. console.info('heanup playNext', '使用 CastController 播放下一首');
  17256. try {
  17257. const nextDuration = this.getSongDurationMs(this.currentSong);
  17258. if (nextDuration > 0) {
  17259. this.duration = nextDuration;
  17260. this.durationTime = Math.floor(nextDuration / 1000);
  17261. this.durationStringTime = secondToTime(this.durationTime);
  17262. this.totalTime = this.stringForTime(nextDuration);
  17263. this.avSessionController.setAVMetadataMusic(this.currentSong, nextDuration, this.lyricContent);
  17264. }
  17265. this.updateCastProgress(0);
  17266. await this.castControllerWrapper.playNext(this.songList, this.curIndex, this.videoUrl, nextDuration);
  17267. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  17268. if (nextLoading) {
  17269. this.hideLoadIng();
  17270. }
  17271. console.info('heanup playNext', 'CastController 播放下一首成功');
  17272. return;
  17273. } catch (error) {
  17274. console.error('heanup playNext', `CastController 播放下一首失败: ${error}`);
  17275. // 如果投播失败,回退到本地播放
  17276. this.isCastPlaying = false;
  17277. }
  17278. }
  17279. // 本地播放器模式,需要先stop
  17280. this.CONTROL_PlayStatus = PlayStatus.INIT;
  17281. this.stop();
  17282. if (nextLoading) {
  17283. this.showLoadIng();
  17284. }
  17285. this.changeImageAnimation()
  17286. }
  17287. }
  17288. changeImageAnimation() {
  17289. if(this.openSkipSongAnimate){
  17290. // 第一步:淡出动画
  17291. this.getUIContext()?.animateTo({
  17292. duration: 500,
  17293. curve: Curve.EaseOut,
  17294. }, () => {
  17295. this.opacityValueImage = 0.1;
  17296. if(this.isCoverRectangle){
  17297. this.scaleValueImage = 0.88
  17298. }
  17299. });
  17300. // 第二步:切换图片后淡入
  17301. setTimeout(() => {
  17302. this.cover = this.songList[this.curIndex].pixelMapPath
  17303. this.getUIContext()?.animateTo({
  17304. duration: 500,
  17305. curve: Curve.EaseIn,
  17306. }, () => {
  17307. this.opacityValueImage = 1;
  17308. this.scaleValueImage = 1 // 图标恢复到原始大小
  17309. this.startPlayOrResumePlay()
  17310. });
  17311. }, 500);
  17312. }else{
  17313. this.cover = this.songList[this.curIndex].pixelMapPath
  17314. this.startPlayOrResumePlay()
  17315. }
  17316. }
  17317. // 内部方法:提前缓存下一首
  17318. private async preloadNextSongInternal(): Promise<void> {
  17319. // 随机模式下传递已播放索引集合
  17320. if (this.playType === 3) {
  17321. this.preloadNextRandomIndex = await preloadNextSongIfNeeded(
  17322. this.songList,
  17323. this.curIndex,
  17324. this.playType,
  17325. this.playedIndices
  17326. );
  17327. } else {
  17328. this.preloadNextRandomIndex = await preloadNextSongIfNeeded(
  17329. this.songList,
  17330. this.curIndex,
  17331. this.playType
  17332. );
  17333. }
  17334. }
  17335. // 存储已播放的歌曲索引
  17336. private playedIndices: Set<number> = new Set();
  17337. // 存储已播放的本地歌曲路径(随机播放去重用)
  17338. private playedLocalFilePaths: Set<string> = new Set();
  17339. // 随机播放模式下的播放历史栈(记录实际播放顺序,用于"上一首"功能)
  17340. private randomPlayHistory: VideoItem[] = [];
  17341. //随机播放
  17342. private async randomPlay() {
  17343. // if (!this.debounce()) {
  17344. // return;
  17345. // }
  17346. // 网盘模式: 渐进式扩展播放库的随机播放
  17347. // 通过检查当前歌曲类型判断是否为网盘音乐(而非modeType,因为不同网盘类型modeType不同)
  17348. const isCloudSong = this.currentSong && isRemoteCloudType(this.currentSong.type);
  17349. if (isCloudSong) {
  17350. // 阈值常量
  17351. const UNPLAYED_THRESHOLD = 10; // 剩余未播放歌曲阈值
  17352. const LOAD_MORE_PAGES = 3; // 每次加载页数
  17353. // 获取网盘播放列表
  17354. const navidromeList = getNavidromeVideoItems();
  17355. const webdavList = getWebdavVideoItems();
  17356. const isNavidrome = navidromeList.length > 0;
  17357. const remoteList = isNavidrome ? navidromeList : webdavList;
  17358. if (remoteList.length > 0) {
  17359. // 将当前歌加入历史栈
  17360. if (this.currentSong) {
  17361. this.randomPlayHistory.unshift(this.currentSong);
  17362. if (this.randomPlayHistory.length > 50) {
  17363. this.randomPlayHistory = this.randomPlayHistory.slice(0, 50);
  17364. }
  17365. // 标记当前歌曲为已播放
  17366. markAsPlayed(this.currentSong.filePath);
  17367. Logger.info(TAG, `randomPlay(网盘模式): 将当前歌加入历史栈, 栈大小: ${this.randomPlayHistory.length}`);
  17368. }
  17369. // 检查未播放歌曲数量(仅Navidrome支持渐进式加载)
  17370. let unplayedCount = isNavidrome ? getUnplayedCount() : remoteList.length;
  17371. const totalCount = remoteList.length;
  17372. const playedCount = isNavidrome ? getPlayedCount() : 0;
  17373. Logger.info(TAG, `randomPlay(网盘模式): 总数${totalCount}, 已播放${playedCount}, 未播放${unplayedCount}`);
  17374. // 如果未播放数量不足阈值,且还有更多数据,触发加载更多页
  17375. if (isNavidrome && unplayedCount < UNPLAYED_THRESHOLD && hasMoreData()) {
  17376. Logger.info(TAG, `randomPlay(网盘模式): 未播放(${unplayedCount})不足阈值(${UNPLAYED_THRESHOLD}),触发加载更多`);
  17377. const loadSuccess = await triggerLoadMoreSongs(LOAD_MORE_PAGES);
  17378. if (loadSuccess) {
  17379. // 重新获取未播放数量
  17380. unplayedCount = getUnplayedCount();
  17381. Logger.info(TAG, `randomPlay(网盘模式): 加载完成,未播放数量更新为${unplayedCount}`);
  17382. }
  17383. }
  17384. // 从未播放歌曲中随机选择
  17385. let candidates: VideoItem[];
  17386. if (isNavidrome) {
  17387. candidates = getUnplayedSongs();
  17388. // 如果全部播放完,重置已播放记录
  17389. if (candidates.length === 0) {
  17390. Logger.info(TAG, 'randomPlay(网盘模式): 全部播放完毕,重置已播放记录');
  17391. clearPlayedHistory();
  17392. // 排除当前歌曲
  17393. const currentFilePath = this.currentSong?.filePath;
  17394. candidates = currentFilePath
  17395. ? getNavidromeVideoItems().filter(v => v.filePath !== currentFilePath)
  17396. : getNavidromeVideoItems();
  17397. }
  17398. } else {
  17399. // WebDAV模式:简单排除当前歌曲
  17400. const currentFilePath = this.currentSong?.filePath;
  17401. candidates = currentFilePath
  17402. ? remoteList.filter(v => v.filePath !== currentFilePath)
  17403. : remoteList;
  17404. }
  17405. if (candidates.length > 0) {
  17406. const randomIndex = Math.floor(Math.random() * candidates.length);
  17407. const randomSong = candidates[randomIndex];
  17408. // 标记为已播放
  17409. if (isNavidrome) {
  17410. markAsPlayed(randomSong.filePath);
  17411. }
  17412. Logger.info(TAG, `randomPlay(网盘模式): 从${candidates.length}首候选中随机选择: ${randomSong.name}`);
  17413. // 将选中的歌曲加入播放列表(如果不存在)
  17414. let nextIndex = this.songList.findIndex(song => song.filePath === randomSong.filePath);
  17415. if (nextIndex < 0) {
  17416. this.songList = [...this.songList, randomSong];
  17417. this.sonDataSource.pushArrayData(this.songList);
  17418. nextIndex = this.songList.length - 1;
  17419. }
  17420. this.curIndex = nextIndex;
  17421. this.playedIndices.add(this.curIndex);
  17422. this.CONTROL_PlayStatus = PlayStatus.INIT;
  17423. this.stop();
  17424. this.currentSong = randomSong;
  17425. const randomRemoteListLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  17426. const randomRemoteListUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-remote-list');
  17427. if (!randomRemoteListUrl) {
  17428. if (randomRemoteListLoading) {
  17429. this.hideLoadIng();
  17430. }
  17431. return;
  17432. }
  17433. this.videoUrl = randomRemoteListUrl;
  17434. this.name = this.currentSong.name;
  17435. this.artist = this.currentSong.artist;
  17436. this.changeImageAnimation();
  17437. return;
  17438. }
  17439. Logger.warn(TAG, 'randomPlay(网盘模式): 无可用候选歌曲,回退到默认随机逻辑');
  17440. }
  17441. }
  17442. if (this.currentSong) {
  17443. // 将当前歌加入到随机播放历史栈(在切换到新歌之前)
  17444. this.randomPlayHistory.unshift(this.currentSong);
  17445. // 限制历史栈大小,避免无限增长
  17446. if (this.randomPlayHistory.length > 50) {
  17447. this.randomPlayHistory = this.randomPlayHistory.slice(0, 50);
  17448. }
  17449. Logger.info(TAG, `randomPlay: 将当前歌加入历史栈, 栈大小: ${this.randomPlayHistory.length}`);
  17450. const isCurrentRemote = isRemoteCloudType(this.currentSong.type);
  17451. const currentFilePath = this.currentSong.filePath;
  17452. if (isCurrentRemote) {
  17453. const remoteOptions: RandomSongQueryOptions = {
  17454. type: this.currentSong.type,
  17455. excludeFilePaths: currentFilePath ? [currentFilePath] : []
  17456. };
  17457. const randomRemoteSong = await this.table.queryRandomSong(remoteOptions);
  17458. if (randomRemoteSong) {
  17459. // 验证并修正webdav_account_id
  17460. if (randomRemoteSong.webdav_account_id) {
  17461. const manager = RemoteDriveManager.getInstance();
  17462. const account = await manager.getWebDavAccountById(randomRemoteSong.webdav_account_id);
  17463. if (!account) {
  17464. Logger.warn(TAG, `随机播放的歌曲账号ID无效: ${randomRemoteSong.webdav_account_id}, 尝试查找同类型账号`);
  17465. // 获取所有账号,查找相同类型的账号
  17466. const allAccounts = manager.getAllWebDavAccounts();
  17467. let foundAccount: WebDavAccount | null = null;
  17468. for (let i = 0; i < allAccounts.length; i++) {
  17469. if (allAccounts[i].webType === randomRemoteSong.type) {
  17470. foundAccount = allAccounts[i];
  17471. break;
  17472. }
  17473. }
  17474. if (foundAccount && foundAccount.id) {
  17475. Logger.info(TAG, `找到同类型账号,更新webdav_account_id: ${randomRemoteSong.webdav_account_id} -> ${foundAccount.id}`);
  17476. randomRemoteSong.webdav_account_id = foundAccount.id.toString();
  17477. // 更新数据库记录
  17478. await this.table.updateWebDavAccountId(randomRemoteSong.filePath, foundAccount.id.toString());
  17479. } else {
  17480. Logger.error(TAG, `无法找到类型为${randomRemoteSong.type}的账号,跳过此歌曲`);
  17481. return;
  17482. }
  17483. }
  17484. }
  17485. let nextIndex = this.songList.findIndex(song => song.filePath === randomRemoteSong.filePath);
  17486. if (nextIndex < 0) {
  17487. this.songList = [...this.songList, randomRemoteSong];
  17488. this.sonDataSource.pushArrayData(this.songList);
  17489. nextIndex = this.songList.length - 1;
  17490. }
  17491. this.curIndex = nextIndex;
  17492. this.playedIndices.add(this.curIndex);
  17493. this.CONTROL_PlayStatus = PlayStatus.INIT;
  17494. this.stop();
  17495. this.currentSong = randomRemoteSong;
  17496. const randomRemoteDbLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  17497. const randomRemoteUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-remote-db');
  17498. if (!randomRemoteUrl) {
  17499. if (randomRemoteDbLoading) {
  17500. this.hideLoadIng();
  17501. }
  17502. return;
  17503. }
  17504. this.videoUrl = randomRemoteUrl;
  17505. this.name = this.currentSong.name;
  17506. this.artist = this.currentSong.artist;
  17507. this.changeImageAnimation();
  17508. return;
  17509. }
  17510. Logger.warn(TAG, '随机播放未获取到网盘歌曲,回退到列表随机');
  17511. } else {
  17512. if (currentFilePath) {
  17513. this.playedLocalFilePaths.add(currentFilePath);
  17514. }
  17515. // 根据modeType构建不同的查询选项
  17516. const localOptions: RandomSongQueryOptions = {
  17517. type: CommonConstants.TYPE_LOCAL,
  17518. excludeFilePaths: Array.from(this.playedLocalFilePaths)
  17519. };
  17520. Logger.info(TAG, `randomPlay: 本地播放模式, modeType=${this.modeType}, currentPlaylistSongFilePaths.length=${this.currentPlaylistSongFilePaths.length}, currentPath=${this.currentPath}`);
  17521. // modeType==0: 文件夹模式,添加parentPath过滤
  17522. if (this.modeType === 0 && this.currentPath) {
  17523. localOptions.parentPath = this.currentPath;
  17524. Logger.info(TAG, `randomPlay: 文件夹模式, parentPath=${this.currentPath}`);
  17525. }
  17526. // modeType==4: 歌单模式,添加playlistSongFilePaths
  17527. else if (this.modeType === 4 && this.currentPlaylistSongFilePaths.length > 0) {
  17528. localOptions.playlistSongFilePaths = this.currentPlaylistSongFilePaths;
  17529. Logger.info(TAG, `randomPlay: 歌单模式,歌曲数量=${this.currentPlaylistSongFilePaths.length}, 前3首=${this.currentPlaylistSongFilePaths.slice(0, 3).join(', ')}`);
  17530. } else if (this.modeType === 4) {
  17531. Logger.warn(TAG, `randomPlay: 歌单模式但没有歌曲路径列表! currentPlaylistSongFilePaths.length=${this.currentPlaylistSongFilePaths.length}`);
  17532. }
  17533. let randomLocalSong = await this.table.queryRandomSong(localOptions);
  17534. if (!randomLocalSong) {
  17535. this.playedLocalFilePaths.clear();
  17536. if (currentFilePath) {
  17537. this.playedLocalFilePaths.add(currentFilePath);
  17538. }
  17539. const fallbackLocalOptions: RandomSongQueryOptions = {
  17540. type: CommonConstants.TYPE_LOCAL,
  17541. excludeFilePaths: currentFilePath ? [currentFilePath] : []
  17542. };
  17543. // fallback时也要保持modeType的过滤条件
  17544. if (this.modeType === 0 && this.currentPath) {
  17545. fallbackLocalOptions.parentPath = this.currentPath;
  17546. } else if (this.modeType === 4 && this.currentPlaylistSongFilePaths.length > 0) {
  17547. fallbackLocalOptions.playlistSongFilePaths = this.currentPlaylistSongFilePaths;
  17548. }
  17549. randomLocalSong = await this.table.queryRandomSong(fallbackLocalOptions);
  17550. }
  17551. if (randomLocalSong !== null) {
  17552. const selectedLocalSong = randomLocalSong;
  17553. let nextIndex = this.songList.findIndex(song => song.filePath === selectedLocalSong.filePath);
  17554. if (nextIndex < 0) {
  17555. this.songList = [...this.songList, selectedLocalSong];
  17556. this.sonDataSource.pushArrayData(this.songList);
  17557. nextIndex = this.songList.length - 1;
  17558. }
  17559. this.curIndex = nextIndex;
  17560. this.playedIndices.add(this.curIndex);
  17561. this.CONTROL_PlayStatus = PlayStatus.INIT;
  17562. this.stop();
  17563. this.currentSong = selectedLocalSong;
  17564. const randomLocalUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-local-db');
  17565. if (!randomLocalUrl) {
  17566. return;
  17567. }
  17568. this.videoUrl = randomLocalUrl;
  17569. this.name = this.currentSong.name;
  17570. this.artist = this.currentSong.artist;
  17571. this.changeImageAnimation();
  17572. return;
  17573. }
  17574. Logger.warn(TAG, '随机播放未获取到本地歌曲,回退到列表随机');
  17575. }
  17576. }
  17577. if (ArrayUtil.isNotEmpty(this.songList)) {
  17578. if (this.curIndex >= 0 && this.curIndex < this.songList.length) {
  17579. this.playedIndices.add(this.curIndex);
  17580. }
  17581. if (this.songList.length > 3) {
  17582. // 优先使用预缓存的随机索引(仅网盘播放时)
  17583. const nextSong = this.songList[this.preloadNextRandomIndex >= 0 ? this.preloadNextRandomIndex : 0];
  17584. const isNextRemote = nextSong && isRemoteCloudType(nextSong.type);
  17585. const isCurrentRemote = this.currentSong && isRemoteCloudType(this.currentSong.type);
  17586. if (this.preloadNextRandomIndex >= 0 && this.preloadNextRandomIndex < this.songList.length && isNextRemote && isCurrentRemote) {
  17587. Logger.info('heanup randomPlay', `使用预缓存的随机索引: ${this.preloadNextRandomIndex} (网盘播放)`);
  17588. this.curIndex = this.preloadNextRandomIndex;
  17589. this.playedIndices.add(this.curIndex);
  17590. this.preloadNextRandomIndex = -1; // 重置预缓存索引
  17591. // 立即预缓存下一首,避免下次点击时没有预缓存
  17592. void this.preloadNextSongInternal();
  17593. } else {
  17594. // 如果没有预缓存索引,则正常随机选择
  17595. // 如果所有歌曲都播放过一次,清空已播放索引集合
  17596. if (this.playedIndices.size === this.songList.length) {
  17597. this.playedIndices.clear();
  17598. }
  17599. // 随机选择一个未播放的歌曲索引
  17600. let newIndex: number;
  17601. // 添加超时机制防止无限循环
  17602. let attempt = 0;
  17603. const maxAttempts = 100; // 根据需求调整
  17604. do {
  17605. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  17606. attempt++;
  17607. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  17608. if (attempt >= maxAttempts) {
  17609. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  17610. newIndex = Math.floor(Math.random() * this.songList.length);
  17611. }
  17612. this.curIndex = newIndex;
  17613. this.playedIndices.add(newIndex);
  17614. }
  17615. } else {
  17616. // 当歌曲数量小于或等于3时,直接播放下一首
  17617. if (this.curIndex == this.songList.length - 1) {
  17618. this.curIndex = 0;
  17619. } else {
  17620. this.curIndex++;
  17621. }
  17622. }
  17623. this.CONTROL_PlayStatus = PlayStatus.INIT;
  17624. this.stop();
  17625. this.currentSong = this.songList[this.curIndex];
  17626. const randomFallbackLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  17627. const randomFallbackUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-fallback');
  17628. if (!randomFallbackUrl) {
  17629. if (randomFallbackLoading) {
  17630. this.hideLoadIng();
  17631. }
  17632. return;
  17633. }
  17634. this.videoUrl = randomFallbackUrl;
  17635. this.name = this.songList[this.curIndex].name;
  17636. this.artist = this.songList[this.curIndex].artist
  17637. // this.cover = this.songList[this.curIndex].pixelMapPath
  17638. this.changeImageAnimation()
  17639. // 预缓存下一首(包括网盘和本地)
  17640. void this.preloadNextSongInternal();
  17641. }
  17642. }
  17643. private async playIndex(index: number) {
  17644. if (!this.debounce()) {
  17645. return;
  17646. }
  17647. if (ArrayUtil.isNotEmpty(this.songList)) {
  17648. this.curIndex = index;
  17649. this.currentSong = this.songList[index];
  17650. const playIndexLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  17651. const playIndexUrl = await this.resolvePlaybackUrlForCurrentSong('playIndex');
  17652. if (!playIndexUrl) {
  17653. if (playIndexLoading) {
  17654. this.hideLoadIng();
  17655. }
  17656. return;
  17657. }
  17658. this.videoUrl = playIndexUrl;
  17659. this.name = this.currentSong.name
  17660. this.artist = this.currentSong.artist
  17661. // 如果是投播模式,需要为投播设备准备当前歌曲
  17662. if (this.castController && this.isCastPlaying) {
  17663. Logger.info('heanup playIndex', '投播模式播放指定歌曲,不调用本地stop()');
  17664. this.initQueueItem();
  17665. await this.prepare();
  17666. if (playIndexLoading) {
  17667. this.hideLoadIng();
  17668. }
  17669. this.cover = this.currentSong.pixelMapPath;
  17670. return;
  17671. }
  17672. // 本地播放器模式,需要先stop
  17673. this.CONTROL_PlayStatus = PlayStatus.INIT;
  17674. this.stop();
  17675. if (playIndexLoading) {
  17676. this.showLoadIng();
  17677. }
  17678. this.changeImageAnimation()
  17679. }
  17680. }
  17681. //上一个
  17682. private async playPrevious() {
  17683. if (!this.debounce()) {
  17684. return;
  17685. }
  17686. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  17687. this.randomModePlayFromHistory()
  17688. return;
  17689. }
  17690. if (this.curIndex == 0) {
  17691. this.curIndex = this.songList.length - 1;
  17692. } else {
  17693. this.curIndex--;
  17694. }
  17695. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  17696. this.currentSong = this.songList[this.curIndex];
  17697. Logger.info('heanup playPrevious', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  17698. // 验证并修正webdav_account_id(针对远程类型歌曲)
  17699. if (isRemoteCloudType(this.currentSong.type) && this.currentSong.webdav_account_id) {
  17700. const manager = RemoteDriveManager.getInstance();
  17701. const account = await manager.getWebDavAccountById(this.currentSong.webdav_account_id);
  17702. if (!account) {
  17703. Logger.warn(TAG, `playPrevious: 歌曲账号ID无效: ${this.currentSong.webdav_account_id}, 尝试查找同类型账号`);
  17704. // 获取所有账号,查找相同类型的账号
  17705. const allAccounts = manager.getAllWebDavAccounts();
  17706. let foundAccount: WebDavAccount | null = null;
  17707. for (let i = 0; i < allAccounts.length; i++) {
  17708. if (allAccounts[i].webType === this.currentSong.type) {
  17709. foundAccount = allAccounts[i];
  17710. break;
  17711. }
  17712. }
  17713. if (foundAccount && foundAccount.id) {
  17714. Logger.info(TAG, `playPrevious: 找到同类型账号,更新webdav_account_id: ${this.currentSong.webdav_account_id} -> ${foundAccount.id}`);
  17715. this.currentSong.webdav_account_id = foundAccount.id.toString();
  17716. // 更新数据库记录
  17717. await this.table.updateWebDavAccountId(this.currentSong.filePath, foundAccount.id.toString());
  17718. } else {
  17719. Logger.error(TAG, `playPrevious: 无法找到类型为${this.currentSong.type}的账号,跳过此歌曲`);
  17720. // 跳过无效账号的歌曲,继续查找上一首
  17721. if (this.curIndex == 0) {
  17722. this.curIndex = this.songList.length - 1;
  17723. } else {
  17724. this.curIndex--;
  17725. }
  17726. this.currentSong = this.songList[this.curIndex];
  17727. }
  17728. }
  17729. }
  17730. const previousLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  17731. const previousUrl = await this.resolvePlaybackUrlForCurrentSong('playPrevious');
  17732. if (!previousUrl) {
  17733. if (previousLoading) {
  17734. this.hideLoadIng();
  17735. }
  17736. return;
  17737. }
  17738. this.videoUrl = previousUrl;
  17739. this.name = this.songList[this.curIndex].name
  17740. this.artist = this.songList[this.curIndex].artist
  17741. // 如果是投播模式,使用 CastController 切换上一首
  17742. if (this.castControllerWrapper) {
  17743. Logger.info('heanup playPrevious', '投播模式播放上一首,不调用本地stop()');
  17744. try {
  17745. const prevDuration = this.getSongDurationMs(this.currentSong);
  17746. if (prevDuration > 0) {
  17747. this.duration = prevDuration;
  17748. this.durationTime = Math.floor(prevDuration / 1000);
  17749. this.durationStringTime = secondToTime(this.durationTime);
  17750. this.totalTime = this.stringForTime(prevDuration);
  17751. this.avSessionController.setAVMetadataMusic(this.currentSong, prevDuration, this.lyricContent);
  17752. }
  17753. this.updateCastProgress(0);
  17754. await this.castControllerWrapper.playPrevious(this.songList, this.curIndex, this.videoUrl, prevDuration);
  17755. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  17756. if (previousLoading) {
  17757. this.hideLoadIng();
  17758. }
  17759. } catch (error) {
  17760. Logger.error('heanup playPrevious', `CastController 播放上一首失败: ${error}`);
  17761. this.isCastPlaying = false;
  17762. }
  17763. this.cover = this.songList[this.curIndex].pixelMapPath;
  17764. return;
  17765. }
  17766. // 本地播放器模式,需要先stop
  17767. this.CONTROL_PlayStatus = PlayStatus.INIT;
  17768. this.stop();
  17769. if (previousLoading) {
  17770. this.showLoadIng();
  17771. }
  17772. this.changeImageAnimation()
  17773. }
  17774. //随机播放模式下点击上一首: 播放刚刚播放过的那一首
  17775. private async randomModePlayFromHistory() {
  17776. if (this.randomPlayHistory.length >= 1) {
  17777. // 播放历史栈的第一首(刚刚播放过的)
  17778. const prevSong = this.randomPlayHistory[0];
  17779. Logger.info('heanup randomModePlayFromHistory', `从随机播放历史栈获取歌曲: ${prevSong.name}, type: ${prevSong.type}, 栈大小: ${this.randomPlayHistory.length}`);
  17780. // 从栈中移除这首歌(因为即将播放它,它应该成为当前歌,而不是历史)
  17781. this.randomPlayHistory.shift();
  17782. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  17783. this.CONTROL_PlayStatus = PlayStatus.INIT;
  17784. this.stop();
  17785. // 验证并修正webdav_account_id(针对远程类型歌曲)
  17786. if (isRemoteCloudType(prevSong.type) && prevSong.webdav_account_id) {
  17787. const manager = RemoteDriveManager.getInstance();
  17788. const account = await manager.getWebDavAccountById(prevSong.webdav_account_id);
  17789. if (!account) {
  17790. Logger.warn(TAG, `randomModePlayFromHistory: 歌曲账号ID无效: ${prevSong.webdav_account_id}, 尝试查找同类型账号`);
  17791. const allAccounts = manager.getAllWebDavAccounts();
  17792. let foundAccount: WebDavAccount | null = null;
  17793. for (let i = 0; i < allAccounts.length; i++) {
  17794. if (allAccounts[i].webType === prevSong.type) {
  17795. foundAccount = allAccounts[i];
  17796. break;
  17797. }
  17798. }
  17799. if (foundAccount && foundAccount.id) {
  17800. Logger.info(TAG, `randomModePlayFromHistory: 找到同类型账号,更新webdav_account_id: ${prevSong.webdav_account_id} -> ${foundAccount.id}`);
  17801. prevSong.webdav_account_id = foundAccount.id.toString();
  17802. await this.table.updateWebDavAccountId(prevSong.filePath, foundAccount.id.toString());
  17803. } else {
  17804. Logger.error(TAG, `randomModePlayFromHistory: 无法找到类型为${prevSong.type}的账号`);
  17805. // 无法播放这首歌,继续尝试下一首历史记录
  17806. if (this.randomPlayHistory.length >= 1) {
  17807. this.randomModePlayFromHistory();
  17808. return;
  17809. } else {
  17810. // 历史记录为空,无法继续
  17811. ToastUtil.showToast('没有更多历史记录');
  17812. return;
  17813. }
  17814. }
  17815. }
  17816. }
  17817. this.currentSong = prevSong;
  17818. const historyLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  17819. const historyUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-history');
  17820. if (!historyUrl) {
  17821. if (historyLoading) {
  17822. this.hideLoadIng();
  17823. }
  17824. return;
  17825. }
  17826. this.videoUrl = historyUrl;
  17827. this.cover = this.currentSong.pixelMapPath
  17828. this.artist = this.currentSong.artist
  17829. this.name = this.currentSong.name;
  17830. console.info('onecold startPlayOrResumePlay randomModePlayFromHistory')
  17831. this.startPlayOrResumePlay();
  17832. } else {
  17833. ToastUtil.showToast('随机播放模式暂无历史记录');
  17834. }
  17835. }
  17836. debounce() {
  17837. const delay = 600;
  17838. let cur = new Date().getTime();
  17839. if (cur - this.last > delay) {
  17840. this.last = cur;
  17841. return true;
  17842. }
  17843. return false;
  17844. }
  17845. /**
  17846. * Sets whether the screen is a constant based on the playback status.
  17847. */
  17848. watchStatus() {
  17849. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  17850. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  17851. this.windowClass.setWindowKeepScreenOn(true);
  17852. } else {
  17853. this.windowClass.setWindowKeepScreenOn(false);
  17854. }
  17855. }
  17856. /**
  17857. * Volume gesture method onActionStart.
  17858. *
  17859. * @param event Gesture event.
  17860. */
  17861. private customDialogComponentIdMM: number = 0
  17862. @Builder
  17863. customDialogComponentMM() {
  17864. Column() {
  17865. Row() {
  17866. Blank()
  17867. Text('验证密码')
  17868. .fontSize(22)
  17869. .fontColor($r('app.color.pri_bg'))
  17870. .margin({ top: 18 })
  17871. Blank()
  17872. Image($r('app.media.close'))
  17873. .fillColor(Color.White)
  17874. .margin({ top: 18, right: 18 })
  17875. .width(20)
  17876. .onClick(() => {
  17877. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  17878. })
  17879. }
  17880. .width('100%') // 使Row占据整个宽度
  17881. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  17882. Verify({
  17883. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  17884. });
  17885. }.height('60%')
  17886. .backgroundColor($r('app.color.index_background'))
  17887. .justifyContent(FlexAlign.SpaceBetween)
  17888. }
  17889. private handleVerifyCompleted(isSuccess: boolean) {
  17890. if (isSuccess) {
  17891. console.log('验证成功');
  17892. // 在这里处理验证成功后的逻辑
  17893. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  17894. this.currentPath = this.lockPath
  17895. this.getSortedFiles(this.currentPath)
  17896. } else {
  17897. // console.log('验证失败');
  17898. ToastUtil.showToast('验证失败')
  17899. }
  17900. }
  17901. private showVerifyDialog() {
  17902. promptAction.openCustomDialog({
  17903. transition: TransitionEffect.asymmetric(
  17904. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  17905. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  17906. ,
  17907. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  17908. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  17909. ),
  17910. builder: () => {
  17911. this.customDialogComponentMM()
  17912. },
  17913. isModal: true,
  17914. autoCancel: true,
  17915. maskColor: Color.Transparent,
  17916. alignment: DialogAlignment.Bottom,
  17917. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  17918. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  17919. console.log("dialog onWillDismiss")
  17920. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  17921. dismissDialogAction.dismiss()
  17922. }
  17923. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  17924. dismissDialogAction.dismiss()
  17925. }
  17926. }
  17927. }).then((dialogId: number) => {
  17928. this.customDialogComponentIdMM = dialogId
  17929. })
  17930. }
  17931. //左滑操作 移动文件 重命名 删除等操作
  17932. @Builder
  17933. DeleteButton(item: VideoItem, index: number, filePath: string) {
  17934. Row() {
  17935. //加入收藏
  17936. // Button() {
  17937. // Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  17938. // .fillColor(Color.White)
  17939. // .width(20)
  17940. // }
  17941. // .width(40)
  17942. // .height(40)
  17943. // .type(ButtonType.Circle)
  17944. // .backgroundColor(this.themeColor)
  17945. // .margin(5)
  17946. // .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  17947. // .onClick(() => {
  17948. // if (item) {
  17949. // this.doFav(item)
  17950. // }
  17951. // })
  17952. //加入下一首播放
  17953. Button() {
  17954. Image($r('app.media.next_to_play'))
  17955. .fillColor(Color.White)
  17956. .width(20)
  17957. }
  17958. .width(40)
  17959. .height(40)
  17960. .type(ButtonType.Circle)
  17961. .backgroundColor(this.themeColor)
  17962. .margin(5)
  17963. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  17964. .onClick(() => {
  17965. this.addToNextPlay(item);
  17966. })
  17967. //复制文件
  17968. Button() {
  17969. Image($r('app.media.copy'))
  17970. .fillColor(Color.White)
  17971. .width(20)
  17972. }
  17973. .width(40)
  17974. .height(40)
  17975. .type(ButtonType.Circle)
  17976. .backgroundColor(this.themeColor)
  17977. .margin(5)
  17978. .id(filePath + 'copy')
  17979. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  17980. .onClick(() => {
  17981. this.showCopyDialog(false, item, index, filePath + 'copy');
  17982. })
  17983. //移动文件
  17984. Button() {
  17985. Image($r('app.media.cut'))
  17986. .fillColor(Color.White)
  17987. .width(20)
  17988. }
  17989. .width(40)
  17990. .height(40)
  17991. .type(ButtonType.Circle)
  17992. .backgroundColor(this.themeColor)
  17993. .margin(5)
  17994. .id(filePath)
  17995. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  17996. .onClick(() => {
  17997. this.showCutDialog(false, item, index, filePath);
  17998. })
  17999. Button() {
  18000. Image($r('app.media.cut_current'))
  18001. .fillColor(Color.White)
  18002. .width(20)
  18003. }
  18004. .width(40)
  18005. .height(40)
  18006. .type(ButtonType.Circle)
  18007. .backgroundColor(this.themeColor)
  18008. .margin(5)
  18009. .id(filePath + 'current')
  18010. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  18011. (this.isHasDir ? Visibility.Visible : Visibility.None))
  18012. .onClick(() => {
  18013. this.showCutDialog(true, item, index, filePath + 'current');
  18014. })
  18015. //重命名
  18016. // Button() {
  18017. // Image($r('app.media.rename2'))
  18018. // .fillColor(Color.White)
  18019. // .width(20)
  18020. // }
  18021. // .width(40)
  18022. // .height(40)
  18023. // .type(ButtonType.Circle)
  18024. // .backgroundColor(this.themeColor)
  18025. // .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  18026. // (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  18027. // item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  18028. // .margin(5)
  18029. // .onClick(() => {
  18030. // this.showReNameDialog(item, index + '', filePath)
  18031. //
  18032. // })
  18033. Button() {
  18034. Image($r('app.media.delete2'))
  18035. .fillColor(Color.White)
  18036. .width(20)
  18037. }
  18038. .width(40)
  18039. .height(40)
  18040. .type(ButtonType.Circle)
  18041. .backgroundColor(this.themeColor)
  18042. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  18043. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  18044. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  18045. .margin({ left:5,top:5,bottom:5,right:20} )
  18046. .onClick(() => {
  18047. this.selectSingleItemForDelete(item)
  18048. this.showWarnIsDelete()
  18049. // this.showWarnIsDeleteFile(item, index + '', filePath)
  18050. })
  18051. // Button() {
  18052. // Image($r('app.media.share2'))
  18053. // .fillColor(Color.White)
  18054. // .width(20)
  18055. // }
  18056. // .width(40)
  18057. // .height(40)
  18058. // .type(ButtonType.Circle)
  18059. // .backgroundColor(this.themeColor)
  18060. // .margin(5)
  18061. // .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  18062. // .onClick(() => {
  18063. // Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  18064. // })
  18065. }
  18066. }
  18067. /**
  18068. * 穿山甲banner广告
  18069. */
  18070. // private declare bannerAd: CSJNativeExpressAd;
  18071. // @State private status: string = "未加载"
  18072. // @State private isShowAd: boolean = false
  18073. // private declare mAdSlot: AdSlot;
  18074. // private mBiddingAdm = '' //服务端bidding才需要设置
  18075. // private expressLoadAdListener: NativeExpressAdListener = {
  18076. // /**
  18077. // * 加载失败的回调
  18078. // *
  18079. // * @param code
  18080. // * @param message
  18081. // */
  18082. // onError: (code: number, message: string) => {
  18083. // console.error("加载广告失败,code=" + code + ",message=" + message);
  18084. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  18085. // },
  18086. //
  18087. // /**
  18088. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  18089. // *
  18090. // * @param ads 返回的广告列表
  18091. // */
  18092. //
  18093. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  18094. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  18095. // if (ads && ads.length > 0) {
  18096. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  18097. // ad.setExpressInteractionListener({
  18098. // /**
  18099. // *广告的点击回调
  18100. // * @param type 广告的交互类型
  18101. // */
  18102. // onAdClicked: (type: number) => {
  18103. // console.log("BannerExpressAdPage==onAdClicked......");
  18104. // },
  18105. //
  18106. // /**
  18107. // * 广告的展示回调 每个广告仅回调一次
  18108. // * @param type 广告的交互类型
  18109. // */
  18110. // onAdShow: (type: number) => {
  18111. // console.log("BannerExpressAdPage==onAdShow......");
  18112. // },
  18113. //
  18114. // /**
  18115. // * 模板渲染失败
  18116. // */
  18117. // onRenderFail: (code: number, msg: string) => {
  18118. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  18119. // },
  18120. //
  18121. // /**
  18122. // * 模板渲染成功
  18123. // * @param width 返回view的宽 单位 vp
  18124. // * @param height 返回view的高 单位 vp
  18125. // */
  18126. // onRenderSuccess: (width: number, height: number) => {
  18127. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  18128. // this.bannerAd = ad;
  18129. // this.status = "广告加载完成待展示";
  18130. //
  18131. // this.showBannerAd()
  18132. // }
  18133. // })
  18134. // //渲染广告
  18135. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  18136. // this.setDislikeCallback(ad); //设置dislike
  18137. // ad.render(this.getUIContext())
  18138. // this.status = "广告加载中...";
  18139. // });
  18140. // }
  18141. // }
  18142. // }
  18143. //
  18144. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  18145. // ad.setDislikeCallback({
  18146. // /**
  18147. // * dislike show
  18148. // */
  18149. // onShow: () => {
  18150. // console.log("BannerExpressAdPage==dislike......show");
  18151. // },
  18152. //
  18153. // /**
  18154. // * @param position 选择的位置
  18155. // * @param value 选择的内容
  18156. // * @param enforceRemove 是否强制关闭广告
  18157. // */
  18158. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  18159. // this.isShowAd = false;
  18160. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  18161. // ",enforce=" + enforceRemove);
  18162. // },
  18163. //
  18164. // /**
  18165. // * 点击取消
  18166. // */
  18167. // onCancel: () => {
  18168. // console.log("BannerExpressAdPage==dislike......onCancel");
  18169. // }
  18170. //
  18171. // })
  18172. // }
  18173. /**
  18174. * 加载Banner广告
  18175. */
  18176. loadBannerAd(rit: string) {
  18177. // if (Utility.isNoble()) {
  18178. // return
  18179. // }
  18180. // if (!Utility.isPassInstallTime(2)) {
  18181. // return
  18182. // }
  18183. // this.isShowAd = false;
  18184. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  18185. // this.mAdSlot = new AdSlotBuilder()
  18186. // .setCodeId(rit)
  18187. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  18188. // .setAdCount(1)
  18189. // .setBidAdm(this.mBiddingAdm)
  18190. // .build()
  18191. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  18192. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  18193. // this.status = "广告加载中..."
  18194. }
  18195. /**
  18196. * 展示Banner广告
  18197. */
  18198. // showBannerAd() {
  18199. // if (!this.bannerAd) {
  18200. // return
  18201. // }
  18202. // this.isShowAd = true
  18203. // this.status = "已展示"
  18204. // }
  18205. /**
  18206. * 穿山甲广告代码结束
  18207. */
  18208. /**
  18209. * 处理歌单播放请求
  18210. */
  18211. private syncWebdavQueueWithoutRestart(): void {
  18212. try {
  18213. if (!this.currentSong || !isWebDavType(this.currentSong.type)) {
  18214. return;
  18215. }
  18216. const webdavList = getWebdavVideoItems();
  18217. if (!ArrayUtil.isNotEmpty(webdavList)) {
  18218. return;
  18219. }
  18220. const currentPath = this.currentSong.filePath;
  18221. let targetIndex = webdavList.findIndex((item: VideoItem) => item.filePath === currentPath);
  18222. if (targetIndex < 0) {
  18223. const memoryIndex = getWebdavCurrentPlayIndex();
  18224. if (memoryIndex >= 0 && memoryIndex < webdavList.length) {
  18225. targetIndex = memoryIndex;
  18226. }
  18227. }
  18228. if (targetIndex < 0) {
  18229. targetIndex = 0;
  18230. }
  18231. this.songList = [...webdavList];
  18232. this.currentSongList = [...webdavList];
  18233. this.sonDataSource.pushArrayData(this.songList);
  18234. this.currentPlaylistSongFilePaths = this.songList.map(song => song.filePath);
  18235. this.curIndex = targetIndex;
  18236. PreferencesUtil.putSync('LastMusicList', this.songList);
  18237. Logger.info(TAG, `WebDAV播放队列已刷新,当前索引=${this.curIndex}, 队列长度=${this.songList.length}`);
  18238. } catch (error) {
  18239. Logger.error(TAG, `刷新WebDAV播放队列失败: ${(error as Error).message}`);
  18240. }
  18241. }
  18242. private async handlePlaylistPlayRequest(playlistId: string, playlistName:
  18243. string, songFilePaths: string[], startIndex: number, isJump: boolean, songCount?: number) {
  18244. try {
  18245. const totalCount = songCount ?? songFilePaths.length;
  18246. Logger.info(`heanup 处理歌单播放请求: ${playlistName}, 已加载: ${songFilePaths.length}, 服务端总数: ${totalCount}, 开始索引: ${startIndex}`)
  18247. // 检查是否为WebDAV播放请求
  18248. if (playlistId === 'webdav-playlist') {
  18249. Logger.info(`heanup 检测到WebDAV播放请求,从内存读取videoItems`)
  18250. // 从全局内存读取videoItems数据
  18251. const videoItems = getWebdavVideoItems();
  18252. const currentPlayIndex = getWebdavCurrentPlayIndex();
  18253. Logger.info(`heanup 从内存读取到WebDAV歌曲列表,长度:${videoItems.length},索引:${currentPlayIndex}`)
  18254. if (videoItems && videoItems.length > 0) {
  18255. // 验证webdav_account_id设置情况
  18256. const accountIds = videoItems.map(item => item.webdav_account_id).filter(id => id);
  18257. Logger.info(`heanup 有 ${accountIds.length}/${videoItems.length} 首歌曲设置了webdav_account_id`)
  18258. if(isJump){
  18259. this.setShowPlayTrue()//显示播放页
  18260. }
  18261. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName, totalCount)
  18262. return
  18263. } else {
  18264. return
  18265. }
  18266. }
  18267. if (playlistId === 'navidrome-playlist') {
  18268. Logger.info(`heanup 检测到Navidrome播放请求,从内存读取videoItems`);
  18269. const videoItems = getNavidromeVideoItems();
  18270. const currentPlayIndex = getNavidromeCurrentPlayIndex();
  18271. Logger.info(`heanup Navidrome歌曲列表长度: ${videoItems.length}, 服务端总数: ${totalCount}`);
  18272. if (videoItems && videoItems.length > 0) {
  18273. if(isJump){
  18274. this.setShowPlayTrue()//显示播放页
  18275. }
  18276. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName, totalCount);
  18277. return;
  18278. } else {
  18279. Logger.warn('heanup Navidrome播放请求缺少歌曲数据');
  18280. return;
  18281. }
  18282. }
  18283. // 从数据库重新加载这些歌曲,使用索引记录位置以保持顺序
  18284. const songMap: Map<number, VideoItem> = new Map()
  18285. let completedQueries = 0
  18286. Logger.info(`heanup 开始从数据库查询 ${songFilePaths.length} 首歌曲`)
  18287. // 遍历所有文件路径,使用索引记录位置
  18288. for (let i = 0; i < songFilePaths.length; i++) {
  18289. const filePath = songFilePaths[i]
  18290. const index = i
  18291. // Logger.info(`heanup 正在查询歌曲[${index}]: ${filePath}`)
  18292. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  18293. const queryPromise = this.table.queryVideoByFilePath(filePath)
  18294. // Logger.info(`heanup 创建了查询Promise,开始等待结果[${index}]: ${filePath}`)
  18295. queryPromise.then((videoItem) => {
  18296. completedQueries++
  18297. // Logger.info(`heanup 查询Promise返回结果[${index}]: ${filePath}, 找到歌曲: ${videoItem ? videoItem.name : 'null'}`)
  18298. if (videoItem) {
  18299. // 使用索引作为key保存到Map中,保持原始顺序
  18300. songMap.set(index, videoItem)
  18301. // Logger.info(`heanup 从数据库找到歌曲[${index}]: ${videoItem.name} (${completedQueries}/${songFilePaths.length})`)
  18302. } else {
  18303. Logger.warn(`heanup 数据库中未找到歌曲[${index}]: ${filePath} (${completedQueries}/${songFilePaths.length})`)
  18304. }
  18305. // 检查是否所有歌曲都已加载完成
  18306. if (completedQueries === songFilePaths.length) {
  18307. // Logger.info(`heanup 所有数据库查询完成,共找到 ${songMap.size} 首歌曲`)
  18308. // 按照索引顺序重建歌曲数组
  18309. const songs: VideoItem[] = []
  18310. for (let j = 0; j < songFilePaths.length; j++) {
  18311. const song = songMap.get(j)
  18312. if (song) {
  18313. songs.push(song)
  18314. // Logger.info(`heanup 按顺序添加歌曲[${j}]: ${song.name}`)
  18315. }
  18316. }
  18317. Logger.info(`heanup 最终歌曲列表顺序: ${songs.map((s, idx) => `[${idx}]${s.name}`).join(', ')}`)
  18318. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  18319. }
  18320. }).catch((error: Error) => {
  18321. completedQueries++
  18322. Logger.error(`heanup 查询歌曲失败[${index}]: ${filePath}, 错误: ${error.message} (${completedQueries}/${songFilePaths.length})`)
  18323. // 即使出错也要检查是否完成所有查询
  18324. if (completedQueries === songFilePaths.length) {
  18325. Logger.info(`heanup 所有数据库查询完成(包含错误),共找到 ${songMap.size} 首歌曲`)
  18326. // 按照索引顺序重建歌曲数组
  18327. const songs: VideoItem[] = []
  18328. for (let j = 0; j < songFilePaths.length; j++) {
  18329. const song = songMap.get(j)
  18330. if (song) {
  18331. songs.push(song)
  18332. }
  18333. }
  18334. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  18335. }
  18336. })
  18337. }
  18338. } catch (error) {
  18339. Logger.error('heanup 处理简化歌单播放请求失败: ' + error)
  18340. ToastUtil.showToast('播放失败')
  18341. }
  18342. }
  18343. /**
  18344. * 完成歌单加载并开始播放
  18345. */
  18346. private finishLoadingPlaylist(songs: VideoItem[], startIndex: number, playlistName: string, totalCount?: number) {
  18347. if (songs.length === 0) {
  18348. Logger.error('heanup 没有找到任何可播放的歌曲')
  18349. ToastUtil.showToast('没有找到可播放的歌曲')
  18350. return
  18351. }
  18352. this.songList = songs
  18353. this.currentSongList = songs // 同步更新 currentSongList
  18354. this.sonDataSource.pushArrayData(songs)
  18355. this.sonDataSource.notifyDataReload()
  18356. this.curIndex = startIndex
  18357. // 保存歌单的歌曲路径列表,用于随机播放
  18358. this.currentPlaylistSongFilePaths = songs.map(song => song.filePath);
  18359. const actualTotal = totalCount ?? songs.length;
  18360. // 如果是网盘播放,保存服务端总数到全局存储
  18361. if (totalCount && totalCount > 0 && songs.length > 0) {
  18362. const firstSong = songs[0];
  18363. if (firstSong && (isNavidromeType(firstSong.type) ||
  18364. isJellyfinType(firstSong.type) ||
  18365. isEmbyType(firstSong.type) ||
  18366. isAudioStationType(firstSong.type) ||
  18367. isPlexType(firstSong.type) ||
  18368. isDaoLiYuType(firstSong.type))) {
  18369. setNavidromeTotalCount(totalCount);
  18370. Logger.info('heanup finishLoadingPlaylist', `已保存服务端总数到全局存储: ${totalCount}`);
  18371. }
  18372. }
  18373. Logger.info('heanup finishLoadingPlaylist', `保存歌单歌曲路径列表,已加载=${this.currentPlaylistSongFilePaths.length}, 服务端总数=${actualTotal}`);
  18374. if (songs[startIndex]) {
  18375. // 确保当前播放的歌曲也更新到存储
  18376. AppStorage.setOrCreate('currentSong', songs[startIndex])
  18377. // 设置isFromSonPlayList=true,避免doPlay方法重新从全局列表构建播放列表
  18378. this.doPlay(songs[startIndex], startIndex, true)
  18379. }
  18380. PreferencesUtil.putSync('LastMusicList', this.songList)
  18381. // ToastUtil.showToast(`开始播放歌单: ${playlistName}`)
  18382. }
  18383. }
  18384. //视频气泡窗口的布局
  18385. @Builder
  18386. function customPopupBuilder(dataBu: BubbleBean) {
  18387. List() {
  18388. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  18389. ListItem() {
  18390. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  18391. Row() {
  18392. Column() {
  18393. Image(dataBu.imageRes[index])
  18394. .height(28)
  18395. .fillColor(dataBu.color)
  18396. .alignSelf(ItemAlign.Center)
  18397. }
  18398. .width(32)
  18399. Text(item)
  18400. .padding({
  18401. top: 10,
  18402. bottom: 10,
  18403. right: 10,
  18404. left: 10
  18405. })
  18406. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  18407. .textAlign(TextAlign.Start)
  18408. .width("100%")
  18409. }
  18410. }
  18411. .backgroundColor($r('app.color.settings_background_main'))
  18412. .margin({ top: 6, bottom: 6 })
  18413. }
  18414. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  18415. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  18416. TransitionEffect.scale({ x: 0, y: 0 })))
  18417. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  18418. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  18419. .onClick(() => {
  18420. dataBu.onItemClick?.(index)
  18421. })
  18422. })
  18423. }
  18424. .scrollBar(BarState.Off)
  18425. .width(120)
  18426. .divider({
  18427. strokeWidth: 1,
  18428. color: "#22FFFFFF"
  18429. })
  18430. }
  18431. // Function to calculate a hash for the file list
  18432. function simpleHash(fileList: string[]): string {
  18433. let hash = 0;
  18434. const str = fileList.join(',');
  18435. for (let i = 0; i < str.length; i++) {
  18436. const char = str.charCodeAt(i);
  18437. hash = (hash << 5) - hash + char;
  18438. hash |= 0; // Convert to 32bit integer
  18439. }
  18440. return hash.toString();
  18441. }
  18442. interface MoreItem {
  18443. id: number;
  18444. image: Resource;
  18445. title: string;
  18446. }
  18447. //视频气泡窗口的布局
  18448. @Builder
  18449. function cutPopupBuilder(dataBu: BubbleBean) {
  18450. Column() {
  18451. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  18452. .padding({
  18453. top: 10,
  18454. bottom: 10,
  18455. right: 10,
  18456. left: 10
  18457. })
  18458. .textAlign(TextAlign.Start)
  18459. .width(160)
  18460. .fontWeight(666)
  18461. .fontSize(16)
  18462. List() {
  18463. ForEach(dataBu.data, (item: string, index: number) => {
  18464. ListItem() {
  18465. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  18466. Row() {
  18467. Column() {
  18468. Image($r('app.media.music_group'))
  18469. .height(28)
  18470. .fillColor(dataBu.color)
  18471. .alignSelf(ItemAlign.Center)
  18472. }
  18473. .width(32)
  18474. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  18475. .padding({
  18476. top: 10,
  18477. bottom: 10,
  18478. right: 10,
  18479. left: 10
  18480. })
  18481. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  18482. .fontSize(15)
  18483. }
  18484. }
  18485. .backgroundColor(Color.Transparent)
  18486. .margin({ top: 7, bottom: 7 })
  18487. }
  18488. .onClick(() => {
  18489. dataBu.onItemClick?.(index)
  18490. })
  18491. })
  18492. }
  18493. .scrollBar(BarState.Off)
  18494. .width(150)
  18495. .divider({
  18496. strokeWidth: 1,
  18497. color: "#22FFFFFF"
  18498. })
  18499. }
  18500. .height(300)
  18501. .padding({
  18502. bottom: 30
  18503. })
  18504. }
  18505. @Concurrent
  18506. function buildAlphabetIndexTask(items: Array<AlphaTaskItem>, sortType: number, isShowFileName: boolean): Array<string> {
  18507. const alphabetSet = new Set<string>()
  18508. for (const item of items) {
  18509. let text = isShowFileName ? (item.fileName || '') :
  18510. (item.type != CommonConstants.TYPE_IS_DIR && item.pyStr) ? item.pyStr : (item.name || '')
  18511. if (sortType === 0 || sortType == 1) {
  18512. text = item.artist || ''
  18513. } else if (sortType === 2 || sortType == 3) {
  18514. text = item.album || ''
  18515. }
  18516. if (text && text.length > 0) {
  18517. const first = getFirstLetter(text)
  18518. if (!alphabetSet.has(first)) {
  18519. alphabetSet.add(first)
  18520. }
  18521. }
  18522. }
  18523. const sorted = Array.from(alphabetSet).sort((a, b) => {
  18524. if (sortType === 4 || sortType == 0 || sortType == 2 || sortType == 6) {
  18525. return a.localeCompare(b)
  18526. }
  18527. return b.localeCompare(a)
  18528. })
  18529. return sorted
  18530. }
  18531. function getFileDirName(filePath: string,rootPath:string): string{
  18532. if(filePath===rootPath){
  18533. return '首页'
  18534. }
  18535. let result = FileUtil.getFileName(filePath)
  18536. if(StrUtil.isEmpty(result))
  18537. return ''
  18538. if(result.startsWith('.'))
  18539. result = result.replace(/\./g, '')
  18540. return result
  18541. }
  18542. //只扫描当前目录下文件(不扫描子文件夹)的方法
  18543. @Concurrent
  18544. async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
  18545. const table: MediaTable = new MediaTable(context);
  18546. try {
  18547. // 直接获取当前目录下的文件列表
  18548. const files = FileUtil.listFileSync(dirPath);
  18549. await Promise.all(files.map(async (file) => {
  18550. const fPath = `${dirPath}/${file}`;
  18551. // 跳过目录,只处理文件
  18552. if (FileUtil.isDirectory(fPath)) {
  18553. return;
  18554. }
  18555. // 跳过特定格式文件
  18556. if (fPath.endsWith('.lrc') || fPath.endsWith('.srt')) {
  18557. return;
  18558. }
  18559. // 检查是否为媒体文件
  18560. if (Utility.isMeidaByExtension(fPath)) {
  18561. let mType = CommonConstants.TYPE_LOCAL;
  18562. if (fPath.includes(lockPath)) {
  18563. mType = CommonConstants.TYPE_LOCK;
  18564. }
  18565. const mediaItem = await Utility.uriGetMusicAssetsFromFile(
  18566. context, fPath, mType, true
  18567. );
  18568. table.insert(mediaItem, (id: number) => {
  18569. // 插入回调函数
  18570. }, cover_api);
  18571. }
  18572. }));
  18573. } catch (error) {
  18574. console.error(' 扫描当前目录失败:', error);
  18575. }
  18576. }
  18577. //内嵌标签后更新库
  18578. @Concurrent
  18579. async function updateInfoDb(
  18580. context: Context,
  18581. filePath: string,
  18582. titleStr: string,
  18583. artistStr: string,
  18584. albumStr: string,
  18585. lyricConStr: string,
  18586. yearStr: string,
  18587. genreStr: string,
  18588. trackStr: string,
  18589. albumArtistStr: string,
  18590. composerStr: string,
  18591. lyricistStr: string,
  18592. commentStr: string,
  18593. discStr: string,
  18594. ): Promise<boolean> {
  18595. const table: MediaTable = new MediaTable(context);
  18596. await new Promise<void>((resolve, reject) => {
  18597. table.getRdbStore(context, (err:Error) => {
  18598. err ? reject(err) : resolve();
  18599. });
  18600. });
  18601. return await new Promise<boolean>((resolve) => {
  18602. table.updateMediaInfo(filePath, titleStr, artistStr, albumStr, lyricConStr,
  18603. yearStr, genreStr, trackStr, albumArtistStr, composerStr, lyricistStr, commentStr, discStr,
  18604. (success: boolean, error?: string) => {
  18605. if (success) {
  18606. console.log("onecold 编辑信息成功,数据库已同步");
  18607. } else {
  18608. console.error("onecold 编辑信息数据库失败原因: " + error);
  18609. }
  18610. resolve(success);
  18611. });
  18612. });
  18613. }
  18614. @Concurrent
  18615. async function replaceLocalMusicCoverTask(
  18616. context: Context,
  18617. filePath: string,
  18618. sandboxCoverPath: string
  18619. ): Promise<boolean> {
  18620. const coverResult: boolean = await changeMusicCover(context, filePath, sandboxCoverPath, true, '');
  18621. if (!coverResult) {
  18622. return false;
  18623. }
  18624. const table: MediaTable = new MediaTable(context);
  18625. await new Promise<void>((resolve, reject) => {
  18626. table.getRdbStore(context, (err: Error) => {
  18627. err ? reject(err) : resolve();
  18628. });
  18629. });
  18630. return await new Promise<boolean>((resolve) => {
  18631. table.updateCustomCoverPath(filePath, fileUri.getUriFromPath(sandboxCoverPath),
  18632. (success: boolean, _error?: string) => {
  18633. resolve(success);
  18634. });
  18635. });
  18636. }