LocalMusic.ets 734 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580
  1. import TitleBar from './TitleBar'
  2. import { curves, display, MenuModifier, PiPWindow, promptAction, router, SymbolGlyphModifier, window } from '@kit.ArkUI';
  3. import { VideoItem } from '../viewmodel/VideoItem';
  4. import { LengthMetrics, SegmentButton,SegmentButtonOptions } from '@kit.ArkUI';
  5. import { getWebdavVideoItems, getWebdavCurrentPlayIndex } from '../pages/WebDavMainPage';
  6. import {
  7. getNavidromeVideoItems,
  8. getNavidromeCurrentPlayIndex,
  9. getUnplayedSongs,
  10. getUnplayedCount,
  11. markAsPlayed,
  12. clearPlayedHistory,
  13. getPlayedCount,
  14. getNavidromeTotalCount,
  15. setNavidromeTotalCount
  16. } from '../common/util/NavidromePlaylistStore';
  17. import { getFindVideoItems, getFindCurrentPlayIndex } from '../common/util/FindPlaylistStore';
  18. import { triggerLoadMoreSongs, hasMoreData } from '../common/util/NavidromeRandomLoader';
  19. import {
  20. ImplOnBufferingUpdateListener,
  21. ImplOnCompletionListener,
  22. ImplOnErrorListener,
  23. ImplOnInfoListener,
  24. ImplOnPreparedListener,
  25. ImplOnSeekCompleteListener,
  26. ImplOnTimedTextListener,
  27. ImplOnVideoSizeChangedListener
  28. } from '../common/IjkPlayerListenerImpls';
  29. import {
  30. ButtonFancyModifier,
  31. ImageFancyModifier,
  32. ShadowModifier,
  33. SymbolGlyphFancyModifier } from '../common/util/AttributeModifierUtil'
  34. import {
  35. AppUtil,
  36. ArrayUtil,
  37. Base64Util,
  38. DateUtil,
  39. DeviceUtil,
  40. FileUtil,
  41. GlobalContext,
  42. LogUtil,
  43. MD5,
  44. PreferencesUtil,
  45. RandomUtil,
  46. StrUtil,
  47. ToastUtil
  48. } from '@pura/harmony-utils';
  49. import { imagePathToPixelMap } from '../common/util/CommUtils';
  50. import LyricUtil from '../common/util/LyricUtil';
  51. import { unifiedDataChannel, uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData';
  52. import { CommonConstants } from '../common/constants/CommonConstants';
  53. import { BaiduConstants } from '../common/constants/BaiduConstants';
  54. import { EventConstants } from '../common/constants/EventConstants';
  55. import Logger from '../common/util/Logger';
  56. import { http } from '@kit.NetworkKit';
  57. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  58. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  59. import { BubbleBean } from '../viewmodel/BubbleBean';
  60. import { PopupPosition, XPopup } from '@chinalike/popup';
  61. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  62. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  63. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  64. import { MessageEvents, util, worker, ErrorEvent, JSON } from '@kit.ArkTS';
  65. import { Verify } from './Verify';
  66. import { taskpool } from '@kit.ArkTS';
  67. import { RotatingCover } from './RotatingCover';
  68. import { SpectrumView } from './spectrum/SpectrumView';
  69. import { PlayingIndicator } from './PlayingIndicator';
  70. import { PointLightButton } from './PointLight/PointLightButton';
  71. import { PlayConstants } from '../common/constants/PlayConstants';
  72. import { effectKit } from '@kit.ArkGraphics2D';
  73. import { ColorConversion } from '../common/util/ColorConversion';
  74. import { Lyric, LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  75. import { AvSessionController } from '../controller/AvSessionController';
  76. import { EqualizerManager } from '../common/util/EqualizerManager';
  77. import { EqualizerViewWithCallback } from './EqualizerView';
  78. import { CastController, CastControllerCallbacks } from '../controller/CastController';
  79. import { repairAudioMetadata, convertDsfToWav, getApiLyric,changeMusicCover} from '../common/util/MusicTagUtils';
  80. import { extractHwMediaMetadata, FFMpegTags,Utility } from '../common/util/Utility';
  81. import { TagsContentCover } from '../view/TagsContentCover';
  82. import {
  83. DeviceChangeReason,
  84. IjkMediaPlayer,
  85. InterruptEvent,
  86. InterruptHintType,
  87. LogUtils,
  88. OnBufferingUpdateListener,
  89. OnCompletionListener,
  90. OnErrorListener,
  91. OnInfoListener,
  92. OnPreparedListener,
  93. OnSeekCompleteListener,
  94. OnTimedTextListener,
  95. OnVideoSizeChangedListener
  96. } from '@ohos/ijkplayer';
  97. import { PlayStatus } from '../common/PlayStatus';
  98. import fs from '@ohos.file.fs';
  99. import { image } from '@kit.ImageKit';
  100. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  101. import { media } from '@kit.MediaKit';
  102. import { UniversalDetector } from '@ohos/juniversalchardet';
  103. import { SettingPage } from '../pages/SettingPage';
  104. import { secondToTime,getTransverterText } from '../common/util/CommUtils';
  105. import { CommonConstants2 } from '../common/util/CommonConstants2';
  106. import { hilog } from '@kit.PerformanceAnalysisKit';
  107. import { LazyDataSource } from '../common/util/LazyDataSource';
  108. import MediaTable, { PageQueryOptions, PageQueryResult, RandomSongQueryOptions } from '../common/util/MediaTable';
  109. import FileDeletionWatcher from '../common/util/FileDeletionWatcher';
  110. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  111. import { ringtone } from '@kit.RingtoneKit';
  112. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  113. import { resourceManager } from '@kit.LocalizationKit';
  114. import { deviceInfo } from '@kit.BasicServicesKit';
  115. import '../common/network/RemoteCacheRegistry';
  116. import { ServerLogUtil } from '../common/util/ServerLogUtil';
  117. import { lyricService, SongData } from '../common/service/LyricService';
  118. import { shouldResolveRemoteLyricOnPlay, tryResolveRemotePlaybackLyric } from '../common/util/RemotePlaybackLyricUtil';
  119. import {
  120. cloneVideoItem,
  121. preloadNextSongIfNeeded,
  122. setVideoUrlForSong,
  123. getTypeOrder,
  124. isWebDavType,
  125. isSmbType,
  126. isNavidromeType,
  127. isFtpType,
  128. isBaiduType,
  129. isJellyfinType,
  130. isEmbyType,
  131. isAudioStationType,
  132. isPlexType,
  133. isRemoteCloudType,
  134. mergeCoverWithPriority,
  135. WorkerEditMusicResult,
  136. WebDavMetadataUpdatePayload,
  137. isDaoLiYuType
  138. } from '../common/util/RemotePlayerUtil';
  139. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  140. import app from '@system.app';
  141. import { TextNodeController } from './PipLyricTextBuilder';
  142. import { IndexerView } from './IndexerView';
  143. import { KeyCode } from '@kit.InputKit';
  144. import { KnockController } from '../controller/KnockController';
  145. import { DeleteComptent } from '../view/DeleteComptent';
  146. import { ABLoopComptent } from '../view/ABLoopComptent';
  147. import { FixMessyView } from '../view/FixMessyView';
  148. import {
  149. parseCueFile,
  150. CueTrack,
  151. CueInfo,
  152. getCueTrackDuration,
  153. getCueTrackEndOffset,
  154. getCueTrackStartOffset,
  155. importCueTracks,
  156. isCueSplitItem
  157. } from '../common/util/CueUtils';
  158. import { CueComptent } from '../view/CueComptent';
  159. import { SearchHistoryUtil } from '../common/util/SearchHistoryUtil';
  160. import { IsoExtractComptent } from '../view/IsoExtractComptent';
  161. import PlaylistTable from '../common/util/PlaylistTable';
  162. import { showAddToPlaylistDialog } from '../dialog/AddToPlaylistDialog';
  163. import { showCreatePlaylistDialog } from '../dialog/PlaylistDialog';
  164. import { convertPlaylistSongsToVideoItems, emptyView,updateAllSongsSortOrder } from '../pages/PlaylistDetailPage';
  165. import { Playlist, PlaylistSong } from '../viewmodel/Playlist';
  166. import { Song } from '../viewmodel/Song';
  167. import { WebDavAccount } from '../viewmodel/WebDavAccount';
  168. import { SongType } from '../common/enums/SongType';
  169. import { RemoteDriveManager, WebDavAuthInfo as WebDavManagerAuthInfo,
  170. buildHttpHeadersWithWebDav,
  171. WebDavAuthItem} from '../common/util/RemoteDriveManager';
  172. import PermissionUtil from '../common/util/PermissionUtil'
  173. import { EditAudio, setRingTone } from './EditAudio';
  174. import { ExtractAccompaniment } from './ExtractAccompaniment';
  175. import { ExtractAudioFromVideo } from './ExtractAudioFromVideo';
  176. import { AudioFormatConverter } from './AudioFormatConverter';
  177. import { MergeAudio } from './MergeAudio';
  178. import { AIVoiceSeparation } from './AIVoiceSeparation';
  179. import { WebDavUrlUtil } from '../common/util/WebDavUrlUtil';
  180. import { ChangeTone } from './ChangeTone';
  181. import {
  182. hdsEffect,
  183. HdsVisualComponent,
  184. HdsSceneController,
  185. HdsSceneType,
  186. HdsVisualComponentAttribute,
  187. } from '@kit.UIDesignKit';
  188. import { GlobalAlphabetIndexerModifier } from '../Styels/GlobalStyles'
  189. import { getFirstLetter } from '../Constants';
  190. import { audio } from '@kit.AudioKit';
  191. import { PointLightDefaultButton } from './PointLight/PointLightDeFaultButton';
  192. import { CoverThumbCache } from '../common/util/CoverThumbCache';
  193. import { LyricCopySheet } from './LyricCopySheet';
  194. import {
  195. IsoArchiveAudioEntry,
  196. IsoExtractFailureDetail,
  197. IsoExtractProgressMessage,
  198. IsoExtractTaskResult,
  199. listIsoAudioEntriesTask,
  200. extractIsoAudioEntriesTask
  201. } from '../common/util/IsoArchiveUtil';
  202. const TAG = 'LocalMusic';
  203. const HICAR_LOG_TAG = 'HiCarWindow';
  204. const PREF_PLAY_COVER_SCALE_GUIDE_SHOWN = 'play_cover_scale_guide_show';
  205. function logHiCarWindow(message: string): void {
  206. void ServerLogUtil.info(HICAR_LOG_TAG, message);
  207. }
  208. export interface WorkerMetadataPayload {
  209. originFilePath: string;
  210. originId?: string;
  211. bit_rate?: string;
  212. duration?: string;
  213. sampleRate?: string;
  214. mimeType?: string;
  215. md5Str?: string;
  216. videoSize?: number;
  217. size?: string;
  218. pixelMapPath?: string;
  219. artist?: string;
  220. album?: string;
  221. name?: string;
  222. lyricContent?: string;
  223. bits_per_raw_sample?: string;
  224. channels?: string;
  225. channel_layout?: string;
  226. start_time?: string;
  227. genre?: string;
  228. year?: string;
  229. probe_score?: number;
  230. track?: string;
  231. disc?: string;
  232. ALBUMARTIST?: string;
  233. COMPOSER?: string;
  234. COMMENT?: string;
  235. LYRICIST?: string;
  236. nb_streams?: number;
  237. nb_programs?: number;
  238. error?: string;
  239. }
  240. interface WorkerMessageScanDone {
  241. code: 101;
  242. data: Record<string, never>;
  243. }
  244. interface WorkerMessageMediaList {
  245. code: 102;
  246. data: Array<VideoItem>;
  247. totalCount: number;
  248. }
  249. interface WorkerMessageArtistList {
  250. code: 103;
  251. data1: Map<string, Array<VideoItem>>;
  252. data2: Array<VideoItem>;
  253. totalCount: number;
  254. }
  255. interface WorkerMessageAlbumList {
  256. code: 104;
  257. data1: Map<string, Array<VideoItem>>;
  258. data2: Array<VideoItem>;
  259. totalCount: number;
  260. }
  261. interface WorkerMessageMetadata {
  262. code: 105;
  263. data: WorkerMetadataPayload;
  264. }
  265. interface WorkerMessageEditResult {
  266. code: 106;
  267. data: WorkerEditMusicResult;
  268. }
  269. interface AlphaTaskItem {
  270. type: number;
  271. name?: string;
  272. pyStr?: string;
  273. fileName?: string;
  274. artist?: string;
  275. album?: string;
  276. }
  277. type LocalMusicWorkerMessage =
  278. WorkerMessageScanDone
  279. | WorkerMessageMediaList
  280. | WorkerMessageArtistList
  281. | WorkerMessageAlbumList
  282. | WorkerMessageMetadata
  283. | WorkerMessageEditResult;
  284. /**
  285. * 歌单播放事件数据
  286. */
  287. interface PlaylistEventData {
  288. playlistId: string;
  289. playlistName: string;
  290. songCount: number;
  291. startIndex: number;
  292. songFilePaths: string[];
  293. isJump: boolean;
  294. webDavAuthInfo?: WebDavAuthItem; // 新增WebDAV认证信息
  295. }
  296. const DEFAULT_INDEX =
  297. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  298. 'X', 'Y', 'Z']
  299. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  300. // 元数据提取状态追踪
  301. const metadataExtractionInFlight: Map<string, Promise<void>> = new Map();
  302. // setVideoUrlForSong 函数已移至 MusicPlayerUtil.ets
  303. // 定义接口
  304. interface HiCarAspectRatio {
  305. ratio: number;
  306. name: string;
  307. }
  308. interface GeneratedObjectLiteralInterface_1 {
  309. assetId: string;
  310. title: string;
  311. artist: string;
  312. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  313. mediaUri: string;
  314. // 该字段大写,音频'AUDIO',视频'VIDEO'
  315. mediaType: string;
  316. mediaSize: number;
  317. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  318. startPosition: number;
  319. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  320. duration: number;
  321. albumCoverUri: string;
  322. albumTitle: string;
  323. appName: string;
  324. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  325. drmScheme: string;
  326. }
  327. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  328. const ITEM_HEIGHT: number = 65; // 列表项中高度
  329. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  330. /**
  331. * 排序模式枚举
  332. * 定义各种排序方式的升序基准值
  333. */
  334. export enum SortMode {
  335. ByArtist = 0, // 按艺术家升序
  336. ByAlbum = 2, // 按专辑升序
  337. ByName = 4, // 按名称升序
  338. ByTime = 6, // 按时间升序
  339. ByAddTime = 7, // 按添加时间(只有降序)
  340. ByCount = 8, // 按数量升序
  341. ByDiscTrack = 10 // 按碟片编号-音轨号升序
  342. }
  343. //功能强大的音乐播放器
  344. @Preview
  345. @Component
  346. export struct LocalMusic {
  347. @State default_layout:number = 0
  348. @State isGeKongPlayNext: boolean = true//是否开启隔空手势播放下一首
  349. @State bluetoothDisconnectPause: boolean = false // 蓝牙设备断开暂停
  350. @State isBluetoothConnected: boolean = false // 蓝牙连接状态
  351. @State bluetoothLyricEnabled: boolean = false // 蓝牙歌词开关
  352. @State bluetoothLyricMode: number = 0 // 蓝牙歌词显示模式
  353. private lastBluetoothLyricLine: string = '' // 上一次发送的歌词行
  354. @State showFindLocation: boolean = true
  355. @StorageProp("EnablePointLight") enablePointLight: boolean = true
  356. @State showSimple: boolean = true//开启沉浸模式
  357. @State isPaging: boolean = true;//是否分页加载机制
  358. @State isCoverRectangle: boolean = true;
  359. @State showZMIndex: boolean = false //是否右侧显示字母索引
  360. private prevOffsetY: number = 0; // 记录上一次的Y轴偏移量
  361. @State autoHideTitle: boolean = true //滚动自动隐藏标题栏
  362. // 字母表
  363. @State alphaBet: string[] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
  364. 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  365. @State alphaBetStyle: GlobalAlphabetIndexerModifier = new GlobalAlphabetIndexerModifier()
  366. @State selectAlphaBetIndex: number = 0
  367. @State isShowAlphaBet: boolean = false
  368. @State isScrolling: boolean = false
  369. @State isTouchingAlphaBet: boolean = false
  370. @State alphabetHeight: number = 0
  371. public enableShowAlphabet: boolean = true // 是否显示字母表
  372. private alphaBetHideTimer: number = 0
  373. private alphaBetRebuildTimer: number = 0
  374. private alphaBetDirty: boolean = false
  375. private alphaBetCacheKey: string = ''
  376. private alphaBetBuildVersion: number = 0
  377. @State isShowPrecious: boolean = false //播控条显示上一首按钮
  378. //背景两侧流光控制器
  379. @State sceneBgController: HdsSceneController|undefined = deviceInfo.sdkApiVersion>=20
  380. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  381. new HdsSceneController()
  382. .setSceneParams({
  383. backgroundMaskColors: [Color.Green, Color.Red],
  384. firstEdgeFlowLight: {
  385. startPos: 0,
  386. endPos: 0.5,
  387. color: Color.Red
  388. },
  389. secondEdgeFlowLight: {
  390. startPos: 0,
  391. endPos: -0.5,
  392. color: Color.Green
  393. }
  394. }) : undefined;
  395. //背景流光控制器
  396. @State bgController: hdsEffect.ShaderEffectController|undefined = deviceInfo.sdkApiVersion>=20
  397. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  398. new hdsEffect.ShaderEffectController():undefined;
  399. @State showAddSheet:boolean = false
  400. private loadingDialogId: string = ''
  401. private loadingProgressDialogId: string = ''
  402. @State isoAudioEntries: IsoArchiveAudioEntry[] = []
  403. @State selectedIsoAudioPaths: string[] = []
  404. @State isoSourceFileName: string = ''
  405. @State isIsoExtracting: boolean = false
  406. @State isoExtractProgress: number = 0
  407. @State isoExtractProgressText: string = ''
  408. @State isoExtractCurrentEntryName: string = ''
  409. private isoSourceFilePath: string = ''
  410. private isoExtractDestinationDir: string = ''
  411. private isoComponentId: number = 0
  412. private isoExtractProgressTimer: number = 0
  413. private isoExtractExpectedOutputPaths: Array<string> = []
  414. private isoExtractTotalBytes: number = 0
  415. private isoExtractDisplayedProgress: number = 0
  416. private isoExtractReceivedTaskProgress: boolean = false
  417. private isoExtractTask: taskpool.Task | undefined = undefined
  418. private isoExtractLastActivityTime: number = 0
  419. private readonly isoExtractStallTimeoutMs: number = 15000
  420. private isoExtractCanceled: boolean = false
  421. private isoExtractCancelMessage: string = ''
  422. searchController: SearchController = new SearchController()
  423. @State rightTopImage:Resource = $r('sys.symbol.sort')
  424. @State isEditAudio:boolean = false
  425. @State isExtractAcc:boolean = false
  426. @State isConverter:boolean = false
  427. @State isAIVoiceSeparation:boolean = false
  428. @State isExtractAudio:boolean = false
  429. @State isMergeAudio:boolean = false
  430. @State isCopyFileToDownLoad: boolean = false
  431. @State isChangeTone:boolean = false
  432. @State offHeight: number = 75
  433. @State currentSongList: Array<VideoItem> = []//当前歌单
  434. @Consume currentSongListName:string //当前歌单名称
  435. @Consume @Watch('onIDChange') currentSongListID:string //当前歌单ID
  436. @State currentPlaylistSongFilePaths: string[] = [] //当前歌单的歌曲路径列表(用于随机播放)
  437. @State isRefreshing: boolean = false;
  438. @State maxRefreshingHeight: number = 100.0;
  439. @State isPlayerLoading: boolean = false; // 播放器加载状态
  440. private contentNode?: ComponentContent<Object> = undefined;
  441. // WebDAV相关实例变量(现在改为从内存读取,不再需要存储)
  442. @State ratioL: number = 1;
  443. @State mediaKuCount: number = 0;
  444. @State albumCount: number = 0;
  445. @State artistCount: number = 0;
  446. @State fastForwardSeconds: string = '10'
  447. @State isShowBackFast: boolean = true//快进快退按钮
  448. @State isCanAuto:boolean = true
  449. @State opacityValueImage: number = 1;
  450. @State tipPopup:boolean = false
  451. @State preloadNextSong: boolean = PreferencesUtil.getBooleanSync('preload_next_song', true) // 是否提前缓存下一首
  452. @Consume mType: number;
  453. @StorageProp('themeColor') themeColor: string =
  454. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  455. themeMode: number = 0;
  456. @State titleName: string = '首页'
  457. @State textStr: string = ''
  458. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  459. // private download_path: string = '';
  460. @Consume rootPath: string //音频根目录
  461. @Consume currentPath: string
  462. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  463. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  464. @State lockPath: string = ''
  465. @State favPath: string = ''
  466. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  467. @State historyPath: string = ''
  468. @State historyList: Array<VideoItem> = []
  469. @Consume isHistory: boolean
  470. static readonly HISTORY_MUSIC: string = 'music_historyList';
  471. private table: MediaTable = new MediaTable(getContext(this))
  472. private playlistTable: PlaylistTable | null = null
  473. private deletionWatcher: FileDeletionWatcher | null = null
  474. @State allPlaylists: Playlist[] = []
  475. @State isZero: boolean = false
  476. @State fileList: Array<string> = []
  477. @State dirList: Array<VideoItem> = []
  478. @Consume videoLocalList:VideoItem[]
  479. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  480. @State listRefreshKey: number = 0
  481. @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  482. @State artistList: Array<VideoItem> = []; //艺术家文件
  483. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  484. @State artistSongCountMap: Map<string, number> = new Map();
  485. @State albumList: Array<VideoItem> = []; //专辑文件
  486. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  487. @State albumSongCountMap: Map<string, number> = new Map();
  488. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  489. @State imageOpacities: number[] = [];
  490. @Consume isCanBack: boolean
  491. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  492. @State showSingleLyric: boolean = false
  493. @State sortType: number = 4 //默认排序方式
  494. @State isShowSimi: boolean = false //是否显示私密音频
  495. @State isShowFAV: boolean = true //是否显示我的收藏
  496. @State isShowTitleBar: boolean = true //是否显示分类导航条
  497. @State isShowAllBar: boolean = true //是否显示播放全部条
  498. @State isShowSingleLineLyric: boolean = false //是否显示单行歌词
  499. @State isEnableWordByWordLyric: boolean = true //是否开启逐字歌词
  500. @State isShowHistory: boolean = true //是否显示最近播放
  501. @State @Watch('onColorModeChange') isCustomizeBg: boolean = false //自定义背景界面
  502. @State isGridMusic: boolean = false //是否网格布局
  503. @State isCircleBtn: boolean = false //是否圆形播放按钮
  504. @State twoFingerType: number = 3 //双支放大缩小的类型
  505. @State isScrollHide: boolean = false //是否滚动隐藏
  506. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  507. @State isStartAutoPlay: boolean = false //启动后自动播放
  508. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  509. @State isShowHeader: boolean = true
  510. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  511. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  512. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  513. @State rectangleCoverScale: number = 1
  514. @State rectangleCoverPinchValue: number = 1
  515. @State isSwipe: boolean = false //listItem的左滑开关
  516. @State openSkipSongAnimate: boolean = true//切歌动画效果
  517. @State isPlayPageSwipeNext: boolean = true // 播放页上滑切歌
  518. @State isLightText: boolean = true //是否开启歌词发光
  519. @State customizeBgPath: string | undefined = '';
  520. @State isDarkMode: boolean = false
  521. @State lyricTextWeight: number = 400
  522. @State lyricTextWeightPip: number = 400
  523. @State currentSwiperIndex: number = 0
  524. @State blurValue: number = 0 //背景模糊
  525. @State bgBrightness: number = 0 //背景亮度
  526. private listScroller: ListScroller = new ListScroller()
  527. private playListScroller: Scroller = new Scroller()
  528. @State isOneKeyTags:boolean = false
  529. @State isFixMessy:boolean = false
  530. // 分页相关状态
  531. @State private currentPage: number = 0 // 当前页码
  532. @State private pageSize: number = 53 // 每页数量
  533. @State private totalCount: number = 0 // 总记录数
  534. @State private hasMoreData: boolean = true // 是否还有更多数据
  535. @State private isLoadingPage: boolean = false // 是否正在加载分页数据
  536. private pageCache: Map<number, VideoItem[]> = new Map() // 页面缓存(最多保留3页)
  537. private pageHasMoreCache: Map<number, boolean> = new Map()
  538. private pageTotalCountCache: Map<number, number> = new Map()
  539. private prefetchingPages: Set<number> = new Set()
  540. private preloadStartRatio: number = 0.18
  541. private appendStartRatio: number = 0.30
  542. private earlyAppendReserveCount: number = 28
  543. private lastScrollTriggerPage: number = -1
  544. private lastVisibleEndIndex: number = -1
  545. private isPagingTransition: boolean = false
  546. private pagingScheduleTimer: number = 0
  547. private listScrollAlphaCheckAt: number = 0
  548. private listScrollPagingCheckAt: number = 0
  549. private listScrollLastAlphaStart: number = -1
  550. private listScrollLastPagingEnd: number = -1
  551. private gridScrollPagingCheckAt: number = 0
  552. private gridScrollLastPagingEnd: number = -1
  553. private waterScrollPagingCheckAt: number = 0
  554. private waterScrollLastPagingEnd: number = -1
  555. private gridWaterScrollIdleTimer: number = 0
  556. private gridWaterLastActiveTs: number = 0
  557. private listUpdateTimer: number = 0
  558. private listUpdateVersion: number = 0
  559. private detailBackTransitioning: boolean = false
  560. private mediaLibraryEnterTs: number = 0
  561. private mediaLibraryWarmupPrefetchTimer: number = 0
  562. private listVisibleStart: number = -1
  563. private listVisibleEnd: number = -1
  564. private listThumbWarmupCheckAt: number = 0
  565. private listThumbWarmupStart: number = -1
  566. private listThumbWarmupEnd: number = -1
  567. private gridThumbWarmupCheckAt: number = 0
  568. private gridThumbWarmupStart: number = -1
  569. private gridThumbWarmupEnd: number = -1
  570. private waterThumbWarmupCheckAt: number = 0
  571. private waterThumbWarmupStart: number = -1
  572. private waterThumbWarmupEnd: number = -1
  573. private gridVisibleStart: number = -1
  574. private gridVisibleEnd: number = -1
  575. private waterVisibleStart: number = -1
  576. private waterVisibleEnd: number = -1
  577. private titleBarToggleMinDelta: number = 12
  578. private titleBarLastCheckTs: number = 0
  579. @State private coverThumbVersion: number = 0
  580. private coverThumbCache: CoverThumbCache = new CoverThumbCache(1, 960)
  581. private coverThumbCacheReady: boolean = false
  582. private pendingCoverThumbRefresh: boolean = false
  583. private playQueueScope: 'view' | 'history' | 'fav' | 'playlist' | 'single' = 'view'
  584. private isHydratingPlayList: boolean = false
  585. @StorageProp('isLandscape') @Watch('onIsLandscapeChange') isLandscape: boolean = false;
  586. @StorageProp('topSafeHeight') topSafeHeight: number = 0;
  587. @StorageProp('bottomSafeHeight') bottomSafeHeight: number = 0;
  588. @StorageProp('windowWidth') windowWidth: number = 0;
  589. @StorageProp('windowHeight') windowHeight: number = 0;
  590. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  591. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  592. private UNKONWN:string = '';
  593. private listArea: Area = {
  594. width: 0,
  595. height: 0,
  596. position: {},
  597. globalPosition: {}
  598. }
  599. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  600. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  601. // WebDAV认证信息缓存(作为实例变量,比全局上下文更可靠)
  602. private currentWebDavAuthInfo: WebDavAuthItem | null = null;
  603. // 当前实际播放中的记忆key,避免切歌时 currentSong 已切换导致串写
  604. private activePlaybackMemoryKey: string = '';
  605. // 网盘流地址记忆恢复token,切歌后用于取消旧的延迟seek任务
  606. private remoteRestoreSeekToken: number = 0;
  607. // 本次是否需要先seek到记忆点再开始播放
  608. private waitInitialSeekBeforeStart: boolean = false;
  609. // 本次播放记忆点(毫秒)
  610. private pendingMemorySeekPosition: number = 0;
  611. // 记忆播放seek兜底,避免一直转圈
  612. private initialSeekGuardTimer: number = 0;
  613. private readonly initialSeekGuardTimeoutMs: number = 2000;
  614. private readonly remoteMemorySeekInitialDelayMs: number = 120;
  615. private readonly remoteMemorySeekRetryIntervalMs: number = 80;
  616. private readonly remoteMemorySeekMaxRetryCount: number = 6;
  617. private lastSeekRequestMs: number = -1;
  618. private lastSeekSource: string = '';
  619. private seekTraceUntilTs: number = 0;
  620. private lastSeekTraceLogTs: number = 0;
  621. private readonly seekTraceLogWindowMs: number = 4000;
  622. private readonly seekTraceLogIntervalMs: number = 400;
  623. //瀑布流的列数横竖屏动态切换
  624. onIsLandscapeChange() {
  625. if(this.isLandscape){
  626. this.columns = 4
  627. }else{
  628. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  629. }
  630. }
  631. onColorModeChange() {
  632. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  633. }
  634. //点击某个歌单id发生变化的时候回调
  635. onIDChange(){
  636. console.log('onecold 歌单id发生变化this.currentSongListID='+this.currentSongListID)
  637. console.log('onecold 歌单id发生变化this.currentSongListName='+this.currentSongListName)
  638. if(this.modeType==4){
  639. this.titleName = this.currentSongListName
  640. this.rightTopImage = $r('sys.symbol.sort')
  641. //获取缓存
  642. const cacheSongs:string =PreferencesUtil.getStringSync(this.currentSongListID+'currentSongList', '')
  643. console.log('onecold 歌单id发生变化获取缓存2 cacheSongs = '+cacheSongs)
  644. if(StrUtil.isNotEmpty(cacheSongs)){
  645. this.currentSongList = JSON.parse(cacheSongs) as VideoItem[]
  646. this.updateListData(this.currentSongList, true)
  647. }
  648. this.doSongListTask()//获取歌单信息
  649. }
  650. }
  651. async doSongListTask() {
  652. // 初始化歌单数据库
  653. const playlistTable = new PlaylistTable(this.context);
  654. // 查询歌单中的所有歌曲
  655. const playlistSongs: PlaylistSong[] = await playlistTable.queryPlaylistSongs(this.currentSongListID);
  656. console.log('onecold 歌单id发生变化获取缓存7 playlistSongs='+playlistSongs.length)
  657. if (ArrayUtil.isEmpty(playlistSongs)) {
  658. this.updateListData([], true)
  659. // 清空歌单路径列表
  660. this.currentPlaylistSongFilePaths = [];
  661. } else {
  662. this.currentSongList = await convertPlaylistSongsToVideoItems(this.context, playlistSongs);
  663. console.log('onecold 从数据库读取的歌曲为 playlistSongs='+this.currentSongList.length)
  664. this.updateListData(this.currentSongList, true)
  665. // 保存歌单的歌曲路径列表,用于随机播放
  666. this.currentPlaylistSongFilePaths = playlistSongs.map(song => song.songFilePath);
  667. Logger.info('heanup doSongListTask', `保存歌单歌曲路径列表,歌单ID=${this.currentSongListID}, 数量=${this.currentPlaylistSongFilePaths.length}`);
  668. if (ArrayUtil.isNotEmpty(this.currentSongList)&&this.currentSongList.length > 100) {
  669. // 只保存前100条记录到缓存中
  670. let canceList = this.currentSongList.slice(0, 100);
  671. PreferencesUtil.putSync(this.currentSongListID+'currentSongList',
  672. JSON.stringify(canceList))
  673. } else {
  674. PreferencesUtil.putSync(this.currentSongListID+'currentSongList', JSON.stringify(this.currentSongList));
  675. }
  676. }
  677. this.isRefreshing = false
  678. }
  679. async onModeChange(preserveList: boolean = false): Promise<void> {
  680. this.isFavMusic = false
  681. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  682. this.refreshDirVisibilitySettings()
  683. if (this.mediaLibraryWarmupPrefetchTimer) {
  684. clearTimeout(this.mediaLibraryWarmupPrefetchTimer)
  685. this.mediaLibraryWarmupPrefetchTimer = 0
  686. }
  687. Logger.info('heanup LocalMusic', `onModeChange: 切换模式 modeType=${this.modeType}`);
  688. switch (this.modeType) {
  689. case 0:
  690. // 首页模式已在 resetAndLoadFirstPage 中处理
  691. // 切换模式时加载对应的排序类型
  692. this.titleName = Utility.resourceToString(this.context,$r('app.string.home'))
  693. this.sortType = this.loadSortTypeForCurrentMode()
  694. this.mediaLibraryEnterTs = 0
  695. break
  696. case 1:
  697. this.rightTopImage = $r('sys.symbol.sort')
  698. this.titleName = Utility.resourceToString(this.context,$r('app.string.media_ku'))
  699. // 切换模式时加载对应的排序类型
  700. this.sortType = this.loadSortTypeForCurrentMode()
  701. this.mediaLibraryEnterTs = Date.now()
  702. break
  703. case 2:
  704. this.rightTopImage = $r('sys.symbol.sort')
  705. this.titleName = Utility.resourceToString(this.context,$r('app.string.artist'))
  706. // 切换到艺术家模式时,加载艺术家模式的排序类型(默认按数量降序)
  707. this.sortType = this.loadSortTypeForCurrentMode()
  708. this.mediaLibraryEnterTs = 0
  709. break
  710. case 3:
  711. this.rightTopImage = $r('sys.symbol.sort')
  712. this.titleName = Utility.resourceToString(this.context,$r('app.string.album'))
  713. // 切换到专辑模式时,加载专辑模式的排序类型(默认按数量降序)
  714. this.sortType = this.loadSortTypeForCurrentMode()
  715. this.mediaLibraryEnterTs = 0
  716. break
  717. }
  718. // 模式切换时重置分页状态并加载第一页
  719. await this.resetAndLoadFirstPage(!preserveList);
  720. Logger.info('heanup onModeChange', `doSortType: 切换排序方式 sortType=${this.sortType}, mode=${this.modeType}`);
  721. }
  722. // @Consume currentSong: VideoItem | undefined;
  723. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  724. // @StorageLink('isPlay') isPlay: boolean = false;
  725. @Consume isShowPlay: boolean ;
  726. @State isShowCoverScaleGuide: boolean = false
  727. @StorageLink('songList') songList: Array<VideoItem> = [];
  728. @State translateY: number = 0;
  729. @State isShowSheet: boolean = false;
  730. @State isShowSheetView: boolean = false;
  731. @State isShowLyricCopySheet: boolean = false;
  732. @State lyricCopyLines: string[] = [];
  733. @State lyricSelectedIndexes: number[] = [];
  734. @State isShowTimeCloseView: boolean = false;
  735. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  736. @StorageLink('currIndex') curIndex: number = 0;
  737. @Consume isShowDrawer: boolean;
  738. @Consume offsetX: number;
  739. @State isFac: boolean = false;
  740. @State favList: Array<VideoItem> = []
  741. @Consume isFavMusic: boolean
  742. @State isClickedPLayAll: boolean = false;
  743. private scrollerForlist: ListScroller = new ListScroller();
  744. private knockController: KnockController | undefined = undefined;
  745. @StorageProp('animationState') animationState: AnimationStatus = AnimationStatus.Initial
  746. // 缓存机制
  747. private cache: Map<string, Array<VideoItem>> = new Map();
  748. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  749. // 持久化缓存
  750. private async saveCacheToStorage() {
  751. const cacheArray = Array.from(this.cache.entries());
  752. const stringCacheArray = Array.from(this.stringCache.entries());
  753. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  754. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  755. }
  756. // 载入缓存
  757. private async loadCacheFromStorage() {
  758. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  759. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  760. if (cacheString) {
  761. const parsedCache: Object | null = JSON.parse(cacheString);
  762. if (parsedCache && Array.isArray(parsedCache)) {
  763. const cacheArray: [string, Array<VideoItem>][] = parsedCache;
  764. this.cache = new Map(cacheArray);
  765. }
  766. }
  767. if (stringCacheString) {
  768. const parsedStringCache: Object | null = JSON.parse(stringCacheString);
  769. if (parsedStringCache && Array.isArray(parsedStringCache)) {
  770. const stringCacheArray: [string, string][] = parsedStringCache;
  771. this.stringCache = new Map(stringCacheArray);
  772. }
  773. }
  774. }
  775. // 查找缓存
  776. private findCache(key: string): Array<VideoItem> | undefined {
  777. return this.cache.get(key);
  778. }
  779. // 查找字符串缓存
  780. private findStringCache(key: string): string | undefined {
  781. return this.stringCache.get(key);
  782. }
  783. // 添加缓存
  784. private addCache(key: string, value: Array<VideoItem>) {
  785. this.cache.set(key, value);
  786. }
  787. // 添加字符串缓存
  788. private addStringCache(key: string, value: string) {
  789. this.stringCache.set(key, value);
  790. }
  791. // 删除缓存
  792. private deleteCache(key: string) {
  793. this.cache.delete(key);
  794. this.saveCacheToStorage()
  795. }
  796. // 删除字符串缓存
  797. private deleteStringCache(key: string) {
  798. this.stringCache.delete(key);
  799. }
  800. // 多选机制
  801. @State selectedFiles: Array<VideoItem> = [];
  802. @Consume isMultiSelect: boolean;
  803. @State isAllSelected: boolean = false;
  804. @State appName: string = ''
  805. @State isHasDir: boolean = false
  806. @State packName: string = ''
  807. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  808. doSwipBack() {
  809. if(this.isSearchMode){
  810. console.info('onecold doSwipBack = ' +this.isSearchMode)
  811. this.isSearchMode = false
  812. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  813. this.searchText = ''
  814. this.getSortedFiles(this.currentPath)
  815. return
  816. }
  817. this.onSearchInput('')
  818. return
  819. }
  820. this.isZero = false
  821. if (this.modeType !== 0 && this.isCanBack) {
  822. if (this.detailBackTransitioning) {
  823. return
  824. }
  825. this.detailBackTransitioning = true
  826. // 先设置 isCanBack=false,确保 onModeChange 读取的是列表页的排序设置
  827. this.isCanBack = false
  828. this.rightTopImage = $r('sys.symbol.sort')
  829. if (this.modeType == 2) {
  830. this.titleName = Utility.resourceToString(this.context,$r('app.string.artist'))
  831. if (ArrayUtil.isNotEmpty(this.artistList)) {
  832. this.updateListData(this.artistList, true, true)
  833. }
  834. } else if (this.modeType == 3) {
  835. this.titleName = Utility.resourceToString(this.context,$r('app.string.album'))
  836. if (ArrayUtil.isNotEmpty(this.albumList)) {
  837. this.updateListData(this.albumList, true, true)
  838. }
  839. }
  840. // 返回列表页时保留当前列表,避免先清空导致闪现
  841. void this.onModeChange(true).then(() => {
  842. if (this.modeType == 2) {
  843. if (this.isGridMusic||this.twoFingerType==4) {
  844. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  845. let lastWaterOffset = this.mScrollMap.get('lastWaterArtistScrollOffset') ?? 0
  846. if(this.twoFingerType==4){
  847. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  848. }else{
  849. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  850. }
  851. } else {
  852. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  853. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  854. }
  855. } else if (this.modeType == 3) {
  856. if (this.isGridMusic||this.twoFingerType==4) {
  857. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  858. let lastWaterOffset = this.mScrollMap.get('lastWaterAlBumScrollOffset') ?? 0
  859. if(this.twoFingerType==4){
  860. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  861. }else{
  862. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  863. }
  864. } else {
  865. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  866. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  867. }
  868. }
  869. this.detailBackTransitioning = false
  870. }).catch((error: Error) => {
  871. Logger.error('heanup LocalMusic', `doSwipBack onModeChange error: ${error.message}`)
  872. this.detailBackTransitioning = false
  873. })
  874. return
  875. }
  876. this.mediaLibraryEnterTs = 0
  877. if (this.isHistory || this.isFavMusic) {
  878. this.isHistory = false
  879. this.getSortedFiles(this.currentPath)
  880. return
  881. }
  882. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  883. animateTo({ duration: 555 }, () => {
  884. // 动画闭包内控制Image组件的出现和消失
  885. this.isShowDrawer = !this.isShowDrawer
  886. this.offsetX = 0
  887. })
  888. return
  889. }
  890. //返回上一级歌单的滚动位置
  891. setTimeout(() => {
  892. if (this.modeType == 0) {
  893. if (this.isGridMusic||this.twoFingerType==4) {
  894. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  895. let lastWaterOffset = this.mScrollMap.get('lastWaterDirScrollOffset') ?? 0
  896. if(this.twoFingerType==4){
  897. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  898. }else{
  899. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  900. }
  901. } else {
  902. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  903. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  904. }
  905. }
  906. }, 100)
  907. this.currentPath = Utility.getParentDirectory(this.currentPath)
  908. Logger.info('this.currentPath2 = ' + this.currentPath)
  909. this.getSortedFiles(this.currentPath, false, undefined, undefined, undefined, true)
  910. }
  911. private triggerSwipeBackWithAnimation(): void {
  912. animateTo({ duration: 555 }, () => {
  913. this.doSwipBack()
  914. })
  915. }
  916. // 组件生命周期
  917. aboutToAppear() {
  918. console.info('onecold aboutToAppear sdkApiVersion = '+deviceInfo.sdkApiVersion)
  919. if(ArrayUtil.isNotEmpty(this.videoLocalList)&&this.modeType==0){
  920. this.updateListData(this.videoLocalList)
  921. }
  922. // 初始化 PlaylistTable
  923. this.playlistTable = new PlaylistTable(getContext(this))
  924. this.sonTwoFingerType = PreferencesUtil.getNumberSync('sonTwoFingerType', 3);
  925. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  926. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  927. this.tipPopup = !this.tipPopup
  928. PreferencesUtil.putSync('isFirstTiped',false)
  929. }
  930. this.loadSearchHistory()
  931. this.initSetting()
  932. this.syncEqualizerUi();
  933. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  934. Utility.getAppName(getContext(this)).then((appName: string) => {
  935. this.appName = appName
  936. })
  937. this.packName = AppUtil.getBundleName()
  938. this.tabSelectedIndexes[0] = this.modeType//SegmentButton的索引
  939. this.loadCacheFromStorage(); // 加载文件夹缓存
  940. // 在首页初始化时读取媒体库,艺术家,专辑等缓存数据
  941. this.initLoadCache()
  942. this.mkDownLoadDir()
  943. let eventMusic: emitter.InnerEvent = { eventId: EventConstants.EVENT_AUDIO_OPEN }
  944. // 监听广播事件(打开其他应用处理)
  945. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  946. this.saveVideoDatas([eventData.data?.message], true)
  947. });
  948. //侧滑广播接收时间
  949. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_UPDATE }
  950. // 监听广播事件(手势返回处理)
  951. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  952. this.triggerSwipeBackWithAnimation()
  953. });
  954. //ScanFilePage广播接收时间
  955. let eventScanUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_SCAN_UPDATE }
  956. // 监听ScanFilePage广播事件(更新数据库)
  957. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  958. this.doUpdateData()
  959. });
  960. let eventEqualizerChanged: emitter.InnerEvent = { eventId: EventConstants.EVENT_EQUALIZER_CHANGED }
  961. emitter.on(eventEqualizerChanged, () => {
  962. this.syncEqualizerUi();
  963. if (this.mIjkMediaPlayer) {
  964. const equalizerManager = EqualizerManager.getInstance();
  965. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  966. this.markEqualizerApplied();
  967. }
  968. });
  969. // 监听歌单播放请求事件
  970. let eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY }
  971. emitter.on(eventPlaylistPlay, async (eventData: emitter.EventData) => {
  972. const data = eventData.data as Record<string, Object>
  973. if (!data) {
  974. Logger.error('heanup eventPlaylistPlay: eventData.data is undefined or null')
  975. return
  976. }
  977. // 检查歌单播放数据结构
  978. if (data.playlistId && data.songFilePaths && data.startIndex !== undefined) {
  979. const playlistData: PlaylistEventData = {
  980. playlistId: data.playlistId as string,
  981. playlistName: data.playlistName as string,
  982. songCount: data.songCount as number,
  983. startIndex: data.startIndex as number,
  984. isJump: data.isJump as boolean,
  985. songFilePaths: data.songFilePaths as string[]
  986. }
  987. await this.handlePlaylistPlayRequest(
  988. playlistData.playlistId,
  989. playlistData.playlistName,
  990. playlistData.songFilePaths,
  991. playlistData.startIndex,
  992. playlistData.isJump,
  993. playlistData.songCount
  994. )
  995. return
  996. }
  997. Logger.error('heanup eventPlaylistPlay: 接收到无效的数据结构')
  998. });
  999. let eventRefreshSort: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_REFRESH_SORT }
  1000. // 监听广播事件(通用设置配置更新)
  1001. emitter.on(eventRefreshSort, (eventData: emitter.EventData) => {
  1002. if(this.modeType ==4){
  1003. this.doSongListTask()//获取歌单信息
  1004. }
  1005. });
  1006. let eventQueueRefresh: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAY_QUEUE_REFRESH }
  1007. emitter.on(eventQueueRefresh, () => {
  1008. this.syncWebdavQueueWithoutRestart();
  1009. });
  1010. let eventOpenLocalSpecialList: emitter.InnerEvent = { eventId: EventConstants.EVENT_OPEN_LOCAL_SPECIAL_LIST }
  1011. emitter.on(eventOpenLocalSpecialList, (eventData: emitter.EventData) => {
  1012. const data = eventData.data as Record<string, Object>
  1013. const target = data?.target as string
  1014. this.openSpecialLocalList(target)
  1015. });
  1016. let eventSetting: emitter.InnerEvent = { eventId: EventConstants.EVENT_SETTING_UPDATE }
  1017. // 监听广播事件(通用设置配置更新)
  1018. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  1019. this.initSetting()
  1020. });
  1021. // 监听 WebDAV 元数据更新事件
  1022. let eventWebDavMetadata: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED }
  1023. emitter.on(eventWebDavMetadata, (eventData: emitter.EventData) => {
  1024. const payloads = eventData?.data as WebDavMetadataUpdatePayload[] | undefined;
  1025. if (!payloads || payloads.length === 0) {
  1026. Logger.info(TAG, 'LocalMusic: WebDav metadata event received but payload empty');
  1027. return;
  1028. }
  1029. Logger.info(TAG, `LocalMusic: WebDav metadata event payload count: ${payloads.length}`);
  1030. // 处理每个元数据更新
  1031. for (let i = 0; i < payloads.length; i++) {
  1032. const payload = payloads[i];
  1033. if (!payload || !payload.filePath) {
  1034. continue;
  1035. }
  1036. // 重要:只更新当前正在播放的歌曲
  1037. // 如果 filePath 不匹配,说明是其他歌曲的元数据更新,忽略不做处理
  1038. if (this.currentSong && this.currentSong.filePath === payload.filePath) {
  1039. Logger.info(TAG, `LocalMusic: 更新当前播放歌曲的元数据: ${payload.filePath}`);
  1040. if (payload.name && payload.name.length > 0) {
  1041. this.name = payload.name;
  1042. if (this.currentSong) {
  1043. this.currentSong.name = payload.name;
  1044. }
  1045. }
  1046. if (payload.artist && payload.artist.length > 0) {
  1047. this.artist = payload.artist;
  1048. if (this.currentSong) {
  1049. this.currentSong.artist = payload.artist;
  1050. }
  1051. }
  1052. if (this.currentSong) {
  1053. const coverMutated = mergeCoverWithPriority(this.currentSong, payload.pixelMapPath,
  1054. payload.isCustomCover ?? 0);
  1055. if (coverMutated && this.currentSong.pixelMapPath) {
  1056. this.cover = this.currentSong.pixelMapPath;
  1057. Logger.info(TAG, `LocalMusic: 封面已更新: ${this.currentSong.pixelMapPath}`);
  1058. }
  1059. if (payload.md5Str && payload.md5Str.length > 0) {
  1060. this.currentSong.md5Str = payload.md5Str;
  1061. }
  1062. }
  1063. // 同步更新 AppStorage
  1064. AppStorage.setOrCreate('currentSong', this.currentSong);
  1065. } else {
  1066. Logger.info(TAG, `LocalMusic: 跳过非当前播放歌曲的元数据更新: ${payload.filePath}, 当前: ${this.currentSong?.filePath}`);
  1067. }
  1068. }
  1069. });
  1070. // 监听广播事件(通用设置配置更新)
  1071. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  1072. this.doChangeSetting()
  1073. });
  1074. let event: Callback<InterruptEvent> = (event) => {
  1075. // LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  1076. console.info(`heanup onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`)
  1077. this.savePlaybackPosition()
  1078. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  1079. this.pause();
  1080. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  1081. console.info(`heanup onecold audioInterrupt startPlayOrResumePlay: ${JSON.stringify(event)}`)
  1082. this.startPlayOrResumePlay();
  1083. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  1084. console.info(`heanup onecold 与其他应用音频冲突 被截断点 INTERRUPT_HINT_STOP`)
  1085. if(!this.isSameTimePlay){
  1086. this.stop();
  1087. }
  1088. }
  1089. }
  1090. this.mIjkMediaPlayer.on('audioInterrupt', event);
  1091. // 音频设备断连回调处理比如蓝牙耳机断开
  1092. let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  1093. console.info(`onecold Heanup deviceChange event: ${JSON.stringify(event)}`);
  1094. if (event.reason === DeviceChangeReason.REASON_NEW_DEVICE_AVAILABLE) { // 音频设备连接
  1095. } else if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  1096. console.info('heanup onecold 音频设备断开连接, 暂停播放')
  1097. this.pause();
  1098. }
  1099. }
  1100. // 订阅音频设备断开和连接事件
  1101. this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  1102. const eventPause: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAY_PAUSE }
  1103. // 监听广播事件(hicar断开暂停播放)
  1104. emitter.on(eventPause, (eventData: emitter.EventData) => {
  1105. console.info('heanup onecold hicar断开暂停播放, 暂停播放')
  1106. this.pause();
  1107. });
  1108. let audioManager = audio.getAudioManager(); // 需要先创建AudioManager实例。
  1109. let audioRoutingManager = audioManager.getRoutingManager(); // 再调用AudioManager的方法创建AudioRoutingManager实例。
  1110. // 监听蓝牙音响断开音频设备状态变化。
  1111. audioRoutingManager.on('deviceChange', audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (deviceChanged: audio.DeviceChangeAction) => {
  1112. console.info(`onecold device change type : ${deviceChanged.type}`); // 设备连接状态变化,0为连接,1为断开连接。
  1113. console.info(`onecold device descriptor size : ${deviceChanged.deviceDescriptors.length}`);
  1114. console.info(`onecold device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceRole}`); // 设备角色。
  1115. console.info(`onecold device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceType}`);
  1116. // 蓝牙设备类型为8
  1117. const isBluetooth = deviceChanged.deviceDescriptors[0].deviceType === 8;
  1118. if (isBluetooth) {
  1119. if (deviceChanged.type === 0) {
  1120. // 蓝牙连接
  1121. this.isBluetoothConnected = true;
  1122. console.info('onecold 蓝牙设备已连接');
  1123. } else if (deviceChanged.type === 1) {
  1124. // 蓝牙断开
  1125. this.isBluetoothConnected = false;
  1126. this.lastBluetoothLyricLine = '';
  1127. console.info('onecold 蓝牙设备已断开');
  1128. // 恢复原始元数据
  1129. if (this.currentSong) {
  1130. this.avSessionController.restoreOriginalMetadata(
  1131. this.currentSong.name || '',
  1132. this.currentSong.artist || ''
  1133. );
  1134. }
  1135. // 蓝牙断开暂停
  1136. if (this.bluetoothDisconnectPause && deviceChanged.deviceDescriptors[0].deviceRole === 2) {
  1137. console.info('heanup onecold 蓝牙音响断开, 暂停播放');
  1138. this.pause();
  1139. }
  1140. }
  1141. }
  1142. });
  1143. // 有线耳机断开和连接的监听。监听音频设备状态变化。
  1144. audioRoutingManager.on('deviceChange', audio.DeviceFlag.INPUT_DEVICES_FLAG, (deviceChanged: audio.DeviceChangeAction) => {
  1145. console.info('onecold device change type : ' + deviceChanged.type); // 设备连接状态变化,0为连接,1为断开连接。
  1146. // 设备类型 22是USB耳机,带麦克风,3是有线耳机。
  1147. if(deviceChanged.type==1&&
  1148. (deviceChanged.deviceDescriptors[0].deviceType== 22||
  1149. deviceChanged.deviceDescriptors[0].deviceType==3)){
  1150. console.info('heanup onecold 有线耳机断开, 暂停播放')
  1151. this.pause();
  1152. }
  1153. });
  1154. this.makeWorker()
  1155. //折叠屏的屏幕显示模式变化
  1156. display.on('foldDisplayModeChange', (data) => {
  1157. this.doChangeBarHeight()
  1158. });
  1159. display.on('foldStatusChange', (data) => {
  1160. Logger.info('onecold foldStatusChange ')
  1161. });
  1162. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  1163. this.rectangleCoverScale = PreferencesUtil.getNumberSync(SettingPage.RECTANGLE_COVER_SCALE, 1)
  1164. if (this.rectangleCoverScale < 0.7 || this.rectangleCoverScale > 1.4) {
  1165. this.rectangleCoverScale = 1
  1166. }
  1167. // 读取 themeMode 并同步 currentColorMode
  1168. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  1169. this.applyThemeMode(this.themeMode)
  1170. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  1171. AppStorage.setOrCreate('themeColor', themeColor);
  1172. this.themeColor = themeColor;
  1173. this.doChangeSetting()
  1174. this.windowClass.on('windowSizeChange', (size: window.Size) => {
  1175. LogUtil.info('onecold windowSizeChange')
  1176. this.doChangeBarHeight()
  1177. let viewWidth = px2vp(size.width);
  1178. let viewHeight = px2vp(size.height);
  1179. if(this.isPhoneLan()){
  1180. this.is_auto_hide_progress = false
  1181. if(this.isHiCar()){
  1182. return
  1183. }
  1184. setTimeout(() => {
  1185. this.is_auto_hide_progress = true
  1186. }, 6000)
  1187. }else{
  1188. this.startAutoHide()
  1189. }
  1190. });
  1191. this.eventHub.on('onStateChange', (fg: boolean) => {
  1192. this.isAppForeground = fg;
  1193. if (fg && this.curState === 'STARTED') {
  1194. this.stopPip();
  1195. this.syncLyricPositionNow();
  1196. }
  1197. });
  1198. //NewIndex的博空调收到eventHub消息控制播放
  1199. this.getUIContext().getHostContext()!.eventHub.on('playOrPause', () => {
  1200. if (ArrayUtil.isNotEmpty(this.songList)) {
  1201. this.playOrPause();
  1202. } else {
  1203. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1204. }
  1205. });
  1206. this.getUIContext().getHostContext()!.eventHub.on('playPrevious', () => {
  1207. if (ArrayUtil.isNotEmpty(this.songList)) {
  1208. this.playPrevious();
  1209. } else {
  1210. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1211. }
  1212. });
  1213. this.getUIContext().getHostContext()!.eventHub.on('playNext', () => {
  1214. if (ArrayUtil.isNotEmpty(this.songList)) {
  1215. this.playNext();
  1216. } else {
  1217. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1218. }
  1219. });
  1220. this.getUIContext().getHostContext()!.eventHub.on('showPlayerView', () => {
  1221. this.showPlayerView();
  1222. });
  1223. this.getUIContext().getHostContext()!.eventHub.on('openPlayList', () => {
  1224. this.openPlayList();
  1225. });
  1226. }
  1227. //载入媒体库,艺术家,专辑等缓存
  1228. initLoadCache(){
  1229. this.mediaKuCount = PreferencesUtil.getNumberSync('mediaKuCount', 0)
  1230. this.artistCount = PreferencesUtil.getNumberSync('artistCount', 0)
  1231. this.albumCount = PreferencesUtil.getNumberSync('albumCount', 0)
  1232. let cachedListStr:string = PreferencesUtil.getStringSync('mediaKuList', '[]');
  1233. let cachedList = JSON.parse(cachedListStr) as Array<VideoItem>;
  1234. if(ArrayUtil.isNotEmpty(cachedList)){
  1235. this.mediaKuList = cachedList
  1236. if(this.modeType==1){
  1237. this.updateListData(this.mediaKuList)
  1238. }
  1239. }
  1240. let artistListStr:string = PreferencesUtil.getStringSync('artistList', '[]');
  1241. let artistCachedList = JSON.parse(artistListStr) as Array<VideoItem>;
  1242. if(ArrayUtil.isNotEmpty(artistCachedList)){
  1243. this.artistList = artistCachedList
  1244. let artistMapStr:string = PreferencesUtil.getStringSync('artistMap', '[]');
  1245. const parsedArray = JSON.parse(artistMapStr) as [string, VideoItem[]][];
  1246. this.artistMap = new Map(parsedArray);
  1247. // this.artistMap = JSON.parse(artistMapStr) as Map<string, VideoItem[]>;
  1248. if(this.modeType==2){
  1249. this.updateListData(this.artistList)
  1250. }
  1251. }
  1252. let albumListStr:string = PreferencesUtil.getStringSync('albumList', '[]');
  1253. let albumCachedList = JSON.parse(albumListStr) as Array<VideoItem>;
  1254. if(ArrayUtil.isNotEmpty(albumCachedList)){
  1255. this.albumList = albumCachedList
  1256. let albumMapStr:string = PreferencesUtil.getStringSync('albumMap', '[]');
  1257. const parsedArray = JSON.parse(albumMapStr) as [string, VideoItem[]][];
  1258. this.albumMap = new Map(parsedArray);
  1259. if(this.modeType==3){
  1260. this.updateListData(this.albumList)
  1261. }
  1262. }
  1263. }
  1264. startAutoHide() {
  1265. if(this.isHiCar()){
  1266. return
  1267. }
  1268. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  1269. console.info('onecold startAutoHide')
  1270. this.is_auto_hide_progress = false
  1271. setTimeout(() => {
  1272. this.is_auto_hide_progress = true
  1273. }, 6000)
  1274. }
  1275. }
  1276. applyThemeMode(mode: number) {
  1277. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  1278. if (mode === 1) {
  1279. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  1280. } else if (mode === 2) {
  1281. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1282. }
  1283. AppStorage.setOrCreate('currentColorMode', colorMode)
  1284. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  1285. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  1286. AppStorage.setOrCreate('themeMode', mode)
  1287. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1288. // 只有强制浅色/深色时才主动设置
  1289. const context = getContext(this) as common.UIAbilityContext
  1290. context.getApplicationContext().setColorMode(colorMode)
  1291. }
  1292. initSetting() {
  1293. this.default_layout = PreferencesUtil.getNumberSync('default_layout', 0)
  1294. this.isGeKongPlayNext = PreferencesUtil.getBooleanSync('isGeKongPlayNext', false)
  1295. this.bluetoothDisconnectPause = PreferencesUtil.getBooleanSync(SettingPage.BLUETOOTH_DISCONNECT_PAUSE, false)
  1296. this.bluetoothLyricEnabled = PreferencesUtil.getBooleanSync(SettingPage.BLUETOOTH_LYRIC_ENABLED, false)
  1297. this.bluetoothLyricMode = PreferencesUtil.getNumberSync(SettingPage.BLUETOOTH_LYRIC_MODE, 0)
  1298. this.isShowSpectrum = PreferencesUtil.getBooleanSync('isShowSpectrum', true)
  1299. this.spectrumModeIndex = PreferencesUtil.getNumberSync('spectrumModeIndex', 0)
  1300. this.enablePointLight = PreferencesUtil.getBooleanSync('enablePointLight', true)
  1301. AppStorage.setOrCreate('EnablePointLight', this.enablePointLight);
  1302. this.showSimple = PreferencesUtil.getBooleanSync('showSimple', true)
  1303. this.showFindLocation = PreferencesUtil.getBooleanSync('showFindLocation', true)
  1304. this.showZMIndex = PreferencesUtil.getBooleanSync('showZMIndex', false)
  1305. this.autoHideTitle = PreferencesUtil.getBooleanSync('autoHideTitle', true)
  1306. this.isShowPrecious = PreferencesUtil.getBooleanSync('isShowPrecious', false)
  1307. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1308. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  1309. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  1310. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, false)
  1311. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  1312. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  1313. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  1314. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  1315. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  1316. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  1317. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  1318. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  1319. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  1320. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 3)
  1321. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  1322. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  1323. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  1324. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  1325. this.isEnableWordByWordLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_ENABLE_WORD_BY_WORD_LYRIC, true)
  1326. this.isLightText = PreferencesUtil.getBooleanSync(SettingPage.IS_LIGHT_TEXT, true)
  1327. this.syncWordByWordLyricMode()
  1328. this.syncLyricLightTextMode()
  1329. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  1330. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  1331. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  1332. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  1333. const volumeBoostPercent = PreferencesUtil.getNumberSync(this.volumeBoostPreferenceKey, 0)
  1334. this.volumeBoostPercent = Math.max(0, Math.min(volumeBoostPercent, this.volumeBoostMaxPercent))
  1335. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  1336. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  1337. this.isPlayPageSwipeNext = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYPAGE_SWIPE_NEXT, true)
  1338. this.volumeSmall = PreferencesUtil.getBooleanSync('volumeSmall', false)
  1339. this.autoParseMusicName = PreferencesUtil.getBooleanSync('autoParseMusicName', true)
  1340. this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
  1341. this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
  1342. this.refreshDirVisibilitySettings()
  1343. this.fastForwardSeconds = PreferencesUtil.getStringSync('fastForwardSeconds', '10')
  1344. this.isShowBackFast = PreferencesUtil.getBooleanSync('isShowBackFast', false)
  1345. this.isCopyFileToDownLoad = PreferencesUtil.getBooleanSync(SettingPage.IS_COPYFILE_TO_DOWNLOAD, false)
  1346. let audioManager = audio.getAudioManager();
  1347. let audioSessionManager: audio.AudioSessionManager = audioManager.getSessionManager();
  1348. if(this.isSameTimePlay){
  1349. //与其他应用同时播放,关键代码
  1350. let strategy: audio.AudioSessionStrategy = {
  1351. concurrencyMode: audio.AudioConcurrencyMode.CONCURRENCY_MIX_WITH_OTHERS
  1352. };
  1353. audioSessionManager.activateAudioSession(strategy).then(() => {
  1354. console.info('onecold Succeeded in doing activateAudioSession.');
  1355. }).catch((err: BusinessError) => {
  1356. console.error(`Failed to activateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1357. });
  1358. }else{
  1359. let isActivated = audioSessionManager.isAudioSessionActivated();
  1360. if(isActivated){
  1361. audioSessionManager.deactivateAudioSession().then(() => {
  1362. console.info('Succeeded in doing deactivateAudioSession.');
  1363. }).catch((err: BusinessError) => {
  1364. console.error(`Failed to deactivateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1365. });
  1366. }
  1367. }
  1368. //如果是hicar连接状态,这些都是false
  1369. if(this.isHiCar()){
  1370. this.autoHideTitle = false
  1371. this.isCoverRectangle= true
  1372. this.columns=4
  1373. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  1374. {
  1375. this.isGridMusic= false//用list不用网格
  1376. this.isCoverTopBig = false
  1377. }
  1378. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  1379. }
  1380. if (this.isSavePlayMode) {
  1381. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  1382. }
  1383. }
  1384. doChangeSetting() {
  1385. this.initSetting()
  1386. this.deleteCache(this.currentPath)
  1387. if (this.modeType === 0) {
  1388. this.getSortedFiles(this.currentPath)
  1389. }
  1390. }
  1391. doChangeBarHeight() {
  1392. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  1393. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  1394. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  1395. this.setBarHeightNormal()
  1396. }
  1397. }
  1398. onPageShow() {
  1399. this.knockController?.immersiveListening();
  1400. app.setImageCacheCount(100);
  1401. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  1402. app.setImageRawDataCacheSize(104857600);
  1403. this.refreshDirVisibilitySettings();
  1404. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  1405. }
  1406. //开启线程查看各个数据库
  1407. makeWorker() {
  1408. setTimeout(() => {
  1409. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  1410. // ToastUtil.showToast('请到文件扫描页面导入音乐!')
  1411. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  1412. workerInstance.postMessage({
  1413. code: 1,
  1414. data1: this.context,
  1415. data2: this.rootPath,
  1416. data3: this.lockPath,
  1417. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  1418. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  1419. });
  1420. PreferencesUtil.putSync('isFirstApp', false)
  1421. } else {
  1422. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1423. workerInstance.postMessage({ code: 3, data: this.context });
  1424. workerInstance.postMessage({ code: 4, data: this.context });
  1425. this.getHistoryList(false)
  1426. }
  1427. }, 1000)
  1428. workerInstance.onmessage = (e: MessageEvents): void => {
  1429. const message = e.data as LocalMusicWorkerMessage;
  1430. switch (message.code) {
  1431. case 101: //第一次扫描文件夹入库
  1432. ToastUtil.showToast('刷新同步数据库成功!')
  1433. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  1434. this.doAllUpdateData()
  1435. break;
  1436. case 102: //查询媒体库列表
  1437. this.isRefreshing = false
  1438. this.mediaKuList = message.data // 只包含前100条
  1439. const mediaTotalCount: number = message.totalCount ?? this.mediaKuList.length;
  1440. this.mediaKuCount = mediaTotalCount;
  1441. Logger.info(`heanup 查询媒体库列表 缓存数=${this.mediaKuList.length}, 总数=${mediaTotalCount}`)
  1442. Utility.doSortListAscending(this.mediaKuList)
  1443. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  1444. // 媒体库模式下重新加载第一页(分页查询)
  1445. if (this.modeType === 1) {
  1446. this.resetAndLoadFirstPage();
  1447. }
  1448. PreferencesUtil.putSync('mediaKuCount', mediaTotalCount)
  1449. // 只保存前100条记录到缓存中
  1450. PreferencesUtil.putSync('mediaKuList', JSON.stringify(this.mediaKuList));
  1451. break;
  1452. case 103: //收到查询艺术家列表
  1453. this.isRefreshing = false
  1454. this.artistMap = message.data1; // 只包含前60个艺术家的歌曲
  1455. this.artistList = message.data2; // 只包含前100个艺术家
  1456. const artistTotalCount: number = message.totalCount ?? this.artistList.length;
  1457. this.artistCount = artistTotalCount;
  1458. const nextArtistCountMap = new Map(this.artistSongCountMap);
  1459. this.artistMap.forEach((songs, artist) => {
  1460. nextArtistCountMap.set(artist, songs.length);
  1461. });
  1462. this.artistSongCountMap = nextArtistCountMap;
  1463. Logger.info(`heanup 查询艺术家列表 缓存数=${this.artistList.length}, 总数=${artistTotalCount}`)
  1464. PreferencesUtil.putSync('artistCount', artistTotalCount)
  1465. // 艺术家模式下重新加载第一页(分页查询)
  1466. if (this.modeType === 2) {
  1467. this.resetAndLoadFirstPage();
  1468. }
  1469. // 保存前100条艺术家列表
  1470. PreferencesUtil.putSync('artistList', JSON.stringify(this.artistList));
  1471. // 保存前60条艺术家的歌曲Map
  1472. const sortedEntries = Array.from(this.artistMap.entries());
  1473. PreferencesUtil.putSync('artistMap', JSON.stringify(sortedEntries));
  1474. break;
  1475. case 104: //收到查询专辑列表
  1476. this.isRefreshing = false
  1477. this.albumMap = message.data1;
  1478. this.albumList = message.data2
  1479. const albumTotalCount: number = message.totalCount ?? this.albumList.length;
  1480. this.albumCount = albumTotalCount;
  1481. const nextAlbumCountMap = new Map(this.albumSongCountMap);
  1482. this.albumMap.forEach((songs, album) => {
  1483. nextAlbumCountMap.set(album, songs.length);
  1484. });
  1485. this.albumSongCountMap = nextAlbumCountMap;
  1486. Logger.info(`heanup 查询专辑列表 缓存数=${this.albumList.length}, 总数=${albumTotalCount}`)
  1487. // 专辑模式下重新加载第一页(分页查询)
  1488. if (this.modeType === 3) {
  1489. this.resetAndLoadFirstPage();
  1490. }
  1491. //查询完毕在启动是否自动播放
  1492. if (this.isStartAutoPlay&&this.isCanAuto) {
  1493. this.isCanAuto = false
  1494. console.info('onecold startPlayOrResumePlay 757')
  1495. this.startPlayOrResumePlay()
  1496. }
  1497. PreferencesUtil.putSync('albumCount', albumTotalCount)
  1498. // 保存前100条专辑列表(Worker已经只发送了100条)
  1499. PreferencesUtil.putSync('albumList', JSON.stringify(this.albumList));
  1500. // 保存前60条专辑Map(Worker已经只发送了60条)
  1501. const mapArrayAlbum = Array.from(this.albumMap.entries());
  1502. PreferencesUtil.putSync('albumMap', JSON.stringify(mapArrayAlbum));
  1503. break;
  1504. case 105: // 缓存完成后返回的元数据
  1505. this.handleWorkerMetadataPayload(message.data);
  1506. break;
  1507. case 106: // 编辑音乐元数据和封面完成
  1508. this.handleEditMusicResult(message.data);
  1509. break;
  1510. }
  1511. };
  1512. // 在调用terminate后,执行onexit
  1513. workerInstance.onexit = (code) => {
  1514. metadataExtractionInFlight.clear();
  1515. Logger.info(TAG, 'workerInstance 线程已退出,code: ' + code);
  1516. }
  1517. workerInstance.onerror = (err: ErrorEvent) => {
  1518. metadataExtractionInFlight.clear();
  1519. console.error('workerInstance 线程执行发生异常: ' + err.message)
  1520. }
  1521. }
  1522. private handleWorkerMetadataPayload(payload: WorkerMetadataPayload | undefined): void {
  1523. if (!payload || !payload.originFilePath) {
  1524. return;
  1525. }
  1526. metadataExtractionInFlight.delete(payload.originFilePath);
  1527. if (payload.error) {
  1528. Logger.warn(TAG, `缓存文件元数据解析失败: ${payload.error}`);
  1529. return;
  1530. }
  1531. this.applyMetadataToCollections(payload.originFilePath, payload);
  1532. }
  1533. private applyMetadataToCollections(filePath: string, payload: WorkerMetadataPayload): void {
  1534. const targets: Array<VideoItem> = [];
  1535. let mainListUpdated = false;
  1536. let playlistUpdated = false;
  1537. if (this.currentSong && this.currentSong.filePath === filePath) {
  1538. targets.push(this.currentSong);
  1539. }
  1540. const collectFromList = (list?: Array<VideoItem>, markUpdated?: () => void) => {
  1541. if (!list || list.length === 0) {
  1542. return;
  1543. }
  1544. const found = Utility.getItemByFilePath(list, filePath);
  1545. if (found) {
  1546. markUpdated?.();
  1547. targets.push(found);
  1548. }
  1549. };
  1550. collectFromList(this.videoLocalList, () => {
  1551. mainListUpdated = true;
  1552. });
  1553. collectFromList(this.songList, () => {
  1554. playlistUpdated = true;
  1555. });
  1556. collectFromList(this.historyList);
  1557. collectFromList(this.favList);
  1558. const remoteManager = RemoteDriveManager.getInstance();
  1559. collectFromList(remoteManager.webDavSongs);
  1560. const updated = new Set<VideoItem>();
  1561. const remoteMetadataUpdates: Map<string, WebDavMetadataUpdatePayload> = new Map();
  1562. for (let i = 0; i < targets.length; i++) {
  1563. const target = targets[i];
  1564. if (!target || updated.has(target)) {
  1565. continue;
  1566. }
  1567. updated.add(target);
  1568. this.mergeVideoItemWithPayload(target, payload);
  1569. if (isRemoteCloudType(target.type) && StrUtil.isNotEmpty(target.filePath)) {
  1570. remoteMetadataUpdates.set(target.filePath, {
  1571. filePath: target.filePath,
  1572. pixelMapPath: target.pixelMapPath,
  1573. isCustomCover: target.isCustomCover,
  1574. md5Str: target.md5Str,
  1575. name: target.name,
  1576. artist: target.artist
  1577. });
  1578. }
  1579. }
  1580. if (this.currentSong && this.currentSong.filePath === filePath) {
  1581. this.mergeVideoItemWithPayload(this.currentSong, payload);
  1582. if (payload.name) {
  1583. this.name = payload.name;
  1584. }
  1585. if (payload.artist) {
  1586. this.artist = payload.artist;
  1587. }
  1588. if (payload.pixelMapPath && this.currentSong?.pixelMapPath) {
  1589. this.cover = this.currentSong.pixelMapPath;
  1590. }
  1591. if (payload.lyricContent) {
  1592. this.applyInlineLyricContent(payload.lyricContent);
  1593. }
  1594. let avSessionDurationMs: number = this.duration;
  1595. if (payload.duration) {
  1596. const durationSeconds = Number(payload.duration);
  1597. if (!Number.isNaN(durationSeconds) && durationSeconds > 0) {
  1598. avSessionDurationMs = durationSeconds * 1000;
  1599. this.duration = avSessionDurationMs;
  1600. this.durationTime = Math.floor(avSessionDurationMs / 1000);
  1601. this.durationStringTime = secondToTime(this.durationTime);
  1602. }
  1603. }
  1604. if (avSessionDurationMs > 0) {
  1605. this.avSessionController.setAVMetadataMusic(this.currentSong, avSessionDurationMs, this.lyricContent);
  1606. }
  1607. this.currentSong = cloneVideoItem(this.currentSong);
  1608. AppStorage.setOrCreate('currentSong', this.currentSong);
  1609. }
  1610. const primaryTarget = targets.length > 0 ? targets[0] : undefined;
  1611. if (primaryTarget) {
  1612. this.persistRemoteMetadataToDb(primaryTarget).catch((error: Error) => {
  1613. Logger.error(TAG, `缓存元数据持久化失败: ${error.message}`);
  1614. });
  1615. }
  1616. if (remoteMetadataUpdates.size > 0) {
  1617. const eventUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
  1618. emitter.emit(eventUpdate, { data: Array.from(remoteMetadataUpdates.values()) });
  1619. }
  1620. this.refreshLazyListViews(mainListUpdated, playlistUpdated);
  1621. }
  1622. private handleEditMusicResult(result: WorkerEditMusicResult): void {
  1623. // 关闭进度条
  1624. DialogHelper.closeDialog(this.loadingDialogId)
  1625. if (result.success) {
  1626. console.log("heanup 编辑信息成功,数据库已同步");
  1627. if (result.coverResult) {
  1628. ToastUtil.showToast('内嵌封面成功');
  1629. }
  1630. ToastUtil.showToast('内嵌音乐标签成功');
  1631. this.isShowMoreView = false;
  1632. this.name = this.titleStr;
  1633. // 同步当前播放的歌曲信息
  1634. if (this.editingItem && this.currentSong && this.editingItem.filePath == this.currentSong.filePath) {
  1635. this.currentSong.name = this.titleStr;
  1636. this.artist = this.artistStr;
  1637. this.currentSong.artist = this.artistStr;
  1638. this.currentSong.album = this.ablumStr;
  1639. this.currentSong.year = this.yearStr;
  1640. this.currentSong.genre = this.genreStr;
  1641. this.currentSong.track = this.trackStr;
  1642. this.currentSong.lyricContent = this.lyricConStr;
  1643. this.currentSong.ALBUMARTIST = this.albumArtistStr;
  1644. this.currentSong.COMPOSER = this.composerStr;
  1645. this.currentSong.LYRICIST = this.lyricistStr;
  1646. this.currentSong.COMMENT = this.commentStr;
  1647. }
  1648. // if (result.needRefreshList && this.modeType == 0) {
  1649. // this.deleteCache(this.currentPath);
  1650. // this.getSortedFiles(this.currentPath);
  1651. // }
  1652. // 同步编辑字段到本地列表
  1653. if (this.editingItem) {
  1654. this.syncEditedFields(this.editingItem);
  1655. this.syncListsAfterEdit(this.editingItem.filePath);
  1656. this.doUpateEditedFields(this.editingItem);
  1657. }
  1658. // 清理临时变量
  1659. this.longItemFilePath = '';
  1660. this.tempLyricContent = '';
  1661. this.isShowEdit = false;
  1662. this.imagePathStr = '';
  1663. } else {
  1664. console.error("heanup 编辑信息失败: " + result.error);
  1665. ToastUtil.showToast('编辑失败: ' + (result.error || '未知错误'));
  1666. // 清理临时变量
  1667. this.longItemFilePath = '';
  1668. this.tempLyricContent = '';
  1669. this.isShowEdit = false;
  1670. this.imagePathStr = '';
  1671. }
  1672. }
  1673. private assignStringMetadata(target: VideoItem, key: keyof VideoItem, value?: string | null, allowEmpty = false): void {
  1674. if (value === undefined || value === null) {
  1675. return;
  1676. }
  1677. const text = value.toString();
  1678. if (!allowEmpty && text.trim().length === 0) {
  1679. return;
  1680. }
  1681. Reflect.set(target, key as string, value);
  1682. }
  1683. private assignNumberMetadata(target: VideoItem, key: keyof VideoItem, value?: number | null): void {
  1684. if (value === undefined || value === null || Number.isNaN(value)) {
  1685. return;
  1686. }
  1687. Reflect.set(target, key as string, value);
  1688. }
  1689. private mergeVideoItemWithPayload(target: VideoItem, payload: WorkerMetadataPayload): void {
  1690. if (!target || !payload) {
  1691. return;
  1692. }
  1693. this.assignStringMetadata(target, 'name', payload.name);
  1694. this.assignStringMetadata(target, 'artist', payload.artist);
  1695. this.assignStringMetadata(target, 'album', payload.album);
  1696. this.assignStringMetadata(target, 'bit_rate', payload.bit_rate);
  1697. this.assignStringMetadata(target, 'duration', payload.duration);
  1698. this.assignStringMetadata(target, 'sampleRate', payload.sampleRate);
  1699. this.assignStringMetadata(target, 'mimeType', payload.mimeType);
  1700. this.assignStringMetadata(target, 'md5Str', payload.md5Str);
  1701. this.assignStringMetadata(target, 'size', payload.size);
  1702. mergeCoverWithPriority(target, payload.pixelMapPath);
  1703. this.assignStringMetadata(target, 'lyricContent', payload.lyricContent, true);
  1704. this.assignStringMetadata(target, 'genre', payload.genre);
  1705. this.assignStringMetadata(target, 'track', payload.track);
  1706. this.assignStringMetadata(target, 'bits_per_raw_sample', payload.bits_per_raw_sample);
  1707. this.assignStringMetadata(target, 'channels', payload.channels);
  1708. this.assignStringMetadata(target, 'channel_layout', payload.channel_layout);
  1709. this.assignStringMetadata(target, 'start_time', payload.start_time);
  1710. this.assignStringMetadata(target, 'year', payload.year);
  1711. this.assignStringMetadata(target, 'disc', payload.disc);
  1712. this.assignStringMetadata(target, 'ALBUMARTIST', payload.ALBUMARTIST);
  1713. this.assignStringMetadata(target, 'COMPOSER', payload.COMPOSER);
  1714. this.assignStringMetadata(target, 'LYRICIST', payload.LYRICIST);
  1715. this.assignStringMetadata(target, 'COMMENT', payload.COMMENT, true);
  1716. this.assignNumberMetadata(target, 'videoSize', payload.videoSize);
  1717. this.assignNumberMetadata(target, 'probe_score', payload.probe_score);
  1718. this.assignNumberMetadata(target, 'nb_streams', payload.nb_streams);
  1719. this.assignNumberMetadata(target, 'nb_programs', payload.nb_programs);
  1720. }
  1721. private mergeVideoItemFromSource(target: VideoItem, source: VideoItem): void {
  1722. if (!target || !source) {
  1723. return;
  1724. }
  1725. this.assignStringMetadata(target, 'name', source.name);
  1726. this.assignStringMetadata(target, 'artist', source.artist);
  1727. this.assignStringMetadata(target, 'album', source.album);
  1728. this.assignStringMetadata(target, 'bit_rate', source.bit_rate);
  1729. this.assignStringMetadata(target, 'duration', source.duration);
  1730. this.assignStringMetadata(target, 'sampleRate', source.sampleRate);
  1731. this.assignStringMetadata(target, 'md5Str', source.md5Str);
  1732. this.assignStringMetadata(target, 'trackCount', source.trackCount);
  1733. this.assignStringMetadata(target, 'mimeType', source.mimeType);
  1734. this.assignStringMetadata(target, 'size', source.size);
  1735. mergeCoverWithPriority(target, source.pixelMapPath, source.isCustomCover ?? 0);
  1736. this.assignStringMetadata(target, 'lyricContent', source.lyricContent, true);
  1737. this.assignStringMetadata(target, 'genre', source.genre);
  1738. this.assignStringMetadata(target, 'track', source.track);
  1739. this.assignStringMetadata(target, 'bits_per_raw_sample', source.bits_per_raw_sample);
  1740. this.assignStringMetadata(target, 'channels', source.channels);
  1741. this.assignStringMetadata(target, 'channel_layout', source.channel_layout);
  1742. this.assignStringMetadata(target, 'start_time', source.start_time);
  1743. this.assignStringMetadata(target, 'year', source.year);
  1744. this.assignStringMetadata(target, 'disc', source.disc);
  1745. this.assignStringMetadata(target, 'ALBUMARTIST', source.ALBUMARTIST);
  1746. this.assignStringMetadata(target, 'COMPOSER', source.COMPOSER);
  1747. this.assignStringMetadata(target, 'LYRICIST', source.LYRICIST);
  1748. this.assignStringMetadata(target, 'COMMENT', source.COMMENT, true);
  1749. this.assignNumberMetadata(target, 'videoSize', source.videoSize);
  1750. this.assignNumberMetadata(target, 'probe_score', source.probe_score);
  1751. this.assignNumberMetadata(target, 'nb_streams', source.nb_streams);
  1752. this.assignNumberMetadata(target, 'nb_programs', source.nb_programs);
  1753. if (source.remote_rel_path && StrUtil.isEmpty(target.remote_rel_path)) {
  1754. target.remote_rel_path = source.remote_rel_path;
  1755. }
  1756. }
  1757. private async hydrateRemoteSongFromDb(item: VideoItem | undefined): Promise<void> {
  1758. if (!item || !isRemoteCloudType(item.type)) {
  1759. return;
  1760. }
  1761. const storagePath = item.remote_rel_path || WebDavUrlUtil.toStoragePath(item.filePath);
  1762. if (!storagePath) {
  1763. return;
  1764. }
  1765. try {
  1766. const cached = await this.table.queryVideoByFilePath(storagePath);
  1767. if (!cached) {
  1768. return;
  1769. }
  1770. this.mergeVideoItemFromSource(item, cached);
  1771. if (StrUtil.isEmpty(item.remote_rel_path)) {
  1772. item.remote_rel_path = storagePath;
  1773. }
  1774. if (item === this.currentSong) {
  1775. if (StrUtil.isNotEmpty(item.name)) {
  1776. this.name = item.name;
  1777. }
  1778. if (StrUtil.isNotEmpty(item.artist)) {
  1779. this.artist = item.artist!;
  1780. }
  1781. if (StrUtil.isNotEmpty(item.pixelMapPath)) {
  1782. this.cover = item.pixelMapPath!;
  1783. }
  1784. if (StrUtil.isNotEmpty(item.lyricContent) && StrUtil.isEmpty(this.lyricContent)) {
  1785. this.applyInlineLyricContent(item.lyricContent as string);
  1786. }
  1787. }
  1788. } catch (error) {
  1789. Logger.error(TAG, `hydrateRemoteSongFromDb 失败: ${(error as Error).message}`);
  1790. }
  1791. }
  1792. private applyInlineLyricContent(content: string): void {
  1793. if (StrUtil.isEmpty(content)) {
  1794. return;
  1795. }
  1796. this.lyricContent = content;
  1797. const lines: string[] = content.split('\n').map((line: string) => line.trim());
  1798. const lyric: Lyric = this.parser.parse(lines);
  1799. this.lyricController.setLyric(lyric);
  1800. this.lyricControllerXF.setLyric(lyric);
  1801. this.lyricControllerSingle.setLyric(lyric);
  1802. }
  1803. private extractParentPathFromStoragePath(path: string): string {
  1804. if (!path) {
  1805. return '';
  1806. }
  1807. const lastSlash = path.lastIndexOf('/');
  1808. if (lastSlash <= 0) {
  1809. return '';
  1810. }
  1811. return path.substring(0, lastSlash);
  1812. }
  1813. private resolveRemoteStoragePath(target: VideoItem): string | null {
  1814. if (!target || !isRemoteCloudType(target.type)) {
  1815. return null;
  1816. }
  1817. if (isWebDavType(target.type)) {
  1818. const storagePath = target.remote_rel_path || WebDavUrlUtil.toStoragePath(target.filePath);
  1819. if (storagePath) {
  1820. target.remote_rel_path = storagePath;
  1821. return storagePath;
  1822. }
  1823. return null;
  1824. }
  1825. if (target.remote_rel_path && target.remote_rel_path.length > 0) {
  1826. return target.remote_rel_path;
  1827. }
  1828. return null;
  1829. }
  1830. private async persistRemoteMetadataToDb(target: VideoItem): Promise<void> {
  1831. if (!this.context || !target || !isRemoteCloudType(target.type)) {
  1832. return;
  1833. }
  1834. const storagePath = this.resolveRemoteStoragePath(target);
  1835. if (!storagePath) {
  1836. return;
  1837. }
  1838. const table = new MediaTable(this.context);
  1839. await new Promise<void>((resolve) => {
  1840. table.getRdbStore(this.context as Context, () => resolve());
  1841. });
  1842. const cloneItem = cloneVideoItem(target);
  1843. cloneItem.filePath = storagePath;
  1844. cloneItem.remote_rel_path = storagePath;
  1845. cloneItem.parentPath = this.extractParentPathFromStoragePath(storagePath);
  1846. await table.saveOrUpdateWebDavItem(cloneItem);
  1847. }
  1848. onPageHide() {
  1849. this.knockController?.immersiveDisableListening();
  1850. }
  1851. @State isFirstStartPlay: boolean = false
  1852. private async startFileDeletionWatcher(): Promise<void> {
  1853. if (!this.rootPath) {
  1854. return;
  1855. }
  1856. if (!this.deletionWatcher) {
  1857. this.deletionWatcher = new FileDeletionWatcher(this.context, this.table);
  1858. }
  1859. try {
  1860. await this.deletionWatcher.watchDirectories([
  1861. this.rootPath,
  1862. this.lockPath,
  1863. this.favPath,
  1864. this.historyPath
  1865. ]);
  1866. } catch (error) {
  1867. Logger.error(TAG, `初始化文件删除监听失败: ${(error as Error).message}`);
  1868. }
  1869. }
  1870. //获取download_path
  1871. async mkDownLoadDir() {
  1872. const documentViewPicker = new picker.DocumentViewPicker()
  1873. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  1874. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  1875. PreferencesUtil.putSync('download_path', this.rootPath+'/')
  1876. this.currentPath = this.rootPath
  1877. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  1878. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  1879. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  1880. Logger.info('onecold rootPath = ' + this.rootPath)
  1881. if (!FileUtil.accessSync(this.favPath)) {
  1882. FileUtil.mkdirSync(this.favPath)
  1883. }
  1884. if (!FileUtil.accessSync(this.historyPath)) {
  1885. FileUtil.mkdirSync(this.historyPath)
  1886. }
  1887. // await this.startFileDeletionWatcher();
  1888. this.getSortedFiles(this.rootPath).then(async () => {
  1889. this.isFavMusic = false
  1890. //穿山甲
  1891. // this.loadBannerAd(CSJUtil.getBannerID())
  1892. this.restoreLastPlayContext();
  1893. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  1894. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  1895. if (ArrayUtil.isEmpty(this.songList)) {
  1896. this.songList = this.videoLocalList.filter(item =>
  1897. item.type === CommonConstants.TYPE_LOCAL && !this.isIsoLocalFile(item))
  1898. } else {
  1899. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  1900. }
  1901. if (ArrayUtil.isNotEmpty(this.songList)) {
  1902. this.isFirstStartPlay = true
  1903. this.sonDataSource.pushArrayData(this.songList)
  1904. if (this.currentSong === undefined) {
  1905. this.isFirstStartPlay = false
  1906. this.currentSong = this.songList[0]
  1907. }
  1908. const restoredUrl = await this.resolvePlaybackUrlForCurrentSong('restore-last-song');
  1909. if (!restoredUrl) {
  1910. return;
  1911. }
  1912. this.videoUrl = restoredUrl;
  1913. Logger.info(TAG, `WebDAV URL同步构建完成: ${this.videoUrl}`);
  1914. this.name = this.currentSong.name
  1915. this.cover = this.currentSong.pixelMapPath
  1916. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  1917. } else {
  1918. this.name = '空空如也'
  1919. }
  1920. })
  1921. this.getFavList(false)
  1922. }
  1923. getFavList(isFavRefresh: boolean) {
  1924. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  1925. this.favList = result
  1926. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  1927. this.videoLocalList = this.favList
  1928. this.updateListData(this.videoLocalList, true)
  1929. }
  1930. })
  1931. }
  1932. getHistoryList(isRefresh: boolean) {
  1933. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  1934. this.historyList = result
  1935. // for (let i = 0; i < this.historyList.length; i++) {
  1936. //
  1937. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  1938. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  1939. // }
  1940. if (isRefresh) {
  1941. this.videoLocalList = this.historyList
  1942. this.updateListData(this.videoLocalList, true)
  1943. }
  1944. })
  1945. }
  1946. // 组件消失生命周期
  1947. aboutToDisappear() {
  1948. console.info('LifeCycleComponent aboutToDisappear');
  1949. if (this.alphaBetHideTimer) {
  1950. clearTimeout(this.alphaBetHideTimer);
  1951. this.alphaBetHideTimer = 0;
  1952. }
  1953. if (this.alphaBetRebuildTimer) {
  1954. clearTimeout(this.alphaBetRebuildTimer);
  1955. this.alphaBetRebuildTimer = 0;
  1956. }
  1957. if (this.pagingScheduleTimer) {
  1958. clearTimeout(this.pagingScheduleTimer);
  1959. this.pagingScheduleTimer = 0;
  1960. }
  1961. if (this.gridWaterScrollIdleTimer) {
  1962. clearTimeout(this.gridWaterScrollIdleTimer);
  1963. this.gridWaterScrollIdleTimer = 0;
  1964. }
  1965. if (this.listUpdateTimer) {
  1966. clearTimeout(this.listUpdateTimer);
  1967. this.listUpdateTimer = 0;
  1968. }
  1969. if (this.mediaLibraryWarmupPrefetchTimer) {
  1970. clearTimeout(this.mediaLibraryWarmupPrefetchTimer);
  1971. this.mediaLibraryWarmupPrefetchTimer = 0;
  1972. }
  1973. this.clearInitialSeekGuardTimer();
  1974. this.alphaBetBuildVersion++;
  1975. this.gridWaterLastActiveTs = 0;
  1976. this.coverThumbCache.dispose();
  1977. this.coverThumbCacheReady = false;
  1978. this.pendingCoverThumbRefresh = false;
  1979. this.deletionWatcher?.stop();
  1980. this.knockController?.immersiveDisableListening();
  1981. this.curIndex = 0
  1982. this.isAppForeground = false;
  1983. emitter.off(EventConstants.EVENT_AUDIO_OPEN);
  1984. emitter.off(EventConstants.EVENT_SCAN_UPDATE);
  1985. emitter.off(EventConstants.EVENT_SWIPE_BACK_UPDATE);
  1986. emitter.off(EventConstants.EVENT_SETTING_UPDATE);
  1987. emitter.off(EventConstants.EVENT_WEBDAV_METADATA_UPDATED);
  1988. emitter.off(EventConstants.EVENT_EQUALIZER_CHANGED);
  1989. emitter.off(EventConstants.EVENT_PLAY_QUEUE_REFRESH);
  1990. this.mDestroyPage = true;
  1991. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  1992. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  1993. this.stop();
  1994. }
  1995. this.mIjkMediaPlayer.off('audioInterrupt');
  1996. this.mIjkMediaPlayer.off('deviceChange');
  1997. if (workerInstance) {
  1998. workerInstance.terminate();
  1999. }
  2000. this.stopPip();
  2001. this.destroyPipController()
  2002. this.getUIContext().getHostContext()!.eventHub.off('playOrPause');
  2003. this.getUIContext().getHostContext()!.eventHub.off('playPrevious');
  2004. this.getUIContext().getHostContext()!.eventHub.off('playNext');
  2005. this.getUIContext().getHostContext()!.eventHub.off('showPlayerView');
  2006. this.getUIContext().getHostContext()!.eventHub.off('openPlayList');
  2007. this.eventHub.off('onStateChange');
  2008. }
  2009. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean,
  2010. openItem?: VideoItem, immediateListUpdate?: boolean, scrollTopAfterUpdate?: boolean) {
  2011. this.isFavMusic = false
  2012. console.info('onecold getSortedFiles 1 curPath '+curPath)
  2013. if (isWorkerPost) {
  2014. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  2015. }
  2016. if (this.modeType !== 0) {
  2017. // 第三方打开场景:非文件夹模式也需要继续执行自动播放
  2018. if (isOpen && destPath) {
  2019. this.openMusic(true, destPath, openItem)
  2020. }
  2021. return
  2022. }
  2023. console.info('onecold getSortedFiles 2')
  2024. this.isCanBack = false
  2025. this.currentPath = curPath
  2026. console.info('onecold getSortedFiles this.currentPath ='+this.currentPath)
  2027. this.titleName = getFileDirName(this.currentPath,this.rootPath)
  2028. if (curPath === this.rootPath) {
  2029. this.rightTopImage = $r('sys.symbol.sort')
  2030. } else {
  2031. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  2032. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  2033. this.rightTopImage = $r('sys.symbol.chevron_left')
  2034. }
  2035. }
  2036. // Get the current file list and calculate its hash
  2037. this.fileList = FileUtil.listFileSync(curPath);
  2038. const currentHash = simpleHash(this.fileList);
  2039. // Check cache
  2040. const cachedValue = this.findCache(curPath);
  2041. Logger.info('onecold cachedValue = ' + cachedValue)
  2042. const cachedHash = this.findStringCache(curPath + '_hash');
  2043. const cachedDirList = this.findCache(curPath + "_dirList");
  2044. if (cachedValue !== undefined&&!this.isRefreshing) {
  2045. // this.videoLocalList = cachedValue;
  2046. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  2047. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  2048. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  2049. }
  2050. this.isRefreshing = false
  2051. this.updateListData(cachedValue, undefined, immediateListUpdate)
  2052. if (scrollTopAfterUpdate) {
  2053. this.scrollToTopForCurrentLayout()
  2054. }
  2055. }
  2056. if (cachedDirList !== undefined) {
  2057. this.dirList = cachedDirList
  2058. }
  2059. //通过当前hash值和缓存hash判断list有没有变化
  2060. if (cachedValue && cachedHash === currentHash) {
  2061. return;
  2062. }
  2063. // this.fileList = FileUtil.listFileSync(curPath)
  2064. let directories: Array<VideoItem> = [];
  2065. let isoFiles: Array<VideoItem> = this.getLocalIsoItems(curPath, this.fileList);
  2066. let files: Array<VideoItem> = [];
  2067. for (let i = 0; i < this.fileList.length; i++) {
  2068. // console.info(`The name of file: ${this.fileList[i]}`);
  2069. let path = curPath + '/' + this.fileList[i]
  2070. if (FileUtil.isDirectory(path)) {
  2071. let item: VideoItem =
  2072. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  2073. '')
  2074. if (this.isShowDir(item.name)) {
  2075. directories.push(item);
  2076. }
  2077. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2078. // Utility.doSortListAscending(directories)
  2079. } else {
  2080. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  2081. let item: VideoItem =
  2082. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  2083. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  2084. files.push(item);
  2085. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2086. // this.doSortListAscending(files)
  2087. }
  2088. }
  2089. }
  2090. }
  2091. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  2092. if (this.currentPath !== this.lockPath) {
  2093. files = result.filter(item => !this.isIsoLocalFile(item));
  2094. }
  2095. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2096. Utility.doSortListAscending(files)
  2097. Utility.doSortListAscending(isoFiles)
  2098. if (this.currentPath === this.rootPath) {
  2099. this.dirList = directories
  2100. this.addCache(curPath + "_dirList", this.dirList);
  2101. }
  2102. //插入广告先注释掉
  2103. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  2104. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  2105. // directories.push(adItem)
  2106. // }
  2107. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  2108. this.videoLocalList = directories.concat(isoFiles).concat(files);
  2109. this.updateListData(this.videoLocalList, undefined, immediateListUpdate)
  2110. if (scrollTopAfterUpdate) {
  2111. this.scrollToTopForCurrentLayout()
  2112. }
  2113. if (ArrayUtil.isNotEmpty(files)) {
  2114. if (this.currentPath != this.rootPath) {
  2115. if (files) {
  2116. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  2117. }
  2118. }
  2119. }
  2120. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2121. this.addCache(curPath, this.videoLocalList);
  2122. await this.saveCacheToStorage();
  2123. this.addStringCache(curPath + '_hash', currentHash);
  2124. }
  2125. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  2126. for (let i = 0; i < this.videoLocalList.length; i++) {
  2127. console.info(`onecold gengxin 1: ${this.videoLocalList[i].name}`);
  2128. }
  2129. // this.setButtonStatus()
  2130. this.openMusic(isOpen, destPath,openItem)
  2131. this.isRefreshing = false
  2132. });
  2133. }
  2134. //第三方app打开天天静听导入音乐后播放
  2135. openMusic(isOpen?: boolean, destPath?: string,openItem?:VideoItem){
  2136. if (isOpen&&destPath) {
  2137. if (destPath === undefined) {
  2138. // 处理 destPath 为 undefined 的情况
  2139. return
  2140. }
  2141. if (destPath.endsWith('.lrc')) {
  2142. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  2143. if (StrUtil.isNotEmpty(this.videoUrl)) {
  2144. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  2145. this.initLyric(lyricPath);
  2146. }
  2147. return
  2148. }
  2149. if(openItem){
  2150. this.doPlay(openItem,0,false,true)
  2151. // this.isShowPlay = true
  2152. this.setShowPlayTrue()
  2153. }
  2154. }
  2155. }
  2156. //扫描文件夹入库
  2157. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  2158. const files = FileUtil.listFileSync(curPath);
  2159. let mediaItems: VideoItem[] = [];
  2160. Logger.info('onecold scanDirectory start ')
  2161. for (const file of files) {
  2162. const fPath = `${curPath}/${file}`;
  2163. if (fPath === this.lockPath) {
  2164. Logger.info(`Skipping locked path: ${fPath}`);
  2165. continue;
  2166. }
  2167. if (FileUtil.isDirectory(fPath)) {
  2168. // Recursively scan subdirectories
  2169. const subDirItems = await this.scanDirectory(fPath);
  2170. mediaItems = mediaItems.concat(subDirItems);
  2171. } else {
  2172. Logger.info('onecold scanDirectory filePath = ' + fPath)
  2173. // Process media files
  2174. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  2175. let mediaItem: VideoItem =
  2176. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2177. mediaItems.push(mediaItem);
  2178. this.table.insert(mediaItem, (id: number) => {
  2179. });
  2180. }
  2181. }
  2182. }
  2183. return mediaItems;
  2184. }
  2185. updateListData(mList: Array<VideoItem>, noSort?: boolean, immediate?: boolean) {
  2186. this.isShowTitleBar = true
  2187. const shouldAnimate = !immediate
  2188. if (this.listUpdateTimer) {
  2189. clearTimeout(this.listUpdateTimer)
  2190. this.listUpdateTimer = 0
  2191. }
  2192. const updateVersion = ++this.listUpdateVersion
  2193. if (shouldAnimate) {
  2194. this.getUIContext().animateTo({ duration: 666 }, () => {
  2195. this.opacityItem = 0.5;
  2196. });
  2197. }
  2198. const applyListData = () => {
  2199. if (updateVersion !== this.listUpdateVersion) {
  2200. return
  2201. }
  2202. this.videoLocalList = mList;
  2203. if (!noSort) {
  2204. if (this.modeType === 0 || this.modeType === 1) {
  2205. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  2206. this.doSortType(this.sortType)
  2207. }
  2208. }
  2209. this.dataSource.pushArrayData(this.videoLocalList)
  2210. if (shouldAnimate) {
  2211. this.getUIContext().animateTo({ duration: 666 }, () => {
  2212. this.opacityItem = 1;
  2213. });
  2214. } else {
  2215. this.opacityItem = 1;
  2216. }
  2217. this.setButtonStatus()
  2218. //添加到字母索引表
  2219. this.markAlphaBetDirty()
  2220. };
  2221. if (immediate) {
  2222. applyListData();
  2223. return;
  2224. }
  2225. this.listUpdateTimer = setTimeout(() => {
  2226. this.listUpdateTimer = 0
  2227. applyListData();
  2228. }, 200);
  2229. }
  2230. getCurFileList(): Array<VideoItem> {
  2231. const source = this.isSearchMode ? this.filteredList : this.videoLocalList
  2232. let files: Array<VideoItem> = [];
  2233. if (ArrayUtil.isNotEmpty(source)) {
  2234. for (let i = 0; i < source.length; i++) {
  2235. if (this.isSelectableLocalItem(source[i])) {
  2236. files.push(source[i]);
  2237. }
  2238. }
  2239. }
  2240. return files
  2241. }
  2242. private isProtectedLocalDirectory(item: VideoItem): boolean {
  2243. return item.type === CommonConstants.TYPE_IS_DIR &&
  2244. (item.name === LocalMusic.STR_LOCK_VIDEO ||
  2245. item.name === LocalMusic.STR_FAC_VIDEO ||
  2246. item.name === LocalMusic.STR_HISTORY_MUSIC)
  2247. }
  2248. private isIsoLocalFile(item?: VideoItem | null): boolean {
  2249. if (!item || item.type !== CommonConstants.TYPE_LOCAL) {
  2250. return false
  2251. }
  2252. return Utility.isIsoByExtension(item.filePath || item.fileName || item.name || '')
  2253. }
  2254. private supportsLocalAudioActions(item: VideoItem): boolean {
  2255. return !!item && item.type !== CommonConstants.TYPE_IS_DIR && !this.isIsoLocalFile(item)
  2256. }
  2257. private buildLocalIsoItem(filePath: string, fileName?: string): VideoItem {
  2258. const displayName = fileName || FileUtil.getFileName(filePath) || filePath
  2259. let fileSize = 0
  2260. try {
  2261. const stat = fs.statSync(filePath) as fs.Stat
  2262. if (typeof stat.size === 'number') {
  2263. fileSize = stat.size
  2264. }
  2265. } catch (_error) {
  2266. }
  2267. const item = new VideoItem(
  2268. displayName,
  2269. filePath,
  2270. filePath,
  2271. CommonConstants.TYPE_LOCAL,
  2272. fileSize,
  2273. Utility.getFormatDateStr(Date.now(), 'yyyy-MM-dd HH:mm'),
  2274. Utility.formatFSize(fileSize),
  2275. '',
  2276. 'ISO 镜像',
  2277. '可提取音频',
  2278. displayName
  2279. )
  2280. item.mimeType = 'application/x-iso9660-image'
  2281. item.duration = ''
  2282. return item
  2283. }
  2284. private getLocalIsoItems(curPath: string, fileNames?: Array<string>): Array<VideoItem> {
  2285. let sourceNames: Array<string> = []
  2286. if (fileNames !== undefined && fileNames.length > 0) {
  2287. sourceNames = fileNames
  2288. } else {
  2289. const listedNames = FileUtil.listFileSync(curPath)
  2290. sourceNames = listedNames ? listedNames : []
  2291. }
  2292. const isoItems: Array<VideoItem> = []
  2293. for (let i = 0; i < sourceNames.length; i++) {
  2294. const name = sourceNames[i]
  2295. const fullPath = `${curPath}/${name}`
  2296. if (FileUtil.isDirectory(fullPath) || !Utility.isIsoByExtension(fullPath)) {
  2297. continue
  2298. }
  2299. isoItems.push(this.buildLocalIsoItem(fullPath, name))
  2300. }
  2301. Utility.doSortListAscending(isoItems)
  2302. return isoItems
  2303. }
  2304. private filterOutLocalIsoItems(items: Array<VideoItem>): Array<VideoItem> {
  2305. return items.filter(item => !this.isIsoLocalFile(item))
  2306. }
  2307. private isSelectableLocalItem(item: VideoItem): boolean {
  2308. if (!item) {
  2309. return false
  2310. }
  2311. if (item.type === CommonConstants.TYPE_LOCAL) {
  2312. return true
  2313. }
  2314. if (item.type === CommonConstants.TYPE_IS_DIR) {
  2315. return !this.isProtectedLocalDirectory(item)
  2316. }
  2317. return false
  2318. }
  2319. private isLocalItemSelected(item: VideoItem): boolean {
  2320. return this.selectedFiles.some(x => x.filePath === item.filePath)
  2321. }
  2322. private hasSelectedDirectories(): boolean {
  2323. return this.selectedFiles.some(item => item.type === CommonConstants.TYPE_IS_DIR)
  2324. }
  2325. private getSelectedPlayableFiles(): Array<VideoItem> {
  2326. return this.selectedFiles.filter(item => item.type === CommonConstants.TYPE_LOCAL && !this.isIsoLocalFile(item))
  2327. }
  2328. private syncLocalSelectionState(): void {
  2329. const selectableItems = this.getCurFileList()
  2330. const selectableKeys: Set<string> = new Set(selectableItems.map(item => item.filePath))
  2331. const nextSelected = this.selectedFiles.filter(item => selectableKeys.has(item.filePath))
  2332. if (nextSelected.length !== this.selectedFiles.length) {
  2333. this.selectedFiles = [...nextSelected]
  2334. }
  2335. this.isAllSelected = nextSelected.length > 0 && nextSelected.length === selectableItems.length
  2336. }
  2337. private enterLocalMultiSelect(item: VideoItem): void {
  2338. if (!this.isSelectableLocalItem(item)) {
  2339. return
  2340. }
  2341. if (!this.isMultiSelect) {
  2342. this.isMultiSelect = true
  2343. }
  2344. if (!this.isLocalItemSelected(item)) {
  2345. this.selectedFiles = [...this.selectedFiles, item]
  2346. }
  2347. this.syncLocalSelectionState()
  2348. }
  2349. private selectSingleItemForDelete(item: VideoItem): void {
  2350. if (!this.isSelectableLocalItem(item)) {
  2351. return
  2352. }
  2353. this.selectedFiles = [item]
  2354. this.isAllSelected = false
  2355. }
  2356. setButtonStatus() {
  2357. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2358. this.isZero = false
  2359. } else {
  2360. this.isZero = true
  2361. }
  2362. if (this.currentPath !== this.rootPath &&
  2363. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  2364. this.isHasDir = true //不为空,说明有子文件夹
  2365. } else {
  2366. this.isHasDir = false
  2367. }
  2368. }
  2369. private getPlayListDisplayCount(): number {
  2370. if (this.playQueueScope === 'history') {
  2371. return this.historyList.length;
  2372. }
  2373. if (this.playQueueScope === 'fav') {
  2374. return this.favList.length;
  2375. }
  2376. if (this.playQueueScope === 'playlist') {
  2377. // 检测是否是流媒体播放(Navidrome/Jellyfin/Emby/AudioStation/Plex/道理鱼等)
  2378. // 如果是,优先返回服务端总数
  2379. const navidromeTotalCount = getNavidromeTotalCount();
  2380. Logger.info('heanup getPlayListDisplayCount', `playQueueScope=playlist, navidromeTotalCount=${navidromeTotalCount}, currentSong=${this.currentSong?.name}, type=${this.currentSong?.type}`);
  2381. if (navidromeTotalCount > 0 && this.currentSong && (
  2382. isNavidromeType(this.currentSong.type) ||
  2383. isJellyfinType(this.currentSong.type) ||
  2384. isEmbyType(this.currentSong.type) ||
  2385. isAudioStationType(this.currentSong.type) ||
  2386. isPlexType(this.currentSong.type) ||
  2387. isDaoLiYuType(this.currentSong.type)
  2388. )) {
  2389. Logger.info('heanup getPlayListDisplayCount', `返回服务端总数: ${navidromeTotalCount}`);
  2390. return navidromeTotalCount;
  2391. }
  2392. Logger.info('heanup getPlayListDisplayCount', `返回 currentSongList.length: ${this.currentSongList.length}`);
  2393. return this.currentSongList.length;
  2394. }
  2395. if (this.playQueueScope === 'view' && this.modeType === 1 && this.totalCount > 0) {
  2396. return this.totalCount;
  2397. }
  2398. Logger.info('heanup getPlayListDisplayCount', `返回 songList.length: ${this.songList.length}, playQueueScope=${this.playQueueScope}`);
  2399. return this.songList.length;
  2400. }
  2401. private restoreLastPlayContext(): void {
  2402. const scope = PreferencesUtil.getStringSync('LastPlayQueueScope', 'view') as string;
  2403. if (scope === 'history' || scope === 'fav' || scope === 'playlist' || scope === 'single') {
  2404. this.playQueueScope = scope;
  2405. } else {
  2406. this.playQueueScope = 'view';
  2407. }
  2408. const lastModeType = PreferencesUtil.getNumberSync('LastPlayModeType', this.modeType);
  2409. const lastTotalCount = PreferencesUtil.getNumberSync('LastPlayTotalCount', 0);
  2410. if (lastModeType === 1 && this.totalCount === 0 && lastTotalCount > 0) {
  2411. this.totalCount = lastTotalCount;
  2412. }
  2413. }
  2414. private async hydrateFullMediaPlayListIfNeeded(isSonList:boolean = true): Promise<void> {
  2415. if (this.isHydratingPlayList) {
  2416. return;
  2417. }
  2418. if (this.playQueueScope !== 'view' || this.modeType !== 1) {
  2419. return;
  2420. }
  2421. if (this.totalCount === 0 || this.songList.length >= this.totalCount) {
  2422. return;
  2423. }
  2424. this.isHydratingPlayList = true;
  2425. try {
  2426. const fullList: VideoItem[] = [];
  2427. let pageIndex = 0;
  2428. let hasMore = true;
  2429. while (hasMore) {
  2430. const result = await this.table.queryMediaLibraryPaged({
  2431. pageIndex,
  2432. pageSize: this.pageSize,
  2433. sortType: this.sortType,
  2434. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  2435. isShowFileName: this.isShowFileName
  2436. });
  2437. if (result.items.length === 0) {
  2438. break;
  2439. }
  2440. fullList.push(...result.items);
  2441. hasMore = result.hasMore;
  2442. pageIndex += 1;
  2443. if (fullList.length >= result.totalCount) {
  2444. hasMore = false;
  2445. }
  2446. }
  2447. if (fullList.length > 0) {
  2448. if(isSonList){
  2449. this.songList = fullList;
  2450. this.sonDataSource.pushArrayData(this.songList);
  2451. }else{
  2452. this.videoLocalList = fullList;
  2453. this.dataSource.pushArrayData(this.videoLocalList);
  2454. }
  2455. }
  2456. } finally {
  2457. this.isHydratingPlayList = false;
  2458. }
  2459. }
  2460. @Builder
  2461. SortMenuBuilder() {
  2462. Menu() {
  2463. MenuItem({
  2464. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.person')),
  2465. content: "按艺术家",
  2466. builder: this.SubSortBuilder(SortMode.ByArtist),
  2467. symbolEndIcon: this.isSortTypeInRange(SortMode.ByArtist) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2468. })
  2469. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByArtist)))
  2470. MenuItem({
  2471. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat_size_square')),
  2472. content: "按专辑",
  2473. builder: this.SubSortBuilder(SortMode.ByAlbum),
  2474. symbolEndIcon: this.isSortTypeInRange(SortMode.ByAlbum) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2475. })
  2476. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByAlbum)))
  2477. MenuItem({
  2478. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat')),
  2479. content: "按名称",
  2480. builder: this.SubSortBuilder(SortMode.ByName),
  2481. symbolEndIcon: this.isSortTypeInRange(SortMode.ByName) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2482. })
  2483. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByName)))
  2484. MenuItem({
  2485. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2486. content: $r('app.string.sort_by_time'),
  2487. builder: this.SubSortBuilder(SortMode.ByTime),
  2488. symbolEndIcon: this.isSortTypeInRange(SortMode.ByTime) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2489. })
  2490. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByTime)))
  2491. MenuItem({
  2492. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  2493. content: '按碟片音轨号',
  2494. builder: this.SubSortBuilder(SortMode.ByDiscTrack),
  2495. symbolEndIcon: this.isSortTypeInRange(SortMode.ByDiscTrack) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2496. })
  2497. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByDiscTrack)))
  2498. .visibility((this.modeType==0||(this.modeType==2&&this.isCanBack)||
  2499. (this.modeType==3&&this.isCanBack))?Visibility.Visible:Visibility.None)
  2500. }.attributeModifier(new MenuModifier())
  2501. }
  2502. @Builder
  2503. SortMenuForArtistAblumBuilder() {
  2504. Menu() {
  2505. MenuItem({
  2506. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat')),
  2507. content: "按名称",
  2508. builder: this.SubSortBuilder(SortMode.ByName),
  2509. symbolEndIcon: this.isSortTypeInRange(SortMode.ByName) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2510. })
  2511. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByName)))
  2512. MenuItem({
  2513. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2514. content: '按数量',
  2515. builder: this.SubSortBuilder(SortMode.ByCount),
  2516. symbolEndIcon: this.isSortTypeInRange(SortMode.ByCount) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2517. })
  2518. .backgroundColor(this.getSortModeItemBackground(this.isSortTypeInRange(SortMode.ByCount)))
  2519. }.attributeModifier(new MenuModifier())
  2520. }
  2521. @Builder SubSortBuilder(sortType: number){
  2522. Menu(){
  2523. MenuItem({
  2524. content: "升序",
  2525. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_up')),
  2526. symbolEndIcon: this.sortType === sortType ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2527. })
  2528. .backgroundColor(this.getSortOrderItemBackground(this.sortType === sortType, true))
  2529. .onClick(async () => {
  2530. await this.doSortType(sortType)
  2531. })
  2532. MenuItem({
  2533. content: "降序",
  2534. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_down')),
  2535. symbolEndIcon: this.sortType === sortType + 1 ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2536. })
  2537. .backgroundColor(this.getSortOrderItemBackground(this.sortType === sortType + 1, false))
  2538. .onClick(async () => {
  2539. await this.doSortType(sortType + 1) // 降序的sortType = 升序的sortType + 1
  2540. })
  2541. }
  2542. }
  2543. async doSortType(index: number): Promise<void> {
  2544. Logger.info('heanup LocalMusic', `doSortType: 切换排序方式 sortType=${index}, mode=${this.modeType}, isCanBack=${this.isCanBack}`);
  2545. this.sortType = index;
  2546. this.saveSortTypeForCurrentMode(index);
  2547. // 详情页模式(modeType=2/3 且 isCanBack=true): 重新查询当前项目的歌曲
  2548. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  2549. await this.reloadCurrentDetailSongs();
  2550. } else {
  2551. // 分页模式下,排序需要重新从数据库查询
  2552. await this.resetAndLoadFirstPage();
  2553. }
  2554. }
  2555. /**
  2556. * 重新加载当前详情页(专辑/艺术家)的歌曲数据
  2557. * 用于详情页切换排序方式时重新查询并排序
  2558. */
  2559. private async reloadCurrentDetailSongs(): Promise<void> {
  2560. Logger.info('heanup LocalMusic', `reloadCurrentDetailSongs: modeType=${this.modeType}, titleName=${this.titleName}, sortType=${this.sortType}`);
  2561. try {
  2562. if (this.modeType === 2) {
  2563. // 艺术家详情页: 重新查询该艺术家的歌曲
  2564. const mList = await this.table.querySongsByArtist(this.titleName, this.sortType, this.isShowFileName);
  2565. if (ArrayUtil.isNotEmpty(mList)) {
  2566. // 使用带排序类型的缓存键
  2567. const cacheKey = `${this.titleName}_sort_${this.sortType}`;
  2568. this.artistMap.set(cacheKey, mList);
  2569. this.totalCount = mList.length;
  2570. // 使用 noSort=true 避免在 updateListData 中重新排序导致死循环
  2571. this.updateListData(mList, true);
  2572. Logger.info('heanup LocalMusic', `reloadCurrentDetailSongs: 艺术家详情页重新加载完成, 歌曲数=${mList.length}`);
  2573. }
  2574. } else if (this.modeType === 3) {
  2575. // 专辑详情页: 重新查询该专辑的歌曲
  2576. const albumList = await this.table.querySongsByAlbum(this.titleName, this.sortType, this.isShowFileName);
  2577. if (ArrayUtil.isNotEmpty(albumList)) {
  2578. // 使用带排序类型的缓存键
  2579. const cacheKey = `${this.titleName}_sort_${this.sortType}`;
  2580. this.albumMap.set(cacheKey, albumList);
  2581. this.totalCount = albumList.length;
  2582. // 使用 noSort=true 避免在 updateListData 中重新排序导致死循环
  2583. this.updateListData(albumList, true);
  2584. Logger.info('heanup LocalMusic', `reloadCurrentDetailSongs: 专辑详情页重新加载完成, 歌曲数=${albumList.length}`);
  2585. }
  2586. }
  2587. } catch (err) {
  2588. const error = err as Error;
  2589. Logger.error('heanup LocalMusic', `reloadCurrentDetailSongs error: ${error.message}`);
  2590. ToastUtil.showToast('重新加载数据失败');
  2591. }
  2592. }
  2593. /**
  2594. * 根据当前模式保存排序类型到不同的存储键
  2595. * 区分列表页和详情页的排序设置
  2596. */
  2597. private saveSortTypeForCurrentMode(sortType: number): void {
  2598. let storageKey = SettingPage.SORT_TYPE;
  2599. if (this.modeType === 2) {
  2600. // 艺术家模式
  2601. if (this.isCanBack) {
  2602. storageKey = 'SORT_TYPE_ARTIST_DETAIL'; // 艺术家详情页排序
  2603. } else {
  2604. storageKey = 'SORT_TYPE_ARTIST'; // 艺术家列表页排序
  2605. }
  2606. } else if (this.modeType === 3) {
  2607. // 专辑模式
  2608. if (this.isCanBack) {
  2609. storageKey = 'SORT_TYPE_ALBUM_DETAIL'; // 专辑详情页排序
  2610. } else {
  2611. storageKey = 'SORT_TYPE_ALBUM'; // 专辑列表页排序
  2612. }
  2613. } else {
  2614. storageKey = SettingPage.SORT_TYPE;
  2615. }
  2616. PreferencesUtil.putSync(storageKey, sortType);
  2617. Logger.info('heanup LocalMusic', `saveSortTypeForCurrentMode: mode=${this.modeType}, isCanBack=${this.isCanBack}, sortType=${sortType}, key=${storageKey}`);
  2618. }
  2619. /**
  2620. * 根据当前模式加载排序类型
  2621. * 区分列表页和详情页的排序设置
  2622. */
  2623. private loadSortTypeForCurrentMode(): number {
  2624. let storageKey = SettingPage.SORT_TYPE;
  2625. let defaultSortType = 4;
  2626. if (this.modeType === 2) {
  2627. // 艺术家模式
  2628. if (this.isCanBack) {
  2629. storageKey = 'SORT_TYPE_ARTIST_DETAIL'; // 艺术家详情页排序
  2630. defaultSortType = 4; // 详情页默认按名称升序
  2631. } else {
  2632. storageKey = 'SORT_TYPE_ARTIST'; // 艺术家列表页排序
  2633. defaultSortType = 9; // 列表页默认按数量降序
  2634. }
  2635. } else if (this.modeType === 3) {
  2636. // 专辑模式
  2637. if (this.isCanBack) {
  2638. storageKey = 'SORT_TYPE_ALBUM_DETAIL'; // 专辑详情页排序
  2639. defaultSortType = 4; // 详情页默认按名称升序
  2640. } else {
  2641. storageKey = 'SORT_TYPE_ALBUM'; // 专辑列表页排序
  2642. defaultSortType = 9; // 列表页默认按数量降序
  2643. }
  2644. }
  2645. return PreferencesUtil.getNumberSync(storageKey, defaultSortType);
  2646. }
  2647. /**
  2648. * 检查当前sortType是否在指定排序类型的范围内
  2649. * 用于判断是否显示打勾图标
  2650. * @param baseSortType 基础排序类型(升序的值)
  2651. * @returns 如果当前sortType是该排序类型的升序或降序,返回true
  2652. */
  2653. private isSortTypeInRange(baseSortType: number): boolean {
  2654. return this.sortType === baseSortType || this.sortType === baseSortType + 1;
  2655. }
  2656. private getSortModeItemBackground(isSelected: boolean): ResourceColor {
  2657. if (!isSelected) {
  2658. return Color.Transparent;
  2659. }
  2660. return this.isDarkMode ? '#334967' : '#EAF2FF';
  2661. }
  2662. private getSortOrderItemBackground(isSelected: boolean, isAsc: boolean): ResourceColor {
  2663. if (!isSelected) {
  2664. return Color.Transparent;
  2665. }
  2666. if (isAsc) {
  2667. return this.isDarkMode ? '#295B8A' : '#DCEEFF';
  2668. }
  2669. return this.isDarkMode ? '#7A4D22' : '#FFE9D5';
  2670. }
  2671. showSheelDialog() {
  2672. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  2673. // this.showTips()
  2674. // return
  2675. // }
  2676. this.showAddDialog()
  2677. }
  2678. showAddDialog() {
  2679. if (this.modeType === 2 || this.modeType === 3) {
  2680. return
  2681. }
  2682. DialogHelper.showActionSheetDialog({
  2683. title: "请选择添加方式(建议歌词文件一起导入)",
  2684. sheets: [
  2685. { value: "新建文件夹", fontColor: $r('app.color.text_color') },
  2686. { value: "手动导入", fontColor: $r('app.color.text_color') },
  2687. { value: "自动导入", fontColor: $r('app.color.text_color') },
  2688. { value: "全选导入", fontColor: $r('app.color.text_color') },
  2689. ],
  2690. maskColor: Color.Transparent,
  2691. backgroundColor: $r('app.color.bg_card'),
  2692. transition: AnimationHelper.transitionInDown(555),
  2693. onAction: (index) => {
  2694. switch (index) {
  2695. case 0:
  2696. if (this.modeType === 0) {
  2697. this.showMkDialog()
  2698. } else {
  2699. ToastUtil.showToast('请切换到首页才能新建文件夹!')
  2700. }
  2701. break;
  2702. case 1:
  2703. this.callFilePickerSelectFile()
  2704. break;
  2705. case 2:
  2706. this.showTips()
  2707. break;
  2708. case 3:
  2709. this.goSelectMusic()
  2710. break;
  2711. }
  2712. }
  2713. })
  2714. }
  2715. //拉起音频
  2716. goSelectMusic() {
  2717. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  2718. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  2719. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  2720. ) {
  2721. ToastUtil.showToast('暂时不支持该设备')
  2722. return
  2723. }
  2724. try {
  2725. let documentSelectOptions = new picker.DocumentSelectOptions();
  2726. documentSelectOptions.authMode = true
  2727. documentSelectOptions.multiAuthMode = true
  2728. if( deviceInfo.sdkApiVersion>=21){//如果api大于21 ,可以支持1w首歌以上
  2729. documentSelectOptions.maxSelectNumber = 20000
  2730. }
  2731. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  2732. let documentPicker = new picker.DocumentViewPicker(this.context);
  2733. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  2734. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  2735. this.saveVideoDatas(documentSelectResult)
  2736. }
  2737. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  2738. JSON.stringify(documentSelectResult));
  2739. }).catch((err: BusinessError) => {
  2740. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  2741. });
  2742. } catch (error) {
  2743. let err: BusinessError = error as BusinessError;
  2744. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2745. }
  2746. }
  2747. async showTips() {
  2748. try {
  2749. this.getUIContext().getPromptAction().showDialog({
  2750. title: '导入指南',
  2751. message:'用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  2752. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  2753. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  2754. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后去文件扫描一下。\n',
  2755. buttons: [
  2756. {
  2757. text: '知道了',
  2758. color: '#000000'
  2759. },
  2760. ]
  2761. }, (err, data) => {
  2762. if (err) {
  2763. console.error('showDialog err: ' + err);
  2764. return;
  2765. }
  2766. console.info('showDialog success callback, click button: ' + data.index);
  2767. });
  2768. } catch (error) {
  2769. let message = (error as BusinessError).message;
  2770. let code = (error as BusinessError).code;
  2771. console.error(`showDialog args error code is ${code}, message is ${message}`);
  2772. };
  2773. }
  2774. showMkDialog() {
  2775. DialogHelper.showTextInputDialog({
  2776. title: '新建歌单',
  2777. maskColor: Color.Transparent,
  2778. text: '',
  2779. transition: AnimationHelper.transitionInDown(666),
  2780. onChange: (text) => {
  2781. console.error("onChange: " + text);
  2782. },
  2783. onAction: (action, dialogId, content) => {
  2784. // ToastUtil.showToast('content = ' +content)
  2785. if (action == DialogAction.TWO) {
  2786. const newName = content
  2787. const newPath = this.currentPath + '/' + newName
  2788. FileUtil.mkdir(newPath, true).then(() => {
  2789. this.cache.delete(this.currentPath); // 删除目标路径缓存
  2790. this.getSortedFiles(this.currentPath)
  2791. }).catch((error: BusinessError) => {
  2792. console.error(error.message);
  2793. });
  2794. }
  2795. }
  2796. })
  2797. }
  2798. @State progress: number = 0;
  2799. async saveVideoDatas(uris:string[],isOpen?:boolean){
  2800. if (ArrayUtil.isEmpty(uris)) {
  2801. return;
  2802. }
  2803. console.info('onecold this.isCopyFileToDownLoad = ' + this.isCopyFileToDownLoad);
  2804. if(this.isCopyFileToDownLoad||this.currentPath==this.lockPath||isOpen){
  2805. this.saveVideoDatasToDownLoad(uris,isOpen)
  2806. return
  2807. }
  2808. // 初始化进度条
  2809. this.progress = 0;
  2810. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  2811. progress: this.progress,
  2812. backCancel: false,
  2813. autoCancel: false,
  2814. loadColor: $r('app.color.title_bar_bg'),
  2815. fontColor: $r('app.color.title_bar_bg')
  2816. });
  2817. // 计算处理总数用于进度计算
  2818. const totalItems = uris.length;
  2819. let processedItems = 0;
  2820. for (let i = 0; i < uris.length; i++) {
  2821. let filePath = uris[i];
  2822. try {
  2823. if (this.currentPath !== this.lockPath) { // 判断不是私密音乐,才入库
  2824. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2825. let mediaItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context,
  2826. filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2827. console.info('onecold saveVideoDatas filePath = ' + filePath)
  2828. if (!filePath.includes(this.rootPath)) {
  2829. console.info('onecold saveVideoDatas mediaItem.parentPath111 = ' + mediaItem.parentPath)
  2830. mediaItem.parentPath = this.currentPath;
  2831. }
  2832. console.info('onecold saveVideoDatas mediaItem.parentPath = ' + mediaItem.parentPath)
  2833. this.table.insert(mediaItem, (id: number) => {
  2834. // 插入完成回调
  2835. });
  2836. }
  2837. }
  2838. // 更新进度
  2839. processedItems++;
  2840. this.progress = Math.floor((processedItems / totalItems) * 100);
  2841. DialogHelper.updateLoading(this.loadingProgressDialogId,` 正在处理 ${this.progress}%`, this.progress);
  2842. } catch (error) {
  2843. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2844. // 即使出错也更新进度
  2845. processedItems++;
  2846. this.progress = Math.floor((processedItems / totalItems) * 100);
  2847. DialogHelper.updateLoading(this.loadingProgressDialogId,` 正在处理 ${this.progress}%`, this.progress);
  2848. }
  2849. }
  2850. // 关闭进度条
  2851. DialogHelper.closeDialog(this.loadingProgressDialogId)
  2852. this.isZero = false
  2853. // 删除目标路径缓存
  2854. setTimeout(() => {
  2855. this.cache.delete(this.currentPath);
  2856. this.getSortedFiles(this.currentPath,false,uris[0],isOpen)
  2857. this.setButtonStatus()
  2858. }, 500);
  2859. }
  2860. async saveVideoDatasToDownLoad(uris: string[], isOpen?: boolean) {
  2861. if (ArrayUtil.isEmpty(uris)) {
  2862. return;
  2863. }
  2864. let newUris: string[] = [];
  2865. this.progress = 0
  2866. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  2867. progress: this.progress,
  2868. backCancel: false,
  2869. autoCancel: false,
  2870. loadColor: this.themeColor,
  2871. fontColor: this.themeColor
  2872. });
  2873. // 计算所有文件的总大小
  2874. let totalSize = 0;
  2875. for (let uri of uris) {
  2876. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  2877. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  2878. await fileIo.close(sourceFile.fd);
  2879. }
  2880. let totalRead = 0;
  2881. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  2882. Logger.info(TAG, 'destPath uri: ' + destPath);
  2883. for (let i = 0; i < uris.length; i++) {
  2884. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  2885. Logger.info(TAG, 'filePath uri: ' + filePath);
  2886. newUris.push(filePath);
  2887. try {
  2888. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  2889. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  2890. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  2891. const buffer = new ArrayBuffer(buffSize);
  2892. let len = await fileIo.read(sourceFile.fd, buffer);
  2893. while (len > 0) {
  2894. await fileIo.write(destFile.fd, buffer.slice(0, len));
  2895. totalRead += len;
  2896. // 计算总进度
  2897. this.progress = Math.floor((totalRead / totalSize) * 100);
  2898. DialogHelper.updateLoading( this.loadingProgressDialogId,`正在导入 ${this.progress}%`, this.progress);
  2899. len = await fileIo.read(sourceFile.fd, buffer);
  2900. }
  2901. await fileIo.close(sourceFile.fd);
  2902. await fileIo.close(destFile.fd);
  2903. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  2904. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2905. let mediaItem: VideoItem =
  2906. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2907. this.table.insert(mediaItem, (id: number) => {
  2908. // 删除目标路径缓存
  2909. this.cache.delete(this.currentPath);
  2910. this.getSortedFiles(this.currentPath, true, destPath, isOpen,mediaItem)
  2911. });
  2912. }
  2913. }
  2914. } catch (error) {
  2915. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2916. }
  2917. }
  2918. DialogHelper.closeDialog(this.loadingProgressDialogId);
  2919. this.isZero = false
  2920. Logger.info(TAG, 'scan select video result:' + newUris)
  2921. }
  2922. //拉起音频
  2923. // goSelectMusic(){
  2924. //
  2925. // try {
  2926. // let audioSelectOptions = new picker.AudioSelectOptions();
  2927. // let audioPicker = new picker.AudioViewPicker(this.context);
  2928. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  2929. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  2930. // this.saveVideoDatas(audioSelectResult)
  2931. // }
  2932. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  2933. // }).catch((err: BusinessError) => {
  2934. //
  2935. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  2936. // });
  2937. // } catch (error) {
  2938. // let err: BusinessError = error as BusinessError;
  2939. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2940. // }
  2941. //
  2942. //
  2943. //
  2944. // }
  2945. async goSelectImage(item: VideoItem): Promise<string | undefined> {
  2946. if (!item) {
  2947. return undefined;
  2948. }
  2949. try {
  2950. let selectUris: Array<string> = [];
  2951. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  2952. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  2953. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  2954. photoSelectOptions.maxSelectNumber = 1;
  2955. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  2956. selectUris = photoSelectResult.photoUris;
  2957. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  2958. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  2959. console.info('file fd: ' + file.fd);
  2960. let name = await MD5.digestSync(this.videoUrl)+'.jpg'
  2961. let imagePath = this.context.filesDir + FileUtil.separator + name
  2962. imagePath = fileUri.getUriFromPath(imagePath)
  2963. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  2964. fileIo.copyFileSync(file.fd, file2.fd)
  2965. fileIo.closeSync(file);
  2966. fileIo.closeSync(file2);
  2967. if (item.filePath == this.currentSong?.filePath) {
  2968. this.cover = imagePath
  2969. if (this.currentSong) {
  2970. this.currentSong.isCustomCover = 1;
  2971. }
  2972. }
  2973. if (item) {
  2974. item.pixelMapPath = imagePath
  2975. item.isCustomCover = 1;
  2976. }
  2977. if (isRemoteCloudType(item.type)) {
  2978. return FileUtil.getFilePath(imagePath);
  2979. }
  2980. this.table.updateCustomCoverPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  2981. if (success) {
  2982. this.doUpdateData()
  2983. console.log("onecold 更新音乐封面成功,数据库已同步");
  2984. } else {
  2985. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  2986. }
  2987. });
  2988. LogUtil.debug("onecold this.cover =" + this.cover)
  2989. return FileUtil.getFilePath(imagePath); // Return the image path here
  2990. } catch (err) {
  2991. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  2992. return undefined;
  2993. }
  2994. }
  2995. private async pickCoverImageToSandbox(): Promise<string | undefined> {
  2996. try {
  2997. const photoPicker = new photoAccessHelper.PhotoViewPicker();
  2998. const photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  2999. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  3000. photoSelectOptions.maxSelectNumber = 1;
  3001. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  3002. const selectUris = photoSelectResult.photoUris;
  3003. if (!selectUris || selectUris.length === 0) {
  3004. return undefined;
  3005. }
  3006. const coverDir = this.context.filesDir + FileUtil.separator + 'ttmusic_cover';
  3007. if (!FileUtil.accessSync(coverDir)) {
  3008. FileUtil.mkdirSync(coverDir);
  3009. }
  3010. const sourceUri = selectUris[0];
  3011. const sourceName = FileUtil.getFileName(sourceUri) || '';
  3012. let suffix = '.jpg';
  3013. const dotIndex = sourceName.lastIndexOf('.');
  3014. if (dotIndex >= 0) {
  3015. suffix = sourceName.substring(dotIndex);
  3016. }
  3017. const targetName = `${Date.now()}_${await MD5.digestSync(sourceUri)}${suffix}`;
  3018. const targetPath = coverDir + FileUtil.separator + targetName;
  3019. const sourceFile = fileIo.openSync(sourceUri, fileIo.OpenMode.READ_ONLY);
  3020. const targetFile = fileIo.openSync(targetPath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
  3021. fileIo.copyFileSync(sourceFile.fd, targetFile.fd);
  3022. fileIo.closeSync(sourceFile.fd);
  3023. fileIo.closeSync(targetFile.fd);
  3024. return fileUri.getUriFromPath(targetPath);
  3025. } catch (error) {
  3026. const err = error as BusinessError;
  3027. Logger.error(TAG, `pickCoverImageToSandbox failed, code: ${err.code}, message: ${err.message}`);
  3028. return undefined;
  3029. }
  3030. }
  3031. private async replaceCurrentSongCoverByAlbum(): Promise<void> {
  3032. if (!this.currentSong || StrUtil.isEmpty(this.currentSong.filePath)) {
  3033. ToastUtil.showToast('当前歌曲无效');
  3034. return;
  3035. }
  3036. const sandboxCoverUri = await this.pickCoverImageToSandbox();
  3037. if (StrUtil.isEmpty(sandboxCoverUri)) {
  3038. return;
  3039. }
  3040. const coverUri = sandboxCoverUri as string;
  3041. this.loadingDialogId = DialogHelper.showLoadingDialog();
  3042. try {
  3043. if (isRemoteCloudType(this.currentSong.type)) {
  3044. this.cover = coverUri;
  3045. this.currentSong.pixelMapPath = coverUri;
  3046. this.currentSong.isCustomCover = 1;
  3047. this.syncRemoteManagerSong(this.currentSong);
  3048. await this.persistRemoteMetadataToDb(this.currentSong);
  3049. this.emitRemoteMetadataUpdated(this.currentSong);
  3050. this.currentSong = cloneVideoItem(this.currentSong);
  3051. AppStorage.setOrCreate('currentSong', this.currentSong);
  3052. ToastUtil.showToast('更换封面成功');
  3053. return;
  3054. }
  3055. if (this.currentSong.type !== CommonConstants.TYPE_LOCAL) {
  3056. ToastUtil.showToast('当前歌曲类型暂不支持更换封面');
  3057. return;
  3058. }
  3059. const task = new taskpool.Task(
  3060. replaceLocalMusicCoverTask,
  3061. this.context,
  3062. this.currentSong.filePath,
  3063. FileUtil.getFilePath(coverUri)
  3064. );
  3065. const result = await taskpool.execute(task, taskpool.Priority.HIGH) as boolean;
  3066. if (!result) {
  3067. ToastUtil.showToast('更换封面失败');
  3068. return;
  3069. }
  3070. this.cover = coverUri;
  3071. this.currentSong.pixelMapPath = coverUri;
  3072. this.currentSong.isCustomCover = 1;
  3073. await this.doUpateEditedFields(this.currentSong);
  3074. ToastUtil.showToast('更换封面成功');
  3075. } catch (error) {
  3076. Logger.error(TAG, `replaceCurrentSongCoverByAlbum failed: ${JSON.stringify(error)}`);
  3077. ToastUtil.showToast('更换封面失败');
  3078. } finally {
  3079. DialogHelper.closeDialog(this.loadingDialogId);
  3080. }
  3081. }
  3082. // 拉起picker选择文件管理器
  3083. async callFilePickerSelectFile(): Promise<void> {
  3084. try {
  3085. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  3086. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  3087. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  3088. } else {
  3089. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  3090. }
  3091. let documentPicker = new picker.DocumentViewPicker();
  3092. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  3093. Logger.info(TAG,
  3094. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  3095. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  3096. this.saveVideoDatas(DocumentSelectResult)
  3097. }
  3098. }).catch((err: BusinessError) => {
  3099. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  3100. });
  3101. } catch (err) {
  3102. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  3103. }
  3104. }
  3105. //重命名的对话框
  3106. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  3107. if(!item.filePath.includes(this.packName)){
  3108. ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限重命名')
  3109. return
  3110. }
  3111. DialogHelper.showTextInputDialog({
  3112. title: '重命名',
  3113. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : (item.fileName || item.name),
  3114. maskColor: Color.Transparent,
  3115. backgroundColor: Color.Grey,
  3116. transition: AnimationHelper.transitionInDown(666),
  3117. onChange: (text) => {
  3118. console.error("onChange: " + text);
  3119. },
  3120. onAction: (action, dialogId, content) => {
  3121. // ToastUtil.showToast('content = ' +content)
  3122. if (action == DialogAction.TWO) {
  3123. const newName = content
  3124. const newPath = this.currentPath + '/' + newName
  3125. console.log("onecold item = " + item.type);
  3126. this.doReName(index, newName, filePath, newPath, item)
  3127. }
  3128. }
  3129. })
  3130. }
  3131. //剪切 移动到另个文件夹的对话框
  3132. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  3133. Logger.info('onecold showCutDialog')
  3134. let mList: Array<string> = []
  3135. let rPath = this.rootPath
  3136. if (isCurrent) {
  3137. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  3138. rPath = this.currentPath
  3139. } else {
  3140. mList = Utility.getNameList(this.dirList);
  3141. rPath = this.rootPath
  3142. }
  3143. let dataBean = new BubbleBean()
  3144. dataBean.data = mList
  3145. dataBean.color = this.themeColor
  3146. dataBean.onItemClick = (i) => {
  3147. const targetName = item.fileName || item.name
  3148. const newPath = rPath + '/' + mList[i] + '/' + targetName
  3149. Logger.info('newPath = ' + newPath)
  3150. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  3151. ToastUtil.showToast('移动成功')
  3152. this.table.deleteData(item, () => {
  3153. });
  3154. if (!Utility.isIsoByExtension(newPath)) {
  3155. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  3156. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3157. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  3158. this.table.insert(newItem, (id: number) => {
  3159. //加入数据库
  3160. });
  3161. }
  3162. }
  3163. this.cache.delete(this.currentPath); // 删除原路径缓存
  3164. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  3165. this.getSortedFiles(this.currentPath, true)
  3166. }).catch((error: BusinessError) => {
  3167. console.error(error.message);
  3168. });
  3169. XPopup.dismissTop()
  3170. }
  3171. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  3172. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  3173. popupPosition = PopupPosition.TOP
  3174. }
  3175. if (index <= 3) {
  3176. popupPosition = PopupPosition.BOTTOM
  3177. }
  3178. let pup: XPopup
  3179. if (this.isDarkMode) {
  3180. pup = XPopup.Builder()
  3181. .setPopupPosition(popupPosition)
  3182. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  3183. .setBackgroundColor(Color.Black)
  3184. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3185. .show()
  3186. } else {
  3187. pup = XPopup.Builder()
  3188. .setPopupPosition(popupPosition)
  3189. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  3190. .setBackgroundColor(Color.White)
  3191. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3192. .show()
  3193. }
  3194. }
  3195. //复制 到另个文件夹的对话框
  3196. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  3197. Logger.info('onecoldv showCopyDialog')
  3198. let mList: Array<string> = []
  3199. let rPath = this.rootPath
  3200. if (isCurrent) {
  3201. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  3202. rPath = this.currentPath
  3203. } else {
  3204. mList = Utility.getNameList(this.dirList);
  3205. rPath = this.rootPath
  3206. }
  3207. let dataBean = new BubbleBean()
  3208. dataBean.data = mList
  3209. dataBean.isCopy = true
  3210. dataBean.color = this.themeColor
  3211. dataBean.onItemClick = (i) => {
  3212. const targetName = item.fileName || item.name
  3213. const newPath = rPath + '/' + mList[i] + '/' + targetName
  3214. Logger.info('newPath = ' + newPath)
  3215. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  3216. ToastUtil.showToast('复制成功')
  3217. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  3218. this.getSortedFiles(this.currentPath)
  3219. if (!Utility.isIsoByExtension(newPath)) {
  3220. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  3221. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3222. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  3223. this.table.insert(newItem, (id: number) => {
  3224. //加入数据库
  3225. });
  3226. }
  3227. }
  3228. }).catch((error: BusinessError) => {
  3229. console.error(error.message);
  3230. });
  3231. XPopup.dismissTop()
  3232. }
  3233. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  3234. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  3235. popupPosition = PopupPosition.TOP
  3236. }
  3237. if (index <= 3) {
  3238. popupPosition = PopupPosition.BOTTOM
  3239. }
  3240. let pup: XPopup
  3241. if (this.isDarkMode) {
  3242. pup = XPopup.Builder()
  3243. .setPopupPosition(popupPosition)
  3244. .atView(id)
  3245. .setMaxHeight('60%')
  3246. .setBackgroundColor(Color.Black)
  3247. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3248. .show();
  3249. } else {
  3250. pup = XPopup.Builder()
  3251. .setPopupPosition(popupPosition)
  3252. .atView(id)
  3253. .setMaxHeight('60%')
  3254. .setBackgroundColor(Color.White)
  3255. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3256. .show();
  3257. }
  3258. }
  3259. //重命名索引index的视频
  3260. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  3261. FileUtil.rename(oldPath, newPath).then(async () => {
  3262. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  3263. let refreshedItem: VideoItem = info
  3264. if (info.type === CommonConstants.TYPE_IS_DIR) {
  3265. //如果是文件夹先删除源数据,再添加新数据
  3266. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  3267. if (success) {
  3268. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  3269. } else {
  3270. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  3271. }
  3272. });
  3273. this.scanDirectory(newPath)
  3274. refreshedItem = new VideoItem(newName, newName, newPath, CommonConstants.TYPE_IS_DIR, 0, '')
  3275. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  3276. if (Utility.isIsoByExtension(oldPath) || Utility.isIsoByExtension(newPath)) {
  3277. refreshedItem = this.buildLocalIsoItem(newPath, newName)
  3278. } else {
  3279. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  3280. if (success) {
  3281. console.log(" onecold 重命名成功,数据库已同步");
  3282. } else {
  3283. console.error(" onecold 重命名数据库失败原因: " + error);
  3284. }
  3285. });
  3286. refreshedItem =
  3287. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3288. }
  3289. } else {
  3290. return
  3291. }
  3292. this.videoLocalList[index] = refreshedItem;
  3293. }
  3294. this.cache.delete(this.currentPath)
  3295. this.cache.delete(oldPath)
  3296. this.cache.delete(newPath)
  3297. this.getSortedFiles(this.currentPath, true)
  3298. }).catch((error: BusinessError) => {
  3299. console.error(error.message);
  3300. });
  3301. }
  3302. build() {
  3303. Stack() {
  3304. this.ContentBuild()
  3305. Stack() {
  3306. Column()
  3307. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  3308. height: '95%',
  3309. dragBar: true,
  3310. showClose: true,
  3311. blurStyle: BlurStyle.Thin,
  3312. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3313. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  3314. title: {
  3315. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  3316. + `(${this.getPlayListDisplayCount()}首)`
  3317. }
  3318. })
  3319. }
  3320. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  3321. modalTransition:ModalTransition.DEFAULT,
  3322. onWillDisappear: () => {
  3323. this.setShowPlayFalse()
  3324. },
  3325. })
  3326. }
  3327. .alignContent(Alignment.Bottom)
  3328. .width('100%')
  3329. .height('100%')
  3330. }
  3331. @Builder
  3332. ContentBuild() {
  3333. Scroll() {
  3334. Column() {
  3335. Stack() {
  3336. //libraryname加上去后onKeyEvent监听不了,因为目前的解决方案是上面的XComponent,去掉libraryname
  3337. XComponent({ id: 'for_onKeyEvent',type: XComponentType.SURFACE,
  3338. controller: this.xcomponentController })
  3339. .onLoad(async (event?: object) => {
  3340. })
  3341. .focusable(true)
  3342. .height(0)
  3343. .focusOnTouch(true)
  3344. .defaultFocus(true) // 自动获取键盘焦点
  3345. .onKeyEvent((event?: KeyEvent) => {
  3346. console.info('onecold点击 onKeyEvent')
  3347. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  3348. if (!event || event.type !== KeyType.Down) {
  3349. return;
  3350. }
  3351. console.info('onecold点击 onKeyEvent event.keyCode: ' + event.keyCode)
  3352. //空格键 Space key controls pause/play
  3353. if (event.keyCode === KeyCode.KEYCODE_SPACE|| event.keyCode === KeyCode.KEYCODE_MEDIA_PLAY_PAUSE) {
  3354. this.playOrPause()
  3355. }
  3356. if (event.keyCode === KeyCode.KEYCODE_DPAD_UP) {
  3357. this.playPrevious()
  3358. }
  3359. if (event.keyCode === KeyCode.KEYCODE_DPAD_DOWN) {
  3360. this.playNext()
  3361. }
  3362. // Right-click to fast forward
  3363. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  3364. this.fastForward()
  3365. }
  3366. // Left-click to rewind
  3367. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  3368. this.backForward()
  3369. }
  3370. })
  3371. Column() {
  3372. XComponent({
  3373. id: 'xcomponentId',
  3374. type: 'surface',
  3375. libraryname: 'ijkplayer_napi',
  3376. controller: this.xcomponentController
  3377. })
  3378. .onLoad((event?: object) => {
  3379. if (!!event) {
  3380. this.initDelayPlay(event);
  3381. }
  3382. })
  3383. .onDestroy(() => {
  3384. })
  3385. .width('100%')// .width(this.videoWidth)
  3386. .aspectRatio(this.videoAspectRatio)
  3387. }
  3388. .aspectRatio(this.videoAspectRatio)
  3389. .justifyContent(FlexAlign.Center)
  3390. .backgroundColor(Color.Transparent)
  3391. .visibility(Visibility.Hidden)
  3392. .height(CommonConstants.FULL_PERCENT)
  3393. .width(CommonConstants.FULL_PERCENT)
  3394. .bindSheet($$this.isABSheet, this.ABLoopSheet(), {
  3395. height:this.isLandscape?'80%': '43%',
  3396. dragBar: true,
  3397. showClose: true,
  3398. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3399. blurStyle:BlurStyle.Thin,
  3400. backgroundColor:Color.Transparent,
  3401. title: { title: 'AB循环' }
  3402. })
  3403. Stack() {
  3404. Column() {
  3405. if(this.twoFingerType==4){
  3406. this.getWaterView()
  3407. }else{
  3408. if(this.isGridMusic){
  3409. this.getGridView()
  3410. }else {
  3411. this.getListView()
  3412. }
  3413. }
  3414. if (this.modeType ==0||this.modeType==4) {
  3415. Column() {
  3416. emptyView(this.themeColor)
  3417. }
  3418. .padding({ right:6 })
  3419. .onClick(()=>{
  3420. this.asyncCurrentPathOnlyFile()
  3421. })
  3422. .alignItems(HorizontalAlign.Center)
  3423. .position({ top: 200 })
  3424. .justifyContent(FlexAlign.Center)
  3425. .opacity(this.isZero ? 1 : 0)
  3426. .visibility(this.isZero&&!this.isLoadingPage && !this.isFavMusic && !this.isHistory
  3427. ? Visibility.Visible : Visibility.None)
  3428. .animation({
  3429. duration: 500,
  3430. curve: Curve.Friction // 可选动画曲线
  3431. })
  3432. .width('100%')
  3433. }
  3434. }
  3435. .layoutWeight(1)
  3436. .height('100%')
  3437. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  3438. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3439. .onDrop((event?: DragEvent) => {
  3440. try {
  3441. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3442. if (dragData !== undefined) {
  3443. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3444. if (records.length > 0) {
  3445. for (let i = 0; i < records.length; i++) {
  3446. let types = records[i].getTypes();
  3447. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3448. const fileUriUds =
  3449. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3450. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3451. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3452. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3453. this.targetFile = fileUriUds.oriUri;
  3454. this.saveVideoDatas([this.targetFile])
  3455. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3456. }
  3457. }
  3458. }
  3459. } else {
  3460. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3461. }
  3462. } else {
  3463. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3464. }
  3465. } catch (error) {
  3466. const err = error as BusinessError;
  3467. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3468. }
  3469. })
  3470. // 右侧居中的字母表索引
  3471. this.indexBuilder()
  3472. this.topTitleBar()
  3473. }
  3474. .alignContent(Alignment.Top)
  3475. .layoutWeight(1)
  3476. .height('100%')
  3477. Row() {
  3478. Button(this.isAllSelected ? '反选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  3479. .width(45)
  3480. .height(45)
  3481. .fontSize(10)
  3482. .margin({ top: 10, bottom: 10, right: 6 })
  3483. .backgroundColor(this.themeColor)
  3484. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3485. .onClick(() => {
  3486. if (this.isAllSelected) {
  3487. // 全不选
  3488. this.selectedFiles = [];
  3489. } else {
  3490. // 全选
  3491. this.selectedFiles = [...this.getCurFileList()];
  3492. }
  3493. this.syncLocalSelectionState();
  3494. })
  3495. Button('内嵌标签', { type: ButtonType.Capsule, stateEffect: true })
  3496. .width(72)
  3497. .height(45)
  3498. .fontSize(10)
  3499. .margin({ top: 10, bottom: 10, right: 6 })
  3500. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3501. .backgroundColor(this.themeColor)
  3502. .enabled(!this.hasSelectedDirectories() && this.getSelectedPlayableFiles().length > 0)
  3503. .bindContentCover($$this.isOneKeyTags, this.TagsContentCoverBuilder(), {
  3504. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3505. })
  3506. .onClick(() => {
  3507. if (this.hasSelectedDirectories()) {
  3508. ToastUtil.showToast('文件夹不支持批量内嵌标签')
  3509. return
  3510. }
  3511. this.isOneKeyTags = !this.isOneKeyTags
  3512. })
  3513. Button('合并', { type: ButtonType.Circle, stateEffect: true })
  3514. .width(45)
  3515. .height(45)
  3516. .fontSize(10)
  3517. .margin({ top: 10, bottom: 10, right: 6 })
  3518. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3519. .backgroundColor(this.themeColor)
  3520. .enabled(!this.hasSelectedDirectories() && this.getSelectedPlayableFiles().length > 0)
  3521. .bindContentCover($$this.isMergeAudio, this.MergeAudioBuilder(), {
  3522. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3523. })
  3524. .onClick(() => {
  3525. const selectedMediaFiles = this.getSelectedPlayableFiles()
  3526. if (this.hasSelectedDirectories()) {
  3527. ToastUtil.showToast('文件夹不支持合并')
  3528. return
  3529. }
  3530. if(ArrayUtil.isNotEmpty(selectedMediaFiles)&&Utility.isMerge(selectedMediaFiles,this.packName)){
  3531. this.isMergeAudio = !this.isMergeAudio
  3532. }else{
  3533. ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限合并')
  3534. }
  3535. })
  3536. Button('+歌单', { type: ButtonType.Circle, stateEffect: true })
  3537. .width(45)
  3538. .height(45)
  3539. .fontSize(10)
  3540. .margin({ top: 10, bottom: 10, right: 6 })
  3541. .backgroundColor(this.themeColor)
  3542. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3543. .enabled(!this.hasSelectedDirectories() && this.getSelectedPlayableFiles().length > 0)
  3544. .onClick(async () => {
  3545. this.longItemFilePath = ''
  3546. const selectedMediaFiles = this.getSelectedPlayableFiles()
  3547. if (ArrayUtil.isEmpty(selectedMediaFiles)) {
  3548. ToastUtil.showToast('请先选择音频文件')
  3549. return
  3550. }
  3551. await this.openAddToPlaylistDialog(selectedMediaFiles)
  3552. })
  3553. // Button('乱码', { type: ButtonType.Circle, stateEffect: true })
  3554. // .width(45)
  3555. // .height(45)
  3556. // .fontSize(10)
  3557. // .margin({ top: 10, bottom: 10, right: 6 })
  3558. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3559. // .backgroundColor(this.themeColor)
  3560. // .bindContentCover($$this.isFixMessy, this.FixMessyViewBuilder(), {
  3561. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3562. // })
  3563. // .onClick(() => {
  3564. // this.isFixMessy = !this.isFixMessy
  3565. // })
  3566. // Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  3567. // .width('35%')
  3568. // .height(60)
  3569. // .id('music_cut')
  3570. // .margin({ top: 10, bottom: 10, right: 6 })
  3571. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3572. // .backgroundColor(this.themeColor)
  3573. // .onClick(() => {
  3574. // this.showCutDialogForMultipleFiles(false, 'music_cut')
  3575. // })
  3576. //
  3577. // Button('移动', { type: ButtonType.Circle, stateEffect: true })
  3578. // .width('35%')
  3579. // .height(60)
  3580. // .id('music_cut_current')
  3581. // .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  3582. // .margin({ top: 10, bottom: 10, right: 6 })
  3583. // .backgroundColor(this.themeColor)
  3584. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3585. // .onClick(() => {
  3586. //
  3587. // this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  3588. // })
  3589. // Button('复制', { type: ButtonType.Circle, stateEffect: true })
  3590. // .width('35%')
  3591. // .height(60)
  3592. // .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  3593. // .margin({ top: 10, bottom: 10, right: 6 })
  3594. // .backgroundColor(this.themeColor)
  3595. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3596. // .onClick(() => {
  3597. // this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  3598. // })
  3599. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  3600. .width(45)
  3601. .height(45)
  3602. .fontSize(10)
  3603. .margin({ top: 10, bottom: 10, right: 6 })
  3604. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  3605. .backgroundColor(this.themeColor)
  3606. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3607. .onClick(() => {
  3608. this.showWarnIsDelete()
  3609. })
  3610. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  3611. .width(45)
  3612. .height(45)
  3613. .fontSize(10)
  3614. .margin({ top: 10, bottom: 10, right: 6 })
  3615. .backgroundColor(this.themeColor)
  3616. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3617. .onClick(() => {
  3618. this.selectedFiles = [];
  3619. this.isAllSelected = false
  3620. this.isMultiSelect = false
  3621. })
  3622. }
  3623. .width('100%')
  3624. .justifyContent(FlexAlign.Center)
  3625. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  3626. .opacity(this.isMultiSelect ? 1 : 0)
  3627. .animation({
  3628. duration: 666,
  3629. curve: 'ease-in-out' // 可选动画曲线
  3630. })
  3631. .position({ bottom: 20 }) // 将 Row 固定在底部
  3632. }
  3633. .width('100%')
  3634. .height('100%')
  3635. .alignContent(Alignment.Top)
  3636. }
  3637. .width('100%')
  3638. .height('100%')
  3639. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  3640. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  3641. .backgroundImagePosition(Alignment.Center)
  3642. .backdropBlur(this.blurValue)
  3643. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  3644. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  3645. }
  3646. }
  3647. //字母表索引
  3648. @Builder
  3649. indexBuilder(){
  3650. Column({space: 5}){
  3651. if(this.showZMIndex&&this.enableShowAlphabet){
  3652. if(this.isShowAlphaBet&&!(this.modeType==2&&!this.isCanBack)
  3653. &&!(this.modeType==3&&!this.isCanBack)&&(this.sortType==4||this.sortType==5)){
  3654. AlphabetIndexer({arrayValue: this.alphaBet,selected: this.selectAlphaBetIndex})
  3655. .attributeModifier(this.alphaBetStyle)
  3656. .usingPopup(this.isTouchingAlphaBet)
  3657. .onAreaChange((old_value,new_value)=>{
  3658. this.alphabetHeight = new_value.height as number
  3659. })
  3660. .popupPosition({
  3661. x: 40,
  3662. y: this.alphabetHeight / 2
  3663. })
  3664. .onSelect((index: number) => {
  3665. void this.onSelectIndexItem(this.alphaBet[index])
  3666. })
  3667. .onTouch((event: TouchEvent) =>{
  3668. this.showAlphabetIndex()
  3669. if(event.type === TouchType.Up || event.type === TouchType.Cancel){
  3670. this.isTouchingAlphaBet = false
  3671. this.hideAlphabetIndexAfterDelay(1500)
  3672. }else{
  3673. this.isTouchingAlphaBet = true
  3674. }
  3675. })
  3676. .transition(
  3677. TransitionEffect.translate({x: 10})
  3678. .combine(TransitionEffect.opacity(0.1))
  3679. .animation({
  3680. duration: 150,
  3681. curve: Curve.EaseInOut,
  3682. })
  3683. )
  3684. }
  3685. }
  3686. if(this.showFindLocation){
  3687. if(!(this.showZMIndex&&this.enableShowAlphabet)){
  3688. Blank()
  3689. .layoutWeight(1)
  3690. }
  3691. PointLightDefaultButton({
  3692. isSysBol:true,
  3693. pointColor:Color.Gray,
  3694. imageResource:$r('sys.symbol.local_fill'),
  3695. isPx: false,
  3696. builderHeight: 30,
  3697. builderWidth: 30,
  3698. })
  3699. .onClick(() =>{
  3700. void this.locateCurrentSong();
  3701. })
  3702. .clickEffect({level:ClickEffectLevel.LIGHT,scale: 0.5})
  3703. .margin({
  3704. bottom: this.bottomSafeHeight+100,right:10
  3705. })
  3706. }
  3707. }
  3708. .padding({
  3709. bottom: 0
  3710. })
  3711. .margin({right:5})
  3712. .position({x:'92%'})
  3713. .height('100%')
  3714. .justifyContent(FlexAlign.Center)
  3715. .bindSheet($$this.isEqualizerSheet, this.EqualizerSheet(), {
  3716. height: '100%',
  3717. dragBar: true,
  3718. showClose: true,
  3719. preferType: SheetType.CENTER ,
  3720. blurStyle: BlurStyle.Thin,
  3721. title: { title: '均衡器' },
  3722. onDisappear: () => {
  3723. this.isEqualizerSheet = false
  3724. }
  3725. })
  3726. }
  3727. async onSelectIndexItem(letter: string) {
  3728. await this.ensureFullListForAlphabetIndex();
  3729. const findTargetIndex = (): number => {
  3730. const songs = this.videoLocalList;
  3731. for (let i = 0; i < songs.length; i++) {
  3732. const song = songs[i];
  3733. let text = this.isShowFileName ? song.fileName :
  3734. (song.type != CommonConstants.TYPE_IS_DIR && song.pyStr) ? song.pyStr : song.name;
  3735. if (this.sortType === 0 || this.sortType == 1) {
  3736. text = song.artist;
  3737. } else if (this.sortType === 2 || this.sortType == 3) {
  3738. text = song.album;
  3739. }
  3740. if (text) {
  3741. const firstPinyin = getFirstLetter(text);
  3742. if (firstPinyin && firstPinyin === letter) {
  3743. return i;
  3744. }
  3745. }
  3746. }
  3747. return -1;
  3748. };
  3749. const targetIndex = findTargetIndex();
  3750. if (targetIndex !== -1) {
  3751. if (this.isGridMusic || this.twoFingerType == 4) {
  3752. this.scroller.scrollToIndex(targetIndex, false);
  3753. } else {
  3754. this.listScroller.scrollToIndex(targetIndex);
  3755. }
  3756. }
  3757. }
  3758. private showAlphabetIndex(): void {
  3759. this.isShowAlphaBet = true;
  3760. if (this.alphaBetHideTimer) {
  3761. clearTimeout(this.alphaBetHideTimer);
  3762. this.alphaBetHideTimer = 0;
  3763. }
  3764. }
  3765. private hideAlphabetIndexAfterDelay(delayMs: number): void {
  3766. if (this.alphaBetHideTimer) {
  3767. clearTimeout(this.alphaBetHideTimer);
  3768. }
  3769. this.alphaBetHideTimer = setTimeout(() => {
  3770. if (!this.isTouchingAlphaBet) {
  3771. this.isShowAlphaBet = false;
  3772. }
  3773. this.alphaBetHideTimer = 0;
  3774. }, delayMs) as number;
  3775. }
  3776. private scheduleAlphaBetRebuild(delayMs: number = 120): void {
  3777. if (!this.showZMIndex) {
  3778. return;
  3779. }
  3780. if (this.alphaBetRebuildTimer) {
  3781. clearTimeout(this.alphaBetRebuildTimer);
  3782. }
  3783. this.alphaBetRebuildTimer = setTimeout(() => {
  3784. this.alphaBetRebuildTimer = 0;
  3785. if (this.isScrolling) {
  3786. this.alphaBetDirty = true;
  3787. return;
  3788. }
  3789. this.alphaBetDirty = false;
  3790. void this.setAlphaBet();
  3791. }, delayMs) as number;
  3792. }
  3793. private markAlphaBetDirty(): void {
  3794. if (!this.showZMIndex) {
  3795. return;
  3796. }
  3797. if (this.isMediaLibraryWarmupWindow()) {
  3798. this.alphaBetDirty = true;
  3799. this.scheduleAlphaBetRebuild(900);
  3800. return;
  3801. }
  3802. this.alphaBetDirty = true;
  3803. if (!this.isScrolling) {
  3804. this.scheduleAlphaBetRebuild(80);
  3805. }
  3806. }
  3807. private async ensureFullListForAlphabetIndex(): Promise<void> {
  3808. if (this.isLoadingPage) {
  3809. return;
  3810. }
  3811. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  3812. return;
  3813. }
  3814. if (this.totalCount === 0 || this.videoLocalList.length >= this.totalCount) {
  3815. return;
  3816. }
  3817. if (this.modeType !== 0 && this.modeType !== 1) {
  3818. return;
  3819. }
  3820. this.isLoadingPage = true;
  3821. try {
  3822. const options: PageQueryOptions = {
  3823. pageIndex: 0,
  3824. pageSize: this.totalCount,
  3825. sortType: this.sortType,
  3826. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  3827. isShowFileName: this.isShowFileName
  3828. };
  3829. if (this.modeType === 0) {
  3830. options.parentPath = this.currentPath;
  3831. }
  3832. let result: PageQueryResult;
  3833. if (this.modeType === 0) {
  3834. result = await this.table.queryByParentPathPaged(options);
  3835. const dbItems = this.filterOutLocalIsoItems(result.items);
  3836. if (!this.isSearchMode) {
  3837. const directories: VideoItem[] = await this.loadDirectories(this.currentPath);
  3838. const isoItems: VideoItem[] = this.getLocalIsoItems(this.currentPath);
  3839. result.items = [...directories, ...isoItems, ...dbItems];
  3840. } else {
  3841. result.items = dbItems;
  3842. }
  3843. } else {
  3844. result = await this.table.queryMediaLibraryPaged(options);
  3845. }
  3846. this.videoLocalList = result.items;
  3847. this.dataSource.pushArrayData(this.videoLocalList);
  3848. this.pageCache.clear();
  3849. this.pageHasMoreCache.clear();
  3850. this.pageTotalCountCache.clear();
  3851. this.prefetchingPages.clear();
  3852. this.currentPage = 0;
  3853. this.totalCount = this.modeType === 0 ? result.items.length : result.totalCount;
  3854. this.hasMoreData = false;
  3855. this.lastScrollTriggerPage = -1;
  3856. this.lastVisibleEndIndex = -1;
  3857. this.isPagingTransition = false;
  3858. if (this.pagingScheduleTimer) {
  3859. clearTimeout(this.pagingScheduleTimer);
  3860. this.pagingScheduleTimer = 0;
  3861. }
  3862. if (this.modeType === 1) {
  3863. this.mediaKuCount = result.totalCount;
  3864. }
  3865. this.setButtonStatus();
  3866. this.markAlphaBetDirty();
  3867. } catch (err) {
  3868. const error = err as Error;
  3869. Logger.warn('heanup LocalMusic', `ensureFullListForAlphabetIndex error: ${error.message}`);
  3870. } finally {
  3871. this.isLoadingPage = false;
  3872. }
  3873. }
  3874. // 找到对应字母表的索引
  3875. findAlphaBetIndex(song: VideoItem):number{
  3876. let text = this.isShowFileName?song.fileName:
  3877. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  3878. if(this.sortType === 0||this.sortType==1){
  3879. text = song.artist
  3880. }else if(this.sortType === 2||this.sortType==3){
  3881. text = song.album
  3882. }
  3883. if(text){
  3884. let firstLetter = getFirstLetter(text)
  3885. for(let i=0;i<this.alphaBet.length;i++){
  3886. if(this.alphaBet[i] === firstLetter){
  3887. return i
  3888. }
  3889. }
  3890. }
  3891. return 0
  3892. }
  3893. private buildAlphaTaskItems(songs: Array<VideoItem>): Array<AlphaTaskItem> {
  3894. const items: Array<AlphaTaskItem> = []
  3895. for (const song of songs) {
  3896. items.push({
  3897. type: song.type,
  3898. name: song.name,
  3899. pyStr: song.pyStr,
  3900. fileName: song.fileName,
  3901. artist: song.artist,
  3902. album: song.album
  3903. })
  3904. }
  3905. return items
  3906. }
  3907. private async buildAlphaBetByTask(songs: Array<VideoItem>, version: number): Promise<void> {
  3908. const taskItems = this.buildAlphaTaskItems(songs)
  3909. const task = new taskpool.Task(buildAlphabetIndexTask, taskItems, this.sortType, this.isShowFileName)
  3910. const result = await taskpool.execute(task, taskpool.Priority.MEDIUM) as Array<string>
  3911. if (version !== this.alphaBetBuildVersion) {
  3912. return
  3913. }
  3914. this.alphaBet = result
  3915. if (this.videoLocalList.length > 0) {
  3916. this.selectAlphaBetIndex = 0
  3917. }
  3918. }
  3919. async setAlphaBet(){
  3920. if(!this.showZMIndex){
  3921. return
  3922. }
  3923. if (this.modeType === 1 && this.totalCount > this.videoLocalList.length) {
  3924. await this.refreshAlphaBetFromMediaLibrary()
  3925. return
  3926. }
  3927. try {
  3928. const songs = this.videoLocalList
  3929. if (songs.length > 40000) {
  3930. this.alphaBet = []
  3931. return
  3932. }
  3933. const version = ++this.alphaBetBuildVersion
  3934. await this.buildAlphaBetByTask(songs, version)
  3935. } catch (e) {
  3936. console.error('testTag','排序字母表出错',JSON.stringify(e))
  3937. }
  3938. }
  3939. private async refreshAlphaBetFromMediaLibrary(): Promise<void> {
  3940. if (this.totalCount <= 0) {
  3941. return
  3942. }
  3943. if (this.totalCount > 40000) {
  3944. this.alphaBet = []
  3945. return
  3946. }
  3947. const keyword = this.isSearchMode ? this.searchText : ''
  3948. const cacheKey = `${this.modeType}-${this.sortType}-${this.isShowFileName}-${keyword}-${this.totalCount}`
  3949. if (this.alphaBetCacheKey === cacheKey && this.alphaBet.length > 0) {
  3950. return
  3951. }
  3952. const result = await this.table.queryMediaLibraryPaged({
  3953. pageIndex: 0,
  3954. pageSize: this.totalCount,
  3955. sortType: this.sortType,
  3956. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  3957. isShowFileName: this.isShowFileName
  3958. })
  3959. const version = ++this.alphaBetBuildVersion
  3960. await this.buildAlphaBetByTask(result.items, version)
  3961. this.alphaBetCacheKey = cacheKey
  3962. }
  3963. @Builder
  3964. topTitleBar(){
  3965. Column() {
  3966. Row({ space: 15 }) {
  3967. if (!this.isSearchMode ) {
  3968. //左侧滑动按钮
  3969. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3970. SymbolGlyph(this.rightTopImage)
  3971. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3972. }
  3973. .attributeModifier(new ButtonFancyModifier(40, 40))
  3974. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3975. .animation({ duration: 300, curve: Curve.Ease })
  3976. .onClick(() => {
  3977. this.triggerSwipeBackWithAnimation()
  3978. })
  3979. .attributeModifier(new ShadowModifier())
  3980. .zIndex(0)
  3981. }else{
  3982. //左侧搜索返回按钮
  3983. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3984. SymbolGlyph($r('sys.symbol.chevron_left'))
  3985. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3986. }
  3987. .attributeModifier(new ButtonFancyModifier(40, 40))
  3988. .margin({bottom:5})
  3989. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3990. .animation({ duration: 300, curve: Curve.Ease })
  3991. .onClick(() => {
  3992. this.isSearchMode = false
  3993. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  3994. this.searchText = ''
  3995. this.getSortedFiles(this.currentPath)
  3996. return
  3997. }
  3998. this.onSearchInput('')
  3999. })
  4000. .attributeModifier(new ShadowModifier())
  4001. .zIndex(0)
  4002. }
  4003. if (!this.isSearchMode) {
  4004. Text(this.modeType==1?`${this.titleName}(${this.mediaKuCount}首)`:this.titleName)
  4005. .margin({left:3,right:10})
  4006. .fontColor($r('app.color.text_color'))
  4007. .fontSize(this.twoFingerType==3?17:16)
  4008. .maxLines(1)
  4009. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  4010. .layoutWeight(1)
  4011. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  4012. }
  4013. //搜索框
  4014. Search({ controller: this.searchController,value: this.searchText, placeholder: '搜索标题、艺术家...' })
  4015. .searchButton('搜索',{fontColor:this.themeColor})
  4016. .searchIcon({
  4017. src: $r('sys.media.ohos_ic_public_search_filled')
  4018. })
  4019. .cancelButton({
  4020. style: CancelButtonStyle.CONSTANT,
  4021. icon: {
  4022. src: $r('sys.media.ohos_ic_public_cancel_filled')
  4023. }
  4024. })
  4025. .layoutWeight(1)
  4026. .height(40)
  4027. .maxLength(20)
  4028. .backgroundColor(this.isDarkMode?Color.Black:'#F5F5F5')
  4029. .placeholderColor(Color.Grey)
  4030. .placeholderFont({ size: 14, weight: 400 })
  4031. .textFont({ size: 14, weight: 400 })
  4032. .onSubmit((value: string) => {
  4033. console.log('onecold onSubmit ='+value)
  4034. this.searchController.stopEditing()
  4035. if(this.modeType==0){
  4036. this.modeType =1//如果是首页 切换到媒体库搜索
  4037. }
  4038. this.commitSearchHistory(value)
  4039. this.onSearchInput(this.searchText);
  4040. })
  4041. .onChange((value: string) => {
  4042. console.log('onecold onChange ='+value)
  4043. if(this.modeType==0){
  4044. this.modeType =1//如果是首页 切换到媒体库搜索
  4045. }
  4046. this.onSearchInput(value);
  4047. })
  4048. .visibility(this.isSearchMode?Visibility.Visible:Visibility.None)
  4049. .animation({ duration: 300, curve: Curve.Ease })
  4050. //搜索按钮
  4051. if (!this.isSearchMode) {
  4052. Button({ type: ButtonType.Circle, stateEffect: true }) {
  4053. SymbolGlyph($r('sys.symbol.magnifyingglass'))
  4054. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  4055. }
  4056. .attributeModifier(new ButtonFancyModifier(40, 40))
  4057. .animation({ duration: 300, curve: Curve.Ease })
  4058. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  4059. .attributeModifier(new ShadowModifier())
  4060. .zIndex(0)
  4061. .onClick(()=>{
  4062. this.isSearchMode = true
  4063. this.loadSearchHistory()
  4064. })
  4065. //排序按钮
  4066. Button({ type: ButtonType.Circle, stateEffect: true }) {
  4067. SymbolGlyph($r('sys.symbol.list_number'))
  4068. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  4069. }
  4070. .attributeModifier(new ButtonFancyModifier(40, 40))
  4071. .animation({ duration: 300, curve: Curve.Ease })
  4072. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  4073. .bindMenu((this.modeType==2&&!this.isCanBack)||(this.modeType==3&&!this.isCanBack)
  4074. ?this.SortMenuForArtistAblumBuilder:this.SortMenuBuilder)
  4075. .attributeModifier(new ShadowModifier())
  4076. .zIndex(0)
  4077. //添加按钮
  4078. Button({ type: ButtonType.Circle, stateEffect: true }) {
  4079. SymbolGlyph($r('sys.symbol.plus'))
  4080. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  4081. }
  4082. .attributeModifier(new ButtonFancyModifier(40, 40))
  4083. .animation({ duration: 300, curve: Curve.Ease })
  4084. .visibility(this.modeType==0||this.modeType==1?Visibility.Visible:Visibility.None)
  4085. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  4086. .bindSheet($$this.showAddSheet, this.addSheet(), {
  4087. height: SheetSize.FIT_CONTENT,
  4088. dragBar: true,
  4089. showClose: true,
  4090. preferType: SheetType.CENTER ,
  4091. title: {
  4092. title: '导入音乐'
  4093. }
  4094. })
  4095. .onClick(() => {
  4096. this.showAddSheet = !this.showAddSheet;
  4097. })
  4098. .attributeModifier(new ShadowModifier())
  4099. .zIndex(0)
  4100. }
  4101. }
  4102. }
  4103. .padding({ top: this.topSafeHeight+10, left: 10, right: 10 })
  4104. .width('100%')
  4105. .translate({
  4106. x: 0,
  4107. y: (this.isShowTitleBar || !this.autoHideTitle) ? 0 : -80
  4108. })
  4109. .opacity((this.isShowTitleBar || !this.autoHideTitle) ? 1 : 0)
  4110. .animation({
  4111. duration: 240,
  4112. curve: Curve.EaseInOut
  4113. })
  4114. }
  4115. @Builder
  4116. addSheet() {
  4117. Scroll() {
  4118. Column() {
  4119. Column() {
  4120. Row() {
  4121. SymbolGlyph($r('sys.symbol.info_circle'))
  4122. .fontSize(22)
  4123. .fontColor([this.themeColor])
  4124. .alignSelf(ItemAlign.Center)
  4125. .margin({ left: 8 })
  4126. Text('导入音乐复制到DownLoad目录')
  4127. .margin({ left: 8 })
  4128. .fontSize(14)
  4129. .fontColor($r('app.color.text_color'))
  4130. .fontWeight(480)
  4131. .layoutWeight(1)
  4132. Toggle({ type: ToggleType.Switch, isOn: this.isCopyFileToDownLoad })
  4133. .selectedColor(this.themeColor)
  4134. .switchPointColor(Color.White)
  4135. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  4136. .margin({ right: 2 })
  4137. .onChange((checked: boolean) => {
  4138. this.isCopyFileToDownLoad = checked;
  4139. PreferencesUtil.put(SettingPage.IS_COPYFILE_TO_DOWNLOAD, this.isCopyFileToDownLoad)
  4140. })
  4141. .width(50)
  4142. .height(30);
  4143. }
  4144. .height(72)
  4145. .padding({ left:8,right:8 })
  4146. }
  4147. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  4148. .backgroundColor($r('app.color.start_window_background'))
  4149. .borderRadius(15)
  4150. .width('85%')
  4151. .margin({
  4152. top: 10,
  4153. bottom: 10
  4154. })
  4155. .padding(0)
  4156. .border({
  4157. color: Color.White,
  4158. width: 1.8
  4159. })
  4160. Menu() {
  4161. MenuItem({
  4162. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder_badge_plus')),
  4163. content: "新建文件夹"
  4164. })
  4165. .backgroundColor($r('app.color.silvery'))
  4166. .border({
  4167. width: { bottom: 1 },
  4168. color: '#12ec5c87'
  4169. })
  4170. .margin(10)
  4171. .height(60)
  4172. .padding({left:15,right:15})
  4173. .onClick(async () => {
  4174. this.showMkDialog()
  4175. this.showAddSheet = !this.showAddSheet
  4176. })
  4177. MenuItem({
  4178. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder')),
  4179. content: $r('app.string.import_from_files')
  4180. })
  4181. .padding({left:15,right:15})
  4182. .backgroundColor($r('app.color.silvery'))
  4183. .border({
  4184. width: { bottom: 1 },
  4185. color: '#12ec5c87'
  4186. })
  4187. .margin(10)
  4188. .height(60)
  4189. .onClick(async () => {
  4190. this.callFilePickerSelectFile()
  4191. this.showAddSheet = !this.showAddSheet
  4192. })
  4193. MenuItem({
  4194. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square')),
  4195. content: '全选导入'
  4196. // content: '从下载文件夹导入(路径:Download/' +
  4197. // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
  4198. })
  4199. .padding({left:15,right:15})
  4200. .backgroundColor($r('app.color.silvery'))
  4201. .border({
  4202. width: { bottom: 1 },
  4203. color: '#12ec5c87'
  4204. })
  4205. .margin(10)
  4206. .height(60)
  4207. .onClick(async () => {
  4208. this.goSelectMusic()
  4209. this.showAddSheet = !this.showAddSheet
  4210. })
  4211. MenuItem({
  4212. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.save')),
  4213. content: '自动导入教程'
  4214. })
  4215. .padding({left:15,right:15})
  4216. .backgroundColor($r('app.color.silvery'))
  4217. .border({
  4218. width: { bottom: 1 },
  4219. color: '#12ec5c87'
  4220. })
  4221. .margin(10)
  4222. .height(60)
  4223. .onClick(async () => {
  4224. this.showTips()
  4225. this.showAddSheet = !this.showAddSheet
  4226. })
  4227. MenuItem({
  4228. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.questionmark_circle')),
  4229. content: '导入疑问'
  4230. })
  4231. .height(60)
  4232. .padding({left:15,right:15})
  4233. .backgroundColor($r('app.color.silvery'))
  4234. .border({
  4235. width: { bottom: 1 },
  4236. color: '#12ec5c87'
  4237. })
  4238. .margin(10)
  4239. .onClick(async () => {
  4240. this.showProblomTips()
  4241. this.showAddSheet = !this.showAddSheet
  4242. })
  4243. }.attributeModifier(new MenuModifier())
  4244. .margin({bottom:30})
  4245. .width('90%')
  4246. .borderRadius(15)
  4247. }
  4248. .layoutWeight(1)
  4249. }
  4250. }
  4251. async showProblomTips() {
  4252. try {
  4253. this.getUIContext().getPromptAction().showDialog({
  4254. title: '导入疑问',
  4255. message:'为什么有些歌曲导入成功后,内嵌标签或者其他功能不能用?:\n\n1、由于鸿蒙系统的安全策略,文件权限不够,请将文件移动到Download/天天静听目录下。' +
  4256. '这样内嵌标签功能就没有权限问题。\n\n2、导入可以也选择不复制,这样可以省略空间。\n\n',
  4257. buttons: [
  4258. {
  4259. text: '知道了',
  4260. color: '#000000'
  4261. },
  4262. ]
  4263. }, (err, data) => {
  4264. if (err) {
  4265. console.error('showDialog err: ' + err);
  4266. return;
  4267. }
  4268. console.info('showDialog success callback, click button: ' + data.index);
  4269. });
  4270. } catch (error) {
  4271. let message = (error as BusinessError).message;
  4272. let code = (error as BusinessError).code;
  4273. console.error(`showDialog args error code is ${code}, message is ${message}`);
  4274. };
  4275. }
  4276. @Builder
  4277. TagsContentCoverBuilder() {
  4278. Scroll() {
  4279. Column() {
  4280. TagsContentCover(
  4281. {
  4282. selectedFiles:this.selectedFiles,
  4283. isOneKeyTags:this.isOneKeyTags,
  4284. onSeePath:(path:string)=>{
  4285. this.modeType = 0
  4286. this.deleteCache(path)
  4287. this.getSortedFiles(path)
  4288. },
  4289. onTagsResult:(result: boolean,deleteCache_path?:string)=>{
  4290. this.isMultiSelect = false
  4291. if(result){//如果嵌入成功,更新数据
  4292. this.listRefreshKey++
  4293. setTimeout(()=>{
  4294. this.doUpdateData()
  4295. },500)
  4296. }
  4297. console.info('onecold onTagsResult deleteCache_path =' +deleteCache_path)
  4298. if(deleteCache_path){
  4299. this.deleteCache(deleteCache_path)
  4300. }
  4301. }
  4302. }
  4303. )
  4304. }
  4305. }
  4306. .width('100%')
  4307. .height('100%')
  4308. }
  4309. @Builder
  4310. FixMessyViewBuilder() {
  4311. Scroll() {
  4312. Column() {
  4313. FixMessyView(
  4314. {
  4315. selectedFiles:this.selectedFiles,
  4316. isFixMessy:this.isFixMessy,
  4317. onFixResult:(result: boolean)=>{
  4318. this.isMultiSelect = false
  4319. if(result){//如果嵌入成功,更新数据
  4320. this.deleteCache(this.currentPath)
  4321. this.doUpdateData()
  4322. }
  4323. }
  4324. }
  4325. )
  4326. }
  4327. }
  4328. .width('100%')
  4329. .height('100%')
  4330. }
  4331. //剪辑音频
  4332. @Builder
  4333. EditAudioBuilder(item:VideoItem) {
  4334. Scroll() {
  4335. Column() {
  4336. EditAudio(
  4337. {
  4338. mVideoItem:item,
  4339. currentPath:this.currentPath,
  4340. videoUrl:this.videoUrl,
  4341. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4342. currentTime:this.currentTime,
  4343. progressValue:this.progressValue,
  4344. onBack:()=>{
  4345. this.isEditAudio = !this.isEditAudio
  4346. },
  4347. onSeeOutputPath:(outPutPath:string)=>{
  4348. this.isEditAudio = !this.isEditAudio
  4349. this.longItemFilePath = ''
  4350. this.modeType = 0
  4351. this.isShowFileName = true
  4352. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4353. },
  4354. onPlayOrPause:()=>{
  4355. if(this.videoUrl==item.filePath){
  4356. this.playOrPause()
  4357. }else{//如果不是当前播放的,则播放该文件
  4358. this.videoUrl==item.filePath
  4359. this.doPlay(item,0,false,true)
  4360. }
  4361. },
  4362. onSliderChange:(value:number)=>{
  4363. if(this.videoUrl!=item.filePath){
  4364. this.videoUrl==item.filePath
  4365. return
  4366. }
  4367. this.isSeekTo = true;
  4368. this.mDestroyPage = false;
  4369. this.showLoadIng();
  4370. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  4371. let seekValue = value * (this.getActiveDuration() / 100);
  4372. this.seekTo(seekValue + "");
  4373. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  4374. this.isSeekTo = false;
  4375. },
  4376. onResult:(result: boolean,outPath:string)=>{
  4377. if(result){//如果剪辑成功,更新数据
  4378. this.doUpdateData()
  4379. }else{
  4380. ToastUtil.showToast('剪辑失败')
  4381. }
  4382. }
  4383. }
  4384. )
  4385. }
  4386. }
  4387. .width('100%')
  4388. .height('100%')
  4389. }
  4390. //提取伴奏
  4391. @Builder
  4392. ConverterBuilder(item:VideoItem) {
  4393. Scroll() {
  4394. Column() {
  4395. AudioFormatConverter(
  4396. {
  4397. mVideoItem:item,
  4398. videoUrl:this.videoUrl,
  4399. currentPath:this.currentPath,
  4400. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4401. currentTime:this.currentTime,
  4402. progressValue:this.progressValue,
  4403. onBack:()=>{
  4404. this.isConverter = !this.isConverter
  4405. this.longItemFilePath = ''
  4406. },
  4407. onPlayOrPause:()=>{
  4408. if(this.videoUrl==item.filePath){
  4409. this.playOrPause()
  4410. }else{//如果不是当前播放的,则播放该文件
  4411. this.videoUrl==item.filePath
  4412. this.doPlay(item,0,false,true)
  4413. }
  4414. },
  4415. onSeeOutputPath:(outPutPath:string)=>{
  4416. this.isConverter = !this.isConverter
  4417. this.longItemFilePath = ''
  4418. this.modeType = 0
  4419. this.isShowFileName = true
  4420. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4421. },
  4422. onSliderChange:(value:number)=>{
  4423. if(this.videoUrl!=item.filePath){
  4424. this.videoUrl==item.filePath
  4425. return
  4426. }
  4427. this.isSeekTo = true;
  4428. this.mDestroyPage = false;
  4429. this.showLoadIng();
  4430. let seekValue = value * (this.getActiveDuration() / 100);
  4431. this.seekTo(seekValue + "");
  4432. this.isSeekTo = false;
  4433. },
  4434. onResult:(result: boolean,outPath:string)=>{
  4435. if(result){//如果成功,更新数据
  4436. this.doUpdateData()
  4437. }else{
  4438. ToastUtil.showToast('格式转化失败')
  4439. }
  4440. }
  4441. }
  4442. )
  4443. }
  4444. }
  4445. .width('100%')
  4446. .height('100%')
  4447. }
  4448. //提取伴奏
  4449. @Builder
  4450. ExtractAccBuilder(item:VideoItem) {
  4451. Scroll() {
  4452. Column() {
  4453. ExtractAccompaniment(
  4454. {
  4455. mVideoItem:item,
  4456. currentPath:this.currentPath,
  4457. videoUrl:this.videoUrl,
  4458. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4459. currentTime:this.currentTime,
  4460. progressValue:this.progressValue,
  4461. onBack:()=>{
  4462. this.isExtractAcc = !this.isExtractAcc
  4463. this.longItemFilePath = ''
  4464. },
  4465. onPlayOrPause:()=>{
  4466. if(this.videoUrl==item.filePath){
  4467. this.playOrPause()
  4468. }else{//如果不是当前播放的,则播放该文件
  4469. this.videoUrl==item.filePath
  4470. this.doPlay(item,0,false,true)
  4471. }
  4472. },
  4473. onSeeOutputPath:(outPutPath:string)=>{
  4474. this.isExtractAcc = !this.isExtractAcc
  4475. this.longItemFilePath = ''
  4476. this.modeType = 0
  4477. this.isShowFileName = true
  4478. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4479. },
  4480. onSliderChange:(value:number)=>{
  4481. if(this.videoUrl!=item.filePath){
  4482. this.videoUrl==item.filePath
  4483. return
  4484. }
  4485. this.isSeekTo = true;
  4486. this.mDestroyPage = false;
  4487. this.showLoadIng();
  4488. let seekValue = value * (this.getActiveDuration() / 100);
  4489. this.seekTo(seekValue + "");
  4490. this.isSeekTo = false;
  4491. },
  4492. onResult:(result: boolean,outPath:string)=>{
  4493. if(result){//如果成功,更新数据
  4494. this.doUpdateData()
  4495. }else{
  4496. ToastUtil.showToast('提取伴奏失败')
  4497. }
  4498. }
  4499. }
  4500. )
  4501. }
  4502. }
  4503. .width('100%')
  4504. .height('100%')
  4505. }
  4506. //AI人声分离
  4507. @Builder
  4508. AiBuilder(item:VideoItem) {
  4509. Scroll() {
  4510. Column() {
  4511. AIVoiceSeparation(
  4512. {
  4513. mVideoItem:item,
  4514. videoUrl:this.videoUrl,
  4515. currentPath:this.currentPath,
  4516. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4517. currentTime:this.currentTime,
  4518. progressValue:this.progressValue,
  4519. onBack:()=>{
  4520. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  4521. this.longItemFilePath = ''
  4522. },
  4523. onPlayOrPause:()=>{
  4524. if(this.videoUrl==item.filePath||this.isPlaying){
  4525. this.playOrPause()
  4526. }else{//如果不是当前播放的,则播放该文件
  4527. this.videoUrl==item.filePath
  4528. this.doPlay(item,0,false,true)
  4529. }
  4530. },
  4531. onPlayPath:(path:string)=>{
  4532. this.videoUrl==path
  4533. const itemP = Utility.getItemByFilePath(this.videoLocalList,path)
  4534. if(itemP)
  4535. this.doPlay(itemP,0,false,true)
  4536. },
  4537. onSeeOutputPath:(outPutPath:string)=>{
  4538. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  4539. this.longItemFilePath = ''
  4540. this.modeType = 0
  4541. this.isShowFileName = true
  4542. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4543. },
  4544. onSliderChange:(value:number)=>{
  4545. if(this.videoUrl!=item.filePath){
  4546. this.videoUrl==item.filePath
  4547. return
  4548. }
  4549. this.isSeekTo = true;
  4550. this.mDestroyPage = false;
  4551. this.showLoadIng();
  4552. let seekValue = value * (this.getActiveDuration() / 100);
  4553. this.seekTo(seekValue + "");
  4554. this.isSeekTo = false;
  4555. },
  4556. onResult:(result: boolean,outPath:string)=>{
  4557. if(result){//如果成功,更新数据
  4558. this.doUpdateData()
  4559. }else{
  4560. ToastUtil.showToast('Ai人声分离失败')
  4561. }
  4562. }
  4563. }
  4564. )
  4565. }
  4566. }
  4567. .width('100%')
  4568. .height('100%')
  4569. }
  4570. //变速变调
  4571. @Builder
  4572. ChangeToneBuilder(item:VideoItem) {
  4573. Scroll() {
  4574. Column() {
  4575. ChangeTone(
  4576. {
  4577. mVideoItem:item,
  4578. currentPath:this.currentPath,
  4579. videoUrl:this.videoUrl,
  4580. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4581. currentTime:this.currentTime,
  4582. progressValue:this.progressValue,
  4583. onBack:()=>{
  4584. this.isChangeTone = !this.isChangeTone
  4585. this.longItemFilePath = ''
  4586. },
  4587. onPlayOrPause:()=>{
  4588. if(this.videoUrl==item.filePath){
  4589. this.playOrPause()
  4590. }else{//如果不是当前播放的,则播放该文件
  4591. this.videoUrl==item.filePath
  4592. this.doPlay(item,0,false,true)
  4593. }
  4594. },
  4595. onSeeOutputPath:(outPutPath:string)=>{
  4596. this.isChangeTone = !this.isChangeTone
  4597. this.longItemFilePath = ''
  4598. this.modeType = 0
  4599. this.isShowFileName = true
  4600. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4601. },
  4602. onSliderChange:(value:number)=>{
  4603. if(this.videoUrl!=item.filePath){
  4604. this.videoUrl==item.filePath
  4605. return
  4606. }
  4607. this.isSeekTo = true;
  4608. this.mDestroyPage = false;
  4609. this.showLoadIng();
  4610. let seekValue = value * (this.getActiveDuration() / 100);
  4611. this.seekTo(seekValue + "");
  4612. this.isSeekTo = false;
  4613. },
  4614. onResult:(result: boolean,outPath:string)=>{
  4615. if(result){//如果成功,更新数据
  4616. this.doUpdateData()
  4617. }else{
  4618. ToastUtil.showToast('变速变调失败')
  4619. }
  4620. }
  4621. }
  4622. )
  4623. }
  4624. }
  4625. .width('100%')
  4626. .height('100%')
  4627. }
  4628. //提取视频中的音频
  4629. @Builder
  4630. extractAudioFromVideoBuilder(item:VideoItem) {
  4631. Scroll() {
  4632. Column() {
  4633. ExtractAudioFromVideo(
  4634. {
  4635. mVideoItem:item,
  4636. currentPath:this.currentPath,
  4637. videoUrl:this.videoUrl,
  4638. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4639. currentTime:this.currentTime,
  4640. progressValue:this.progressValue,
  4641. onBack:()=>{
  4642. this.isExtractAudio = !this.isExtractAudio
  4643. this.longItemFilePath = ''
  4644. },
  4645. onPlayOrPause:()=>{
  4646. if(this.videoUrl==item.filePath){
  4647. this.playOrPause()
  4648. }else{//如果不是当前播放的,则播放该文件
  4649. this.videoUrl==item.filePath
  4650. this.doPlay(item,0,false,true)
  4651. }
  4652. },
  4653. onSeeOutputPath:(outPutPath:string)=>{
  4654. this.isExtractAudio = !this.isExtractAudio
  4655. this.longItemFilePath = ''
  4656. this.modeType = 0
  4657. this.isShowFileName = true
  4658. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4659. },
  4660. onSliderChange:(value:number)=>{
  4661. if(this.videoUrl!=item.filePath){
  4662. this.videoUrl==item.filePath
  4663. return
  4664. }
  4665. this.isSeekTo = true;
  4666. this.mDestroyPage = false;
  4667. this.showLoadIng();
  4668. let seekValue = value * (this.getActiveDuration() / 100);
  4669. this.seekTo(seekValue + "");
  4670. this.isSeekTo = false;
  4671. },
  4672. onResult:(result: boolean,outPath:string)=>{
  4673. if(result){//如果成功,更新数据
  4674. this.doUpdateData()
  4675. }else{
  4676. ToastUtil.showToast('提取音频失败')
  4677. }
  4678. }
  4679. }
  4680. )
  4681. }
  4682. }
  4683. .width('100%')
  4684. .height('100%')
  4685. }
  4686. //合并音频
  4687. @Builder
  4688. MergeAudioBuilder() {
  4689. Scroll() {
  4690. Column() {
  4691. MergeAudio(
  4692. {
  4693. videoUrl:this.videoUrl,
  4694. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4695. currentPath:this.currentPath,
  4696. selectedFiles:this.selectedFiles,
  4697. currentTime:this.currentTime,
  4698. progressValue:this.progressValue,
  4699. onBack:()=>{
  4700. this.isMergeAudio = !this.isMergeAudio
  4701. this.longItemFilePath = ''
  4702. },
  4703. // onPlayPath:(path:string)=>{
  4704. // if(this.videoUrl==item.filePath){
  4705. // this.playOrPause()
  4706. // }else{//如果不是当前播放的,则播放该文件
  4707. // this.videoUrl==item.filePath
  4708. // this.doPlay(item,0,false,true)
  4709. // }
  4710. //
  4711. // },
  4712. onSeeOutputPath:(outPutPath:string)=>{
  4713. this.isMergeAudio = !this.isMergeAudio
  4714. this.longItemFilePath = ''
  4715. this.modeType = 0
  4716. this.isShowFileName = true
  4717. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4718. },
  4719. onResult:(result: boolean,outPath:string)=>{
  4720. if(result){//如果成功,更新数据
  4721. this.doUpdateData()
  4722. }else{
  4723. if(this.selectedFiles.length>=3){
  4724. ToastUtil.showToast('合并数量太多导致失败')
  4725. }else{
  4726. ToastUtil.showToast('合并失败')
  4727. }
  4728. }
  4729. }
  4730. }
  4731. )
  4732. }
  4733. }
  4734. .width('100%')
  4735. .height('100%')
  4736. }
  4737. asyncCurrentPathData() {
  4738. if (this.modeType == 0) {
  4739. workerInstance.postMessage({
  4740. code: 1,
  4741. data1: this.context,
  4742. data2: this.currentPath,
  4743. data3: this.lockPath,
  4744. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  4745. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  4746. });
  4747. }
  4748. }
  4749. // 处理文件选择的函数
  4750. handleFileSelection(item: VideoItem, checked: boolean) {
  4751. if (!this.isSelectableLocalItem(item)) {
  4752. return
  4753. }
  4754. const exists = this.isLocalItemSelected(item)
  4755. if (checked) {
  4756. if (!exists) {
  4757. this.selectedFiles = [...this.selectedFiles, item];
  4758. }
  4759. } else if (exists) {
  4760. this.selectedFiles = this.selectedFiles.filter(selected => selected.filePath !== item.filePath);
  4761. if (this.selectedFiles.length === 0) {
  4762. this.isAllSelected = false
  4763. }
  4764. }
  4765. this.syncLocalSelectionState()
  4766. }
  4767. private deleteComponentId: number = 0
  4768. private closeDeleteDialog(afterClose?: () => void): void {
  4769. if (this.deleteComponentId > 0) {
  4770. try {
  4771. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  4772. } catch (_error) {
  4773. }
  4774. this.deleteComponentId = 0
  4775. }
  4776. if (afterClose) {
  4777. setTimeout(() => {
  4778. afterClose()
  4779. }, 16)
  4780. }
  4781. }
  4782. private resetDeleteSelectionState(): void {
  4783. this.isMultiSelect = false
  4784. this.selectedFiles = []
  4785. this.isAllSelected = false
  4786. }
  4787. private removeDisplayedLocalItemsByKeys(deletedKeys: Set<string>): void {
  4788. for (let index = this.dataSource.dataArray.length - 1; index >= 0; index--) {
  4789. const item = this.dataSource.dataArray[index]
  4790. if (item && deletedKeys.has(item.filePath)) {
  4791. this.dataSource.deleteData(index)
  4792. }
  4793. }
  4794. }
  4795. private async removeDeletedLocalItemsLocally(deletedItems: Array<VideoItem>): Promise<void> {
  4796. if (ArrayUtil.isEmpty(deletedItems) || this.modeType !== 0) {
  4797. return
  4798. }
  4799. const deletedKeys: Set<string> = new Set<string>()
  4800. for (let i = 0; i < deletedItems.length; i++) {
  4801. const item = deletedItems[i]
  4802. if (StrUtil.isNotEmpty(item?.filePath)) {
  4803. deletedKeys.add(item.filePath)
  4804. }
  4805. }
  4806. if (deletedKeys.size <= 0) {
  4807. return
  4808. }
  4809. const nextVideoLocalList = this.videoLocalList.filter((item: VideoItem) => !deletedKeys.has(item.filePath))
  4810. const nextDirList = this.dirList.filter((item: VideoItem) => !deletedKeys.has(item.filePath))
  4811. const nextFilteredList = this.filteredList.filter((item: VideoItem) => !deletedKeys.has(item.filePath))
  4812. const removedCount = this.videoLocalList.length - nextVideoLocalList.length
  4813. this.videoLocalList = nextVideoLocalList
  4814. this.dirList = nextDirList
  4815. this.filteredList = nextFilteredList
  4816. this.removeDisplayedLocalItemsByKeys(deletedKeys)
  4817. if (removedCount > 0 && this.totalCount > 0) {
  4818. this.totalCount = Math.max(0, this.totalCount - removedCount)
  4819. }
  4820. this.pageCache.clear()
  4821. this.pageHasMoreCache.clear()
  4822. this.pageTotalCountCache.clear()
  4823. this.setButtonStatus()
  4824. this.markAlphaBetDirty()
  4825. this.syncLocalSelectionState()
  4826. this.addCache(this.currentPath, nextVideoLocalList)
  4827. if (this.currentPath === this.rootPath) {
  4828. this.addCache(this.currentPath + '_dirList', nextDirList)
  4829. }
  4830. this.deleteStringCache(this.currentPath + '_hash')
  4831. await this.saveCacheToStorage()
  4832. }
  4833. //多选删除文件
  4834. showWarnIsDelete(){
  4835. this.getUIContext().getPromptAction().openCustomDialog({
  4836. builder: () => {
  4837. this.deleteComptentBuilder()
  4838. },
  4839. isModal:true,
  4840. showInSubWindow:false,
  4841. maskColor: Color.Transparent,
  4842. dialogTransition: // 设置弹窗内容显示的过渡效果
  4843. TransitionEffect.translate({ x: 0, y: 120, z: 0 })
  4844. .combine(TransitionEffect.opacity(0.01))
  4845. .animation({ duration: 260, curve: Curve.EaseOut }),
  4846. maskTransition: // 设置蒙层显示的过渡效果
  4847. TransitionEffect.opacity(0)
  4848. .animation({ duration: 220, curve: Curve.EaseOut })
  4849. }).then((dialogId: number) => {
  4850. this.deleteComponentId = dialogId
  4851. })
  4852. .catch((error: BusinessError) => {
  4853. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  4854. })
  4855. }
  4856. @Builder
  4857. deleteComptentBuilder(){
  4858. DeleteComptent({
  4859. selectedFiles:this.selectedFiles,
  4860. isPlaylistMode: this.modeType == 4,
  4861. playlistId: this.currentSongListID,
  4862. onCancel:()=>{
  4863. this.closeDeleteDialog(() => {
  4864. this.resetDeleteSelectionState()
  4865. })
  4866. },
  4867. onDeleteResult:(result: boolean)=>{
  4868. const deletedItems = [...this.selectedFiles]
  4869. this.closeDeleteDialog(() => {
  4870. this.resetDeleteSelectionState()
  4871. if(result){//如果删除成功,更新数据
  4872. if (this.modeType == 4) {
  4873. this.doSongListTask()
  4874. } else {
  4875. void this.removeDeletedLocalItemsLocally(deletedItems)
  4876. }
  4877. }
  4878. })
  4879. }
  4880. })
  4881. }
  4882. //多选移动文件
  4883. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  4884. Logger.info('onecold showCutDialogForMultipleFiles')
  4885. let mList: Array<string> = []
  4886. let rPath = this.rootPath
  4887. if (isCurrent) {
  4888. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  4889. rPath = this.currentPath
  4890. } else {
  4891. mList = Utility.getNameList(this.dirList);
  4892. rPath = this.rootPath
  4893. }
  4894. let dataBean = new BubbleBean();
  4895. dataBean.data = mList;
  4896. dataBean.color = this.themeColor
  4897. dataBean.onItemClick = (i) => {
  4898. const newDirPath = rPath + '/' + mList[i];
  4899. // Logger.info('newDirPath = ' + newDirPath)
  4900. this.selectedFiles.forEach((item) => {
  4901. const targetName = item.fileName || item.name;
  4902. const newPath = newDirPath + '/' + targetName;
  4903. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  4904. ToastUtil.showToast('移动成功');
  4905. this.table.deleteData(item, () => {
  4906. this.cache.delete(this.currentPath); // 删除原路径缓存
  4907. this.cache.delete(newDirPath); // 删除目标路径缓存
  4908. this.getSortedFiles(this.currentPath, true);
  4909. });
  4910. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  4911. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  4912. if (!Utility.isIsoByExtension(newPath)) {
  4913. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  4914. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  4915. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  4916. this.table.insert(newItem, (id: number) => {
  4917. //加入数据库
  4918. });
  4919. }
  4920. }
  4921. }).catch((error: Error) => {
  4922. console.error(error.message);
  4923. });
  4924. });
  4925. this.isMultiSelect = false
  4926. this.selectedFiles = [];
  4927. this.isAllSelected = false
  4928. XPopup.dismissTop();
  4929. };
  4930. let pup: XPopup
  4931. if (this.isDarkMode) {
  4932. pup = XPopup.Builder()
  4933. .setPopupPosition(PopupPosition.TOP)
  4934. .atView(viewId)
  4935. .setBackgroundColor(Color.Black)
  4936. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4937. .show();
  4938. } else {
  4939. pup = XPopup.Builder()
  4940. .setPopupPosition(PopupPosition.TOP)
  4941. .atView(viewId)
  4942. .setBackgroundColor(Color.White)
  4943. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4944. .show();
  4945. }
  4946. }
  4947. /**
  4948. * 加载所有歌单
  4949. */
  4950. async loadAllPlaylists() {
  4951. try {
  4952. this.allPlaylists = await this.playlistTable?.queryAllPlaylists()!
  4953. LogUtil.info('heanup Loaded playlists: ' + this.allPlaylists.length)
  4954. } catch (error) {
  4955. LogUtil.error('heaunp Failed to load playlists: ' + error.message)
  4956. }
  4957. }
  4958. /**
  4959. * 显示添加到歌单对话框
  4960. */
  4961. async openAddToPlaylistDialog(items: VideoItem | VideoItem[]) {
  4962. const songs = Array.isArray(items) ? items : [items]
  4963. const musicItems = songs.filter(song =>
  4964. song.type !== CommonConstants.TYPE_IS_DIR && !this.isIsoLocalFile(song))
  4965. if (musicItems.length === 0) {
  4966. ToastUtil.showToast('请选择要添加的歌曲')
  4967. return
  4968. }
  4969. // 加载最新的歌单列表
  4970. await this.loadAllPlaylists()
  4971. showAddToPlaylistDialog(
  4972. musicItems,
  4973. this.allPlaylists,
  4974. async (playlistId: string) => {
  4975. // 添加歌曲到歌单
  4976. const success = await this.playlistTable?.addSongsToPlaylist(playlistId,
  4977. musicItems.map(song => song.filePath))
  4978. if (success) {
  4979. const count = musicItems.length
  4980. ToastUtil.showToast(count > 1 ? `已添加 ${count} 首歌曲` : '已添加到歌单')
  4981. // 重新加载歌单列表
  4982. await this.loadAllPlaylists()
  4983. } else {
  4984. ToastUtil.showToast(musicItems.length > 1 ? '选中的歌曲已在该歌单中' : '歌曲已在该歌单中')
  4985. }
  4986. this.longItemFilePath = ''
  4987. if (this.isMultiSelect) {
  4988. this.isMultiSelect = false
  4989. this.isAllSelected = false
  4990. this.selectedFiles = []
  4991. }
  4992. },
  4993. () => {
  4994. LogUtil.info('取消添加到歌单')
  4995. },
  4996. () => {
  4997. // 创建新歌单
  4998. showCreatePlaylistDialog(
  4999. async (name: string, description: string, coverPath?: string) => {
  5000. const success = await this.playlistTable?.createPlaylist(name, description, coverPath)
  5001. if (success) {
  5002. ToastUtil.showToast('歌单创建成功')
  5003. // 重新加载歌单列表并打开添加对话框
  5004. await this.loadAllPlaylists()
  5005. await this.openAddToPlaylistDialog(musicItems)
  5006. } else {
  5007. ToastUtil.showToast('歌单创建失败')
  5008. }
  5009. },
  5010. () => {
  5011. // 取消创建歌单
  5012. }
  5013. )
  5014. }
  5015. )
  5016. }
  5017. private syncFavStateLocal(item: VideoItem, isFav: number): void {
  5018. const nextFavList = [...this.favList];
  5019. const favIndex = nextFavList.findIndex((favItem: VideoItem) => favItem.filePath === item.filePath);
  5020. if (isFav === 1) {
  5021. if (favIndex >= 0) {
  5022. nextFavList[favIndex].isFav = 1;
  5023. } else {
  5024. const favItem = cloneVideoItem(item);
  5025. favItem.isFav = 1;
  5026. nextFavList.push(favItem);
  5027. }
  5028. } else if (favIndex >= 0) {
  5029. nextFavList.splice(favIndex, 1);
  5030. }
  5031. this.favList = nextFavList;
  5032. item.isFav = isFav;
  5033. if (this.currentSong && this.currentSong.filePath === item.filePath) {
  5034. this.currentSong.isFav = isFav;
  5035. this.isFac = isFav === 1;
  5036. }
  5037. }
  5038. doFav(item: VideoItem) {
  5039. LogUtil.info('onecold doFav isFav=' + item.isFav)
  5040. let isFav = 0
  5041. if (Utility.getIsFav(this.favList, item)) {
  5042. isFav = 0
  5043. } else {
  5044. isFav = 1
  5045. }
  5046. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  5047. if (result) {
  5048. this.syncFavStateLocal(item, isFav);
  5049. if (isFav === 1) {
  5050. ToastUtil.showToast('收藏成功');
  5051. } else {
  5052. ToastUtil.showToast('取消收藏成功');
  5053. }
  5054. this.deleteCache(this.currentPath)
  5055. this.getFavList(false)
  5056. if (this.modeType === 0 && !this.isFavMusic) {
  5057. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  5058. this.getSortedFiles(this.currentPath)
  5059. }
  5060. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  5061. workerInstance.postMessage({ code: 3, data: this.context });
  5062. workerInstance.postMessage({ code: 4, data: this.context });
  5063. }
  5064. })
  5065. }
  5066. //多选复制文件
  5067. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  5068. console.log('onecold showCopyDialogForMultipleFiles');
  5069. let mList: Array<string> = []
  5070. let rPath = this.rootPath
  5071. if (isCurrent) {
  5072. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  5073. rPath = this.currentPath
  5074. } else {
  5075. mList = Utility.getNameList(this.dirList);
  5076. rPath = this.rootPath
  5077. }
  5078. let dataBean = new BubbleBean();
  5079. dataBean.data = mList;
  5080. dataBean.isCopy = true
  5081. dataBean.color = this.themeColor
  5082. dataBean.onItemClick = (i) => {
  5083. const newDirPath = rPath + '/' + mList[i];
  5084. // Logger.info('newDirPath = ' + newDirPath)
  5085. this.selectedFiles.forEach((item) => {
  5086. const targetName = item.fileName || item.name;
  5087. const newPath = newDirPath + '/' + targetName;
  5088. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  5089. ToastUtil.showToast('复制成功');
  5090. this.cache.delete(newDirPath); // 删除目标路径缓存
  5091. this.getSortedFiles(this.currentPath);
  5092. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  5093. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  5094. if (!Utility.isIsoByExtension(newPath)) {
  5095. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  5096. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  5097. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  5098. this.table.insert(newItem, (id: number) => {
  5099. //加入数据库
  5100. });
  5101. }
  5102. }
  5103. }).catch((error: Error) => {
  5104. console.error(error.message);
  5105. });
  5106. });
  5107. this.isMultiSelect = false
  5108. this.selectedFiles = [];
  5109. this.isAllSelected = false
  5110. XPopup.dismissTop();
  5111. };
  5112. let pup: XPopup
  5113. if (this.isDarkMode) {
  5114. pup = XPopup.Builder()
  5115. .setPopupPosition(PopupPosition.TOP)
  5116. .atView(viewId)
  5117. .setBackgroundColor(Color.Black)
  5118. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  5119. .show();
  5120. } else {
  5121. pup = XPopup.Builder()
  5122. .setPopupPosition(PopupPosition.TOP)
  5123. .atView(viewId)
  5124. .setBackgroundColor(Color.White)
  5125. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  5126. .show();
  5127. }
  5128. }
  5129. @Builder
  5130. private DirItem(item: VideoItem, index?: number) {
  5131. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5132. Row() {
  5133. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ?
  5134. this.getListImageSource(item, index ?? -1, this.coverThumbVersion) :
  5135. $r('app.media.music_group'))
  5136. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  5137. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  5138. .fillColor(this.themeColor)// .fontSize(33)
  5139. .alt($r('app.media.music_group'))
  5140. .borderRadius(this.isCoverRectangle?9:'100%')
  5141. .clip(true)
  5142. .shadow({
  5143. radius: 2,
  5144. type: ShadowType.BLUR,
  5145. color: 'on_primary'
  5146. })
  5147. .sourceSize({width:38, height:38})
  5148. .margin({ left: 20, top: 8, bottom: 8 })
  5149. Column() {
  5150. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  5151. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5152. .maxLines(1)// .width('88%')
  5153. .textOverflow({ overflow: TextOverflow.Ellipsis })//列表模式固定省略,避免滚动跑马灯开销
  5154. .margin({ left: 10, right: 20 })
  5155. .fontColor($r('app.color.text_color'))
  5156. Row() {
  5157. Text(`${this.getArtistSongCount(item.name)}首`)
  5158. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5159. .padding({ top: 8 })
  5160. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  5161. .fontColor($r('app.color.text_color'))
  5162. .margin({ left: 10 })
  5163. Text(`${this.getAlbumSongCount(item.name)}首`)
  5164. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5165. .padding({ top: 8 })
  5166. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  5167. .fontColor($r('app.color.text_color'))
  5168. .margin({ left: 10 })
  5169. Blank()
  5170. }
  5171. }
  5172. .height('100%')
  5173. .width('100%')
  5174. .justifyContent(FlexAlign.Center)
  5175. .alignItems(HorizontalAlign.Start)
  5176. Blank()
  5177. Checkbox({ name: 'dir_checkbox' + (index ?? -1) })
  5178. .select(this.isLocalItemSelected(item))
  5179. .selectedColor(this.themeColor)
  5180. .shape(CheckBoxShape.CIRCLE)
  5181. .opacity(this.isMultiSelect && this.isSelectableLocalItem(item) ? 1 : 0)
  5182. .visibility(this.isMultiSelect && this.isSelectableLocalItem(item) ? Visibility.Visible : Visibility.None)
  5183. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5184. .margin({ left: 20, top: 8, bottom: 8, right: 18 })
  5185. .width(22)
  5186. .height(22)
  5187. Image($r('app.media.arrow_right'))
  5188. .height(25)
  5189. .alignSelf(ItemAlign.Center)
  5190. .id(item.filePath)
  5191. .visibility(this.isShowAlphaBet || (this.isMultiSelect && this.isSelectableLocalItem(item)) ?
  5192. Visibility.None : Visibility.Visible)
  5193. }
  5194. }
  5195. .backgroundColor(Color.Transparent)
  5196. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  5197. .width('98%')
  5198. .reuseId('dir_item')
  5199. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  5200. .opacity(this.opacityItem) // 绑定透明度
  5201. }
  5202. private refreshDirVisibilitySettings(): void {
  5203. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  5204. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  5205. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  5206. }
  5207. isShowDir(dirName: string) {
  5208. if (dirName === undefined) {
  5209. return true
  5210. }
  5211. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  5212. return this.isShowSimi
  5213. }
  5214. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  5215. return this.isShowFAV
  5216. }
  5217. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  5218. return this.isShowHistory
  5219. }
  5220. return true
  5221. }
  5222. @State opacityItem: number = 1; // 控制透明度的状态变量
  5223. @Builder
  5224. private MusicItem(item: VideoItem, index?: number) {
  5225. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  5226. Row() {
  5227. Stack() {
  5228. Image(this.getListImageSource(item, index ?? -1, this.coverThumbVersion))
  5229. .fillColor(this.themeColor)
  5230. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  5231. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  5232. .alt($r('app.media.alt'))
  5233. .borderRadius(this.isCoverRectangle?9:'100%')
  5234. .clip(true)
  5235. .draggable(false)
  5236. .sourceSize({width:38, height:38})
  5237. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  5238. // .autoResize(true) // 重采样,可减少内存占用
  5239. .opacity(this.opacityItem)// 绑定透明度
  5240. .margin({ left: 20 })
  5241. .shadow({
  5242. radius: this.isScrolling ? 0 : 10,
  5243. type: ShadowType.BLUR,
  5244. color: 'on_primary'
  5245. })
  5246. .onClick(()=>{
  5247. if (this.isMultiSelect) {
  5248. const isChecked = this.isLocalItemSelected(item);
  5249. this.handleFileSelection(item, !isChecked);
  5250. } else {
  5251. this.doPlay(item,index)
  5252. this.setShowPlayTrue()
  5253. }
  5254. })
  5255. }
  5256. Column() {
  5257. Column() {
  5258. Text(this.isShowFileName?item.fileName :item.name)
  5259. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5260. .maxLines(1)
  5261. .textOverflow({ overflow: this.isLongNameRoLL&&!this.isScrolling?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5262. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5263. $r('app.color.text_color'))
  5264. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5265. .padding({right:25})
  5266. .bindPopup(this.longItemFilePath === item.filePath, {
  5267. builder: this.MenuBuilder(item,index,item.filePath),
  5268. placement: Placement.Top,
  5269. // autoCancel: true,
  5270. mask: {color:'#33000000'},
  5271. // popupColor: Color.Yellow,
  5272. enableArrow: false,//是否显示箭头
  5273. showInSubWindow: false,
  5274. onStateChange: (e) => {
  5275. if (!e.isVisible) {
  5276. this.longItemFilePath = ''
  5277. this.tempLyricContent = ''
  5278. }
  5279. }
  5280. })
  5281. Row() {
  5282. Column(){
  5283. Text(item.md5Str?.includes('Lossless')?
  5284. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5285. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  5286. .padding({ top: 3,right:6,left:6,bottom:3 })
  5287. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5288. $r('app.color.text_color'))
  5289. .fontWeight(500)
  5290. .borderRadius(12)
  5291. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  5292. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5293. .backgroundColor('#FFC107')
  5294. }
  5295. .padding({ top: 8 })
  5296. Text(StrUtil.isEmpty(item.artist) ? item.duration
  5297. :this.twoFingerType==2? item.artist +' ' + item.duration
  5298. : item.artist + ' ' + item?.duration)
  5299. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5300. .padding({ top: 8 ,right:25})
  5301. .visibility(this.isShowFileName?Visibility.None:Visibility.Visible)
  5302. .maxLines(1)
  5303. .textOverflow({ overflow: TextOverflow.Ellipsis })//列表模式固定省略
  5304. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5305. Color.Gray)
  5306. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5307. Blank()
  5308. Text(this.isShowFileName?item.duration:item.size)
  5309. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  5310. .padding({ top: 8 })
  5311. .maxLines(1)
  5312. .visibility(this.isShowFileName?Visibility.Visible:StrUtil.isEmpty(item.artist)
  5313. ? Visibility.Visible : Visibility.None)
  5314. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5315. Color.Gray)
  5316. .margin({ left: StrUtil.isEmpty(item.artist) ?0:10 })
  5317. }
  5318. }
  5319. .height('100%')
  5320. .width('100%')
  5321. .margin({ right: 10 })
  5322. .justifyContent(FlexAlign.Center)
  5323. .alignItems(HorizontalAlign.Start)
  5324. }
  5325. .height('100%')
  5326. .margin({ left: 5 })
  5327. .layoutWeight(1)
  5328. Column() {
  5329. Checkbox({ name: 'checkbox' + index })
  5330. .select(this.isLocalItemSelected(item))
  5331. .selectedColor(this.themeColor)
  5332. .shape(CheckBoxShape.CIRCLE)
  5333. .opacity(this.isMultiSelect ? 1 : 0)
  5334. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  5335. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5336. .margin({ left: 20, top: 8, bottom: 8,right:18 })
  5337. .width(22)
  5338. .height(22)
  5339. PlayingIndicator({
  5340. isActive: this.videoUrl === item.filePath && !this.isMultiSelect,
  5341. indicatorSize: 18,
  5342. marginRight: 20,
  5343. marginTop: 8,
  5344. marginBottom: 8
  5345. })
  5346. }
  5347. }
  5348. }
  5349. .gesture(LongPressGesture()
  5350. .onAction(async () => {
  5351. //如果是专辑和艺术家的首页,不能长按
  5352. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  5353. return
  5354. //如果是我的收藏 最近播放等也不能长按
  5355. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5356. item.name === LocalMusic.STR_HISTORY_MUSIC
  5357. )
  5358. return
  5359. this.longItemFilePath = item.filePath
  5360. this.tempLyricContent = this.supportsLocalAudioActions(item) ? await this.getLyricContent(item) : ''
  5361. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  5362. })
  5363. .onActionEnd((event: GestureEvent) => {
  5364. }))
  5365. .backgroundColor(Color.Transparent)
  5366. .width('100%')
  5367. .reuseId('file_item')
  5368. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  5369. }
  5370. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  5371. @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
  5372. buttons: [{ text: '文件夹' }, { text: '媒体库' },{ text: '艺术家' }, { text: '专辑' }],
  5373. direction: Direction.Ltr,
  5374. buttonPadding:{top:12,bottom:12},
  5375. backgroundColor: Color.Transparent,
  5376. fontSize:14,
  5377. selectedFontSize:15,
  5378. selectedFontColor:Color.White,
  5379. selectedBackgroundColor: this.themeColor,
  5380. localizedTextPadding: {
  5381. end: LengthMetrics.vp(20),
  5382. start: LengthMetrics.vp(20)
  5383. }
  5384. })
  5385. @State @Watch('capsuleSelectedIndexesChanged')tabSelectedIndexes: number[] = [0]
  5386. //当胶囊按钮的选择发生变化时调用此函数
  5387. capsuleSelectedIndexesChanged() {
  5388. this.modeType = this.tabSelectedIndexes[0]
  5389. }
  5390. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  5391. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  5392. isShowCoverHeader() {
  5393. if (!this.isShowHeader) {
  5394. return false
  5395. }
  5396. if (this.modeType == 0) {
  5397. if (this.isHistory || this.isFavMusic) {
  5398. return true
  5399. }
  5400. if (this.currentPath != this.rootPath) {
  5401. return true
  5402. }
  5403. }
  5404. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  5405. }
  5406. getCoverTitleBg(): ResourceStr | image.PixelMap {
  5407. if (this.isCustomizeBg) {
  5408. return ('rgba(255,255,255,0.2)')
  5409. }
  5410. if (this.isDarkMode) {
  5411. return $r('app.color.user_center_card_background')
  5412. }
  5413. return this.currentTitleCover
  5414. }
  5415. // 第二步:popup构造器定义弹框内容
  5416. @Builder popupBuilder() {
  5417. Column({ space: 2 }) {
  5418. Text('友情提示:双指缩放可以放大缩小列表')
  5419. .fontSize(12)
  5420. .fontWeight(FontWeight.Regular)
  5421. .fontColor($r('app.color.text_color'))
  5422. }
  5423. .justifyContent(FlexAlign.SpaceAround)
  5424. .width(220)
  5425. .height(55)
  5426. .padding(15)
  5427. }
  5428. //搜索功能的实现
  5429. @State searchText: string = ''; // 用户输入内容
  5430. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  5431. @State isSearchMode: boolean = false
  5432. @State searchHistoryItems: string[] = []
  5433. private readonly searchHistoryScope: string = 'local_music'
  5434. private loadSearchHistory(): void {
  5435. this.searchHistoryItems = SearchHistoryUtil.load(this.searchHistoryScope)
  5436. }
  5437. private saveSearchHistory(keyword: string): void {
  5438. this.searchHistoryItems = SearchHistoryUtil.save(this.searchHistoryScope, keyword)
  5439. }
  5440. private commitSearchHistory(keyword: string): void {
  5441. const normalized = keyword.trim()
  5442. if (normalized.length === 0) {
  5443. return
  5444. }
  5445. this.saveSearchHistory(normalized)
  5446. }
  5447. private applySearchHistory(keyword: string): void {
  5448. this.searchText = keyword
  5449. this.searchController.stopEditing()
  5450. void this.onSearchInput(keyword)
  5451. }
  5452. // 实时搜索逻辑(带防抖)
  5453. private async onSearchInput(value: string): Promise<void> {
  5454. this.searchText = value.trim();
  5455. Logger.info('heanup LocalMusic', `onSearchInput: keyword="${this.searchText}", mode=${this.modeType}`);
  5456. // 清空搜索文本时保持搜索态,只重置为不带关键词的结果列表
  5457. if (this.searchText === '') {
  5458. this.loadSearchHistory()
  5459. await this.resetAndLoadFirstPage();
  5460. return;
  5461. }
  5462. // 进入搜索模式
  5463. if (!this.isSearchMode) {
  5464. this.isSearchMode = true;
  5465. }
  5466. // 使用数据库分页查询(带搜索条件)
  5467. await this.resetAndLoadFirstPage();
  5468. }
  5469. @Builder
  5470. private SearchHistoryView(): void {
  5471. Column({ space: 10 }) {
  5472. Row() {
  5473. Text('搜索历史')
  5474. .fontSize(14)
  5475. .fontWeight(FontWeight.Medium)
  5476. .fontColor($r('app.color.text_color'))
  5477. Blank()
  5478. Button('清空')
  5479. .fontSize(12)
  5480. .fontColor(this.themeColor)
  5481. .backgroundColor(Color.Transparent)
  5482. .padding({ left: 8, right: 8, top: 4, bottom: 4 })
  5483. .onClick(() => {
  5484. SearchHistoryUtil.clear(this.searchHistoryScope)
  5485. this.searchHistoryItems = []
  5486. })
  5487. }
  5488. .width('100%')
  5489. Flex({ wrap: FlexWrap.Wrap }) {
  5490. ForEach(this.searchHistoryItems, (keyword: string) => {
  5491. Button(keyword)
  5492. .fontSize(12)
  5493. .fontColor($r('app.color.text_color'))
  5494. .backgroundColor(this.isDarkMode ? '#222222' : '#F2F3F5')
  5495. .borderRadius(16)
  5496. .margin({ right: 8, bottom: 8 })
  5497. .padding({ left: 12, right: 12, top: 8, bottom: 8 })
  5498. .onClick(() => {
  5499. this.applySearchHistory(keyword)
  5500. })
  5501. })
  5502. }
  5503. .width('100%')
  5504. }
  5505. .width('100%')
  5506. .padding({ left: 16, right: 16, top: 10, bottom: 10 })
  5507. }
  5508. @State dragItem: number = -1
  5509. @State scaleItem: number = -1
  5510. @State neighborItem: number = -1
  5511. @State neighborScale: number = -1
  5512. @State offsetY: number = 0
  5513. private dragRefOffset: number = 0
  5514. private ITEM_INTV: number = 78
  5515. scaleSelect(item: number): number {
  5516. if (this.scaleItem === item) {
  5517. return 1.05
  5518. } else if (this.neighborItem === item) {
  5519. return this.neighborScale
  5520. } else {
  5521. return 1
  5522. }
  5523. }
  5524. itemMove(index: number, newIndex: number): void {
  5525. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  5526. return;
  5527. }
  5528. let tmp = this.videoLocalList.splice(index, 1);
  5529. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  5530. this.dataSource.pushArrayData(this.videoLocalList)
  5531. if(this.modeType==4&&this.playlistTable){
  5532. updateAllSongsSortOrder(this.playlistTable, this.videoLocalList,this.currentSongListID)
  5533. }
  5534. }
  5535. //瀑布流布局 支持双指缩放
  5536. @State columns: number = 2;
  5537. @State waterFlowScale: number = 1;
  5538. @State imageScale: number = 1;
  5539. @State waterFlowOpacity: number = 1;
  5540. @State waterFlowSnapshot: image.PixelMap | undefined = undefined;
  5541. private columnChanged: boolean = false;
  5542. private oldColumn: number = this.columns;
  5543. private pinchTime: number = 0;
  5544. // 根据缩放阈值改变列数,触发WaterFlow重新布局
  5545. changeColumns(scale: number): void {
  5546. if (scale > (this.columns / (this.columns - 0.5)) && this.columns > 1) {
  5547. this.columns--;
  5548. this.columnChanged = true;
  5549. } else if (scale < 1 && this.columns < 4) {
  5550. this.columns++;
  5551. this.columnChanged = true;
  5552. }
  5553. }
  5554. @Builder
  5555. getWaterView(){
  5556. Scroll(this.scroller) {
  5557. Column() {
  5558. Blank().height(this.topSafeHeight + 55)
  5559. WaterFlow({
  5560. scroller:this.waterScroller,
  5561. layoutMode: WaterFlowLayoutMode.SLIDING_WINDOW
  5562. }) {
  5563. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5564. FlowItem() {
  5565. this.MusicWaterCardItem(item,index)
  5566. }
  5567. .width('100%')
  5568. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  5569. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  5570. {
  5571. preview: MenuPreviewMode.IMAGE
  5572. })
  5573. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  5574. {
  5575. preview: MenuPreviewMode.IMAGE
  5576. })
  5577. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5578. }
  5579. // .columnsTemplate('repeat(auto-fit, 160)')
  5580. .id('waterflow') // 设置id用于截图
  5581. .columnsTemplate('1fr '.repeat(this.columns)) // 动态生成列模板,如:'1fr 1fr 1fr'表示3列等宽
  5582. .columnsGap(12) // 列间距
  5583. .rowsGap(this.columns >= 4 ? 8 : (this.columns == 3 ? 10 : 14)) // 行间距
  5584. .cachedCount(this.columns >= 4 ? 2 : (this.columns == 3 ? 3 : 4))
  5585. .padding({bottom:this.bottomBarHeight+10})
  5586. .scrollBar(BarState.Off)
  5587. // .fadingEdge(true, { fadingEdgeLength: LengthMetrics.vp(38) })
  5588. // 效果:只有向上或者向下滑动到顶部时才会有弹簧回弹效果
  5589. .edgeEffect(EdgeEffect.None)
  5590. .width('90%')
  5591. .height('100%')
  5592. .opacity(this.waterFlowOpacity)
  5593. .scale({
  5594. x: this.waterFlowScale,
  5595. y: this.waterFlowScale,
  5596. centerX: 0,
  5597. centerY: 0
  5598. })
  5599. .onReachEnd(() => {
  5600. if(this.modeType === 4 )
  5601. return;
  5602. // 触底加载下一页
  5603. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  5604. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  5605. return;
  5606. }
  5607. if (this.hasMoreData && !this.isLoadingPage && !this.isPagingTransition) {
  5608. this.scheduleLoadNextPage();
  5609. }
  5610. })
  5611. .onAppear(() => {
  5612. this.scroller.scrollEdge(Edge.Top)
  5613. })
  5614. .nestedScroll({
  5615. scrollForward: NestedScrollMode.PARENT_FIRST,
  5616. scrollBackward: NestedScrollMode.SELF_FIRST
  5617. })
  5618. .priorityGesture(
  5619. PinchGesture()
  5620. .onActionStart((event: GestureEvent) => {
  5621. // 双指捏合手势识别成功时截图
  5622. this.pinchTime = event.timestamp;
  5623. this.columnChanged = false;
  5624. this.oldColumn = this.columns;
  5625. this.getUIContext().getComponentSnapshot().get('waterflow', (error: Error, pixmap: image.PixelMap) => {
  5626. if (error) {
  5627. console.info('error:' + JSON.stringify(error));
  5628. return;
  5629. }
  5630. this.waterFlowSnapshot = pixmap;
  5631. if ((this.oldColumn === 1 ) && event.scale > 1|| (this.oldColumn === 4 && event.scale < 1)) {
  5632. console.info("onecold onActionStart oldColumn:" + this.oldColumn)
  5633. if (this.oldColumn ===4) {
  5634. this.twoFingerType =3
  5635. this.isGridMusic = true
  5636. }else if (this.oldColumn ===1) {
  5637. this.twoFingerType =1
  5638. this.isGridMusic = false
  5639. }
  5640. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  5641. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5642. return;
  5643. }
  5644. })
  5645. })
  5646. .onActionUpdate((event: GestureEvent) => {
  5647. // 手势更新:处理缩放逻辑和视觉效果
  5648. // 边界限制:防止超出列数范围时继续缩放
  5649. if ((this.oldColumn === 1 && event.scale > 1) || (this.oldColumn === 4 && event.scale < 1)) {
  5650. return;
  5651. }
  5652. // 节流处理:避免过于频繁的更新,提升性能
  5653. if (event.timestamp - this.pinchTime < 10000000) {
  5654. return;
  5655. }
  5656. this.pinchTime = event.timestamp;
  5657. this.waterFlowScale = event.scale;
  5658. this.imageScale = event.scale;
  5659. // 根据缩放比例设置WaterFlow透明度
  5660. this.waterFlowOpacity = (this.waterFlowScale > 1) ? (this.waterFlowScale - 1) : (1 - this.waterFlowScale);
  5661. this.waterFlowOpacity *= 3;
  5662. if (!this.columnChanged) {
  5663. this.changeColumns(event.scale);
  5664. }
  5665. // 列数改变后的缩放比例调整:避免出现空白区域
  5666. if (this.columnChanged) {
  5667. this.waterFlowScale = this.imageScale * this.columns / this.oldColumn;
  5668. // 限制缩放范围,确保视觉效果自然
  5669. if (event.scale < 1) {
  5670. this.waterFlowScale = this.waterFlowScale > 1 ? this.waterFlowScale : 1;
  5671. } else {
  5672. this.waterFlowScale = this.waterFlowScale < 1 ? this.waterFlowScale : 1;
  5673. }
  5674. }
  5675. })
  5676. .onActionEnd((event: GestureEvent) => {
  5677. // 手势结束:执行归位动画并保存状态
  5678. // 执行归位动画:平滑过渡到正常状态
  5679. this.getUIContext()?.animateTo({ duration: 300 }, () => {
  5680. this.waterFlowScale = 1;
  5681. this.waterFlowOpacity = 1;
  5682. })
  5683. // 持久化保存当前列数:下次启动时恢复
  5684. PreferencesUtil.putSync('lastColumns', this.columns);
  5685. })
  5686. )
  5687. .onScrollFrameBegin((offset: number) => {
  5688. this.markGridWaterScrollingActive()
  5689. // 获取当前滚动偏移量
  5690. const currentOffsetY = this.waterScroller.currentOffset().yOffset;
  5691. this.tryTriggerLoadForWaterByOffset(currentOffsetY)
  5692. this.updateTitleBarByScrollOffset(currentOffsetY)
  5693. return { offsetRemain: offset };
  5694. })
  5695. }
  5696. }
  5697. .scrollBar(BarState.Off)
  5698. }
  5699. //瀑布流卡片布局
  5700. @Builder
  5701. private MusicWaterCardItem(item: VideoItem, index: number) {
  5702. Button({ type: ButtonType.Normal, stateEffect: false }) {
  5703. Stack() {
  5704. Column() {
  5705. Image(this.getGridWaterImageSource(item, index, true, this.coverThumbVersion))
  5706. .backgroundImageSize(ImageSize.Auto)
  5707. .borderRadius({
  5708. topLeft: 12,
  5709. topRight : 12,
  5710. bottomLeft: 0,
  5711. bottomRight: 0
  5712. })
  5713. .draggable(false)// 禁止长按手势拖动
  5714. .autoResize(true) // 重采样,可减少内存占用
  5715. .sourceSize({
  5716. width: this.getCoverThumbTargetSize(true),
  5717. height: this.getCoverThumbTargetSize(true)
  5718. })
  5719. .width('100%')
  5720. .height('auto')
  5721. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  5722. .objectFit(ImageFit.Cover)
  5723. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  5724. height: '99%' ,
  5725. dragBar: true,
  5726. onDisappear: () => {
  5727. this.longItemFilePath = '';
  5728. this.tempLyricContent = ''
  5729. },
  5730. showClose: true,
  5731. preferType: SheetType.CENTER ,
  5732. title: { title: '编辑标签' }
  5733. })
  5734. .draggable(false)
  5735. .opacity(this.opacityItem)// 绑定透明度
  5736. .margin({
  5737. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5738. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5739. })
  5740. Column() {
  5741. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  5742. .fontSize(this.columns == 4 ||this.columns==3? 12 : this.columns == 2 ? 15 : 18)
  5743. .maxLines(1)
  5744. .fontWeight(FontWeight.Bold)
  5745. .textOverflow({ overflow: this.isLongNameRoLL&&!this.isScrolling?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5746. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  5747. height: '95%',
  5748. dragBar: true,
  5749. showClose: true,
  5750. onDisappear: () => {
  5751. this.longItemFilePathDetail = '';
  5752. },
  5753. blurStyle:BlurStyle.Thin,
  5754. backgroundColor:Color.Transparent,
  5755. preferType: SheetType.CENTER ,
  5756. title: { title: '详情' }
  5757. })
  5758. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5759. $r('app.color.text_color'))
  5760. Column() {
  5761. Text(`${this.getArtistSongCount(item.name)}首`)
  5762. .fontSize(11)
  5763. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  5764. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5765. .fontColor($r('app.color.text_color'))
  5766. Text(`${this.getAlbumSongCount(item.name)}首`)
  5767. .fontSize(11)
  5768. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  5769. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5770. .fontColor($r('app.color.text_color'))
  5771. Row(){
  5772. Column(){
  5773. Text(item.md5Str?.includes('Lossless')?
  5774. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5775. .fontSize(this.columns == 4 ||this.columns==3? 8 : this.columns == 2 ? 9 : 11)
  5776. .padding({ top: 3,right:6,left:6,bottom:3 })
  5777. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5778. $r('app.color.text_color'))
  5779. .fontWeight(500)
  5780. .borderRadius(12)
  5781. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5782. .backgroundColor('#FFC107')
  5783. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  5784. }
  5785. .margin({ top: 2 ,right:6})
  5786. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  5787. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  5788. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  5789. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 13)
  5790. .maxLines(1)
  5791. .textOverflow({ overflow: TextOverflow.Ellipsis })//瀑布流固定省略
  5792. .margin({ top: 2})
  5793. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  5794. || item.type == CommonConstants.TYPE_IS_ALBUM
  5795. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5796. .fontWeight(FontWeight.Medium)
  5797. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5798. $r('app.color.text_color'))
  5799. }
  5800. }
  5801. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  5802. }
  5803. .height(this.columns == 4 ||this.columns==3? item.type==CommonConstants.TYPE_IS_DIR?30:40
  5804. : this.columns == 2 ? (item.type==CommonConstants.TYPE_IS_DIR?38:48) :
  5805. (item.type==CommonConstants.TYPE_IS_DIR?48:58))
  5806. .width('100%')
  5807. .justifyContent(FlexAlign.Center)
  5808. .margin({
  5809. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5810. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5811. })
  5812. }
  5813. .width('100%')
  5814. .borderRadius(12)
  5815. .backgroundColor($r('app.color.com_bg'))
  5816. Checkbox({ name: 'checkbox' + index })
  5817. .select(this.isLocalItemSelected(item))
  5818. .selectedColor(this.themeColor)
  5819. .shape(CheckBoxShape.CIRCLE)
  5820. .opacity(this.isMultiSelect && this.isSelectableLocalItem(item) ? 1 : 0)
  5821. .visibility(this.isMultiSelect && this.isSelectableLocalItem(item) ? Visibility.Visible :
  5822. Visibility.None)
  5823. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5824. .margin({ left: 20, top: 8, bottom: 8 })
  5825. .width(38)
  5826. .height(38)
  5827. }
  5828. }
  5829. .backgroundColor(Color.Transparent)
  5830. .width('100%')
  5831. .height('auto')
  5832. .padding({top:2})
  5833. .shadow({
  5834. radius: this.isScrolling ? 0 : 8,
  5835. type: ShadowType.BLUR,
  5836. color: 'on_primary'
  5837. })
  5838. .reuseId('card_item')
  5839. .onClick(() => {
  5840. if (this.isMultiSelect) {
  5841. if (this.isSelectableLocalItem(item)) {
  5842. const isChecked = this.isLocalItemSelected(item);
  5843. this.handleFileSelection(item, !isChecked);
  5844. }
  5845. return
  5846. }
  5847. this.doPlay(item, index)
  5848. })
  5849. }
  5850. // Grid布局的开始
  5851. private dragRefOffSetX: number = 0;
  5852. private dragRefOffSetY: number = 0;
  5853. private FIX_VP_X: number = 180;
  5854. private FIX_VP_Y: number = 84;
  5855. isDraggable(index: number): boolean {
  5856. return index >= 0;
  5857. }
  5858. getRowEnd(item: number) {
  5859. if (item.toString() === '0') {
  5860. return 1;
  5861. } else {
  5862. return 0;
  5863. }
  5864. }
  5865. isInLeft(index: number) {
  5866. return index % 2 == 0;
  5867. }
  5868. down(index: number): void {
  5869. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  5870. return;
  5871. }
  5872. this.offsetY -= this.FIX_VP_Y;
  5873. this.dragRefOffSetY += this.FIX_VP_Y;
  5874. this.itemMove(index, index + 1);
  5875. }
  5876. up(index: number): void {
  5877. if (!this.isDraggable(index - 2)) {
  5878. return;
  5879. }
  5880. this.offsetY += this.FIX_VP_Y;
  5881. this.dragRefOffSetY -= this.FIX_VP_Y;
  5882. this.itemMove(index, index - 1);
  5883. }
  5884. left(index: number): void {
  5885. if (this.isInLeft(index)) {
  5886. return;
  5887. }
  5888. if (!this.isDraggable(index - 1)) {
  5889. return;
  5890. }
  5891. this.offsetX += this.FIX_VP_X;
  5892. this.dragRefOffSetX -= this.FIX_VP_X;
  5893. this.itemMove(index, index - 1)
  5894. }
  5895. right(index: number): void {
  5896. if (!this.isInLeft(index)) {
  5897. return;
  5898. }
  5899. if (!this.isDraggable(index + 1)) {
  5900. return;
  5901. }
  5902. this.offsetX -= this.FIX_VP_X;
  5903. this.dragRefOffSetX += this.FIX_VP_X;
  5904. this.itemMove(index, index + 1)
  5905. }
  5906. private scroller: Scroller = new Scroller();
  5907. private waterScroller: Scroller = new Scroller();
  5908. private startIndex: number = 0
  5909. private endIndex: number = 0
  5910. @State scaleValue: number = 1
  5911. @State pinchValue: number = 1
  5912. layoutOptionsForHeader: GridLayoutOptions = {
  5913. regularSize: [1, 1], // 只支持[1, 1]
  5914. irregularIndexes: [0], // 索引为0的GridItem占用一行
  5915. };
  5916. @Builder
  5917. getGridView() {
  5918. Grid(this.scroller, this.layoutOptionsForHeader) {
  5919. GridItem() {
  5920. Column(){
  5921. Blank().height(this.topSafeHeight + 45)
  5922. }
  5923. }
  5924. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5925. GridItem() {
  5926. Stack() {
  5927. this.MusicItemGrid(item, index)
  5928. }
  5929. }
  5930. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  5931. {
  5932. preview: MenuPreviewMode.IMAGE
  5933. })
  5934. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  5935. {
  5936. preview: MenuPreviewMode.IMAGE
  5937. })
  5938. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.9, y: 0.9 }).animation({ duration: 300 }),
  5939. // TransitionEffect.scale({ x: 0, y: 0 })))
  5940. .clickEffect({ level: ClickEffectLevel.LIGHT })
  5941. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  5942. .zIndex(this.dragItem === index ? 1 : 0)
  5943. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  5944. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5945. }
  5946. .width('94%')
  5947. .height('100%')
  5948. .editMode(true)
  5949. .padding({bottom:this.bottomBarHeight+this.bottomSafeHeight+10})
  5950. .reuseId('grid_item')
  5951. .layoutWeight(1)
  5952. .scrollBar(BarState.Off)
  5953. .supportAnimation(false)
  5954. .onReachEnd(() => {
  5955. if(this.modeType === 4 )
  5956. return;
  5957. // 触底加载下一页
  5958. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  5959. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  5960. return;
  5961. }
  5962. if (this.hasMoreData && !this.isLoadingPage && !this.isPagingTransition) {
  5963. this.scheduleLoadNextPage();
  5964. }
  5965. })
  5966. .cachedCount(this.twoFingerType==1?1:this.twoFingerType==2?2:2)
  5967. .columnsTemplate(
  5968. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  5969. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  5970. )
  5971. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  5972. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  5973. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  5974. .gesture(PinchGesture({ fingers: 2 })
  5975. .onActionEnd((event: GestureEvent) => {
  5976. this.setGridTwoFingers()
  5977. })
  5978. .onActionUpdate(e => {
  5979. this.scaleValue = this.pinchValue * e.scale
  5980. })
  5981. .onActionStart(e => {
  5982. }))
  5983. .enableScrollInteraction(true)
  5984. .onScrollIndex((start: number, end: number) => {
  5985. this.startIndex = start
  5986. this.endIndex = end
  5987. this.gridVisibleStart = start
  5988. this.gridVisibleEnd = end
  5989. this.lastVisibleEndIndex = end
  5990. this.warmupGridWaterVisibleThumbs(start, end, false)
  5991. const now = Date.now()
  5992. const pagingDelta = this.gridScrollLastPagingEnd >= 0 ? Math.abs(end - this.gridScrollLastPagingEnd) : 999
  5993. if (pagingDelta >= 2 || now - this.gridScrollPagingCheckAt >= 40) {
  5994. this.gridScrollPagingCheckAt = now
  5995. this.gridScrollLastPagingEnd = end
  5996. this.tryTriggerLoadNextPageByScroll(end)
  5997. }
  5998. })
  5999. .onScrollFrameBegin((offset: number) => {
  6000. this.markGridWaterScrollingActive()
  6001. const currentOffsetY = this.scroller.currentOffset().yOffset;
  6002. this.updateTitleBarByScrollOffset(currentOffsetY)
  6003. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  6004. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  6005. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  6006. if (this.isScrollHide) {
  6007. this.setBarHeightHide2(offset)
  6008. } else {
  6009. this.setBarHeightNormal()
  6010. }
  6011. } else {
  6012. this.setBarHeightHide(offset)
  6013. }
  6014. return { offsetRemain: offset };
  6015. })
  6016. }
  6017. @State targetFile: string = '';
  6018. setGridTwoFingers() {
  6019. this.pinchValue = this.scaleValue;
  6020. Logger.info('this.pinchValue = ' + this.pinchValue);
  6021. if (this.pinchValue >= 1) {
  6022. this.twoFingerType++
  6023. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  6024. if(this.twoFingerType >= 4){
  6025. this.twoFingerType = 4//切换成瀑布流
  6026. this.columns = 4
  6027. }
  6028. } else {
  6029. this.twoFingerType--
  6030. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  6031. if (this.twoFingerType < 1) {
  6032. this.twoFingerType = 3
  6033. this.isGridMusic = false
  6034. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6035. }
  6036. }
  6037. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  6038. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6039. this.pinchValue = 1;
  6040. this.scaleValue = 1;
  6041. }
  6042. @State longItemFilePath: string = ''
  6043. @State tempLyricContent: string = ''
  6044. @State editingItem: VideoItem | null = null
  6045. @Builder
  6046. private MusicItemGrid(item: VideoItem, index: number) {
  6047. Button({ type: ButtonType.Normal, stateEffect: false }) {
  6048. Stack() {
  6049. Column() {
  6050. Image(this.getGridWaterImageSource(item, index, false, this.coverThumbVersion))
  6051. .height(this.getGridHeight())
  6052. .width(this.getGridWight())
  6053. .draggable(false)
  6054. .autoResize(true) // 重采样,可减少内存占用
  6055. .sourceSize({
  6056. width: this.getCoverThumbTargetSize(false),
  6057. height: this.getCoverThumbTargetSize(false)
  6058. })
  6059. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  6060. .clip(true)
  6061. .borderRadius({
  6062. topLeft: 12,
  6063. topRight: 12,
  6064. bottomLeft: 0,
  6065. bottomRight: 0
  6066. })
  6067. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  6068. height: '99%' ,
  6069. dragBar: true,
  6070. onDisappear: () => {
  6071. this.longItemFilePath = '';
  6072. this.tempLyricContent = ''
  6073. },
  6074. showClose: true,
  6075. preferType: SheetType.CENTER ,
  6076. title: { title: '编辑标签' }
  6077. })
  6078. .draggable(false)
  6079. .opacity(this.opacityItem)// 绑定透明度
  6080. .margin({
  6081. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  6082. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  6083. })
  6084. Column() {
  6085. Text(this.isShowFileName&&this.modeType !== 2&&this.modeType !== 3&&
  6086. item.type!=CommonConstants.TYPE_IS_DIR?item.fileName :item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  6087. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  6088. .maxLines(1)
  6089. .fontWeight(FontWeight.Bold)
  6090. .textOverflow({ overflow: this.isLongNameRoLL&&!this.isScrolling?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  6091. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  6092. height: '100%',
  6093. dragBar: true,
  6094. showClose: true,
  6095. onDisappear: () => {
  6096. this.longItemFilePathDetail = '';
  6097. },
  6098. blurStyle:BlurStyle.Thin,
  6099. backgroundColor:Color.Transparent,
  6100. preferType: SheetType.CENTER ,
  6101. title: { title: '详情' }
  6102. })
  6103. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6104. $r('app.color.text_color'))
  6105. Column() {
  6106. Text(`${this.getArtistSongCount(item.name)}首`)
  6107. .fontSize(11)
  6108. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  6109. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  6110. .fontColor($r('app.color.text_color'))
  6111. Text(`${this.getAlbumSongCount(item.name)}首`)
  6112. .fontSize(11)
  6113. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  6114. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  6115. .fontColor($r('app.color.text_color'))
  6116. Row(){
  6117. Column(){
  6118. Text(item.md5Str?.includes('Lossless')?
  6119. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  6120. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  6121. .padding({ top: 3,right:6,left:6,bottom:3 })
  6122. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6123. $r('app.color.text_color'))
  6124. .fontWeight(500)
  6125. .borderRadius(12)
  6126. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  6127. .backgroundColor('#FFC107')
  6128. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  6129. }
  6130. .margin({ top: 2 ,right:6})
  6131. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  6132. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  6133. Text(this.isShowFileName?item.duration:StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  6134. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  6135. .maxLines(1)
  6136. .textOverflow({ overflow: TextOverflow.Ellipsis })//Grid固定省略
  6137. .margin({ top: 2})
  6138. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  6139. || item.type == CommonConstants.TYPE_IS_ALBUM
  6140. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6141. .fontWeight(FontWeight.Medium)
  6142. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  6143. $r('app.color.text_color'))
  6144. }
  6145. }
  6146. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  6147. }
  6148. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  6149. .width(this.getGridWight())
  6150. .justifyContent(FlexAlign.Center)
  6151. .margin({
  6152. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  6153. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  6154. })
  6155. }
  6156. .width(this.getGridWight())
  6157. .borderRadius(12)
  6158. .backgroundColor($r('app.color.com_bg'))
  6159. Checkbox({ name: 'checkbox' + index })
  6160. .select(this.isLocalItemSelected(item))
  6161. .selectedColor(this.themeColor)
  6162. .shape(CheckBoxShape.CIRCLE)
  6163. .opacity(this.isMultiSelect && this.isSelectableLocalItem(item) ? 1 : 0)
  6164. .visibility(this.isMultiSelect && this.isSelectableLocalItem(item) ? Visibility.Visible :
  6165. Visibility.None)
  6166. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  6167. .margin({ left: 20, top: 8, bottom: 8 })
  6168. .width(38)
  6169. .height(38)
  6170. }
  6171. }
  6172. .backgroundColor(Color.Transparent)
  6173. .width('100%')
  6174. .padding({ top: 15 })
  6175. .height(this.getGridAllHeight())
  6176. .onClick(() => {
  6177. if (this.isMultiSelect) {
  6178. if (this.isSelectableLocalItem(item)) {
  6179. const isChecked = this.isLocalItemSelected(item);
  6180. this.handleFileSelection(item, !isChecked);
  6181. }
  6182. return
  6183. }
  6184. this.doPlay(item, index)
  6185. })
  6186. }
  6187. getGridAllHeight() {
  6188. let heightG = 222
  6189. switch (this.twoFingerType) {
  6190. case 1:
  6191. heightG = 143
  6192. break;
  6193. case 2:
  6194. heightG = 178
  6195. break;
  6196. case 3:
  6197. heightG = 222
  6198. break;
  6199. }
  6200. return heightG
  6201. }
  6202. getGridHeight() {
  6203. let heightG = 150
  6204. switch (this.twoFingerType) {
  6205. case 1:
  6206. heightG = 80
  6207. break;
  6208. case 2:
  6209. heightG = 110
  6210. break;
  6211. case 3:
  6212. heightG = 150
  6213. break;
  6214. }
  6215. return heightG
  6216. }
  6217. getGridWight() {
  6218. let wightG = 158
  6219. switch (this.twoFingerType) {
  6220. case 1:
  6221. wightG = 80
  6222. break;
  6223. case 2:
  6224. wightG = 110
  6225. break;
  6226. case 3:
  6227. wightG = 158
  6228. break;
  6229. }
  6230. return wightG
  6231. }
  6232. @State isShowDetail:boolean = false
  6233. @State longItemFilePathDetail:string =''
  6234. @Builder
  6235. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  6236. if(
  6237. ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  6238. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  6239. item.name === LocalMusic.STR_HISTORY_MUSIC)
  6240. ){
  6241. //如果是专辑和艺术家的首页,不能长按
  6242. //如果是我的收藏 最近播放等也不能长按
  6243. }else{
  6244. Scroll() {
  6245. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  6246. Menu() {
  6247. MenuItem({
  6248. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  6249. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  6250. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  6251. })
  6252. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6253. .onClick(() => {
  6254. if (item) {
  6255. this.doFav(item)
  6256. }
  6257. this.longItemFilePath = ''
  6258. })
  6259. MenuItem({
  6260. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  6261. content: '下一首播放'
  6262. })
  6263. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6264. .onClick(() => {
  6265. this.addToNextPlay(item);
  6266. this.longItemFilePath = ''
  6267. })
  6268. MenuItem({
  6269. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  6270. content: '添加到歌单'
  6271. })
  6272. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6273. .onClick(async () => {
  6274. this.longItemFilePath = ''
  6275. await this.openAddToPlaylistDialog(item)
  6276. })
  6277. MenuItem({
  6278. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  6279. content: '编辑标签'
  6280. })
  6281. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  6282. height: '99%',
  6283. dragBar: true,
  6284. showClose: true,
  6285. preferType: SheetType.CENTER ,
  6286. title: { title: '编辑标签' }
  6287. })
  6288. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6289. .onClick(async() => {
  6290. this.initEditFields(item)
  6291. this.tempLyricContent = await this.getLyricContent(item);
  6292. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  6293. this.lyricConStr = this.tempLyricContent
  6294. }
  6295. if(this.isGridMusic||this.twoFingerType==4){
  6296. this.longItemFilePath = item.filePath
  6297. }else{
  6298. this.isShowEdit = !this.isShowEdit;
  6299. }
  6300. })
  6301. MenuItem({
  6302. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  6303. content: $r('app.string.select_all')
  6304. })
  6305. .onClick(() => {
  6306. this.longItemFilePath = ''
  6307. this.enterLocalMultiSelect(item)
  6308. })
  6309. MenuItem({
  6310. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  6311. content: '提取ISO文件'
  6312. })
  6313. .visibility(this.isIsoLocalFile(item) ? Visibility.Visible : Visibility.None)
  6314. .onClick(async () => {
  6315. this.longItemFilePath = ''
  6316. await this.openIsoArchiveDialog(item)
  6317. })
  6318. MenuItem({
  6319. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.cut')),
  6320. content: $r('app.string.edit_audio')
  6321. })
  6322. .bindContentCover($$this.isEditAudio, this.EditAudioBuilder(item), {
  6323. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6324. })
  6325. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6326. .onClick(() => {
  6327. this.isEditAudio = !this.isEditAudio
  6328. })
  6329. MenuItem({
  6330. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  6331. content: $r('app.string.extract_accompaniment')
  6332. })
  6333. .bindContentCover($$this.isExtractAcc, this.ExtractAccBuilder(item), {
  6334. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6335. })
  6336. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6337. .onClick(() => {
  6338. if (!Utility.isNoble()) {
  6339. this.showVipDialog()
  6340. return
  6341. }
  6342. this.isExtractAcc = !this.isExtractAcc
  6343. })
  6344. MenuItem({
  6345. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.repeat')),
  6346. content: $r('app.string.converter_audio')
  6347. })
  6348. .bindContentCover($$this.isConverter, this.ConverterBuilder(item), {
  6349. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6350. })
  6351. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6352. .onClick(() => {
  6353. if (!Utility.isNoble()) {
  6354. this.showVipDialog()
  6355. return
  6356. }
  6357. this.isConverter = !this.isConverter
  6358. })
  6359. // MenuItem({
  6360. // symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.ai_edit')),
  6361. // content: $r('app.string.vocal_separation')
  6362. // })
  6363. // .bindContentCover($$this.isAIVoiceSeparation, this.AiBuilder(item), {
  6364. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6365. // })
  6366. // .onClick(() => {
  6367. // this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  6368. // })
  6369. MenuItem({
  6370. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_counterclockwise_clock')),
  6371. content: $r('app.string.change_tone')
  6372. })
  6373. .bindContentCover($$this.isChangeTone, this.ChangeToneBuilder(item), {
  6374. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6375. })
  6376. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6377. .onClick(() => {
  6378. this.isChangeTone = !this.isChangeTone
  6379. })
  6380. if(Utility.isVideoByExtension(item.filePath)){
  6381. MenuItem({
  6382. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.identify_song')),
  6383. content: $r('app.string.extract_audio')
  6384. })
  6385. .bindContentCover($$this.isExtractAudio, this.extractAudioFromVideoBuilder(item), {
  6386. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  6387. })
  6388. .onClick(() => {
  6389. this.isExtractAudio = !this.isExtractAudio
  6390. })
  6391. }
  6392. MenuItem({
  6393. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.phone')),
  6394. content: $r('app.string.set_ring')
  6395. })
  6396. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  6397. .onClick(async () => {
  6398. await PermissionUtil.activatePermission(item.filePath)
  6399. // if(item.filePath.includes(this.packName)){
  6400. setRingTone(this.context, item.filePath,item.name)
  6401. // }else{
  6402. // ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限设置铃声')
  6403. // }
  6404. this.longItemFilePath = ''
  6405. })
  6406. MenuItem({
  6407. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  6408. content: $r('app.string.rename')
  6409. })
  6410. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  6411. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  6412. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  6413. .onClick(() => {
  6414. this.showReNameDialog(item, index + '', filePath)
  6415. this.longItemFilePath = ''
  6416. })
  6417. MenuItem({
  6418. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  6419. content: $r('app.string.delete')
  6420. })
  6421. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  6422. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  6423. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  6424. .onClick(() => {
  6425. this.selectSingleItemForDelete(item)
  6426. this.showWarnIsDelete()
  6427. this.longItemFilePath = ''
  6428. })
  6429. MenuItem({
  6430. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  6431. content: $r('app.string.detail')
  6432. })
  6433. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  6434. height:'100%',
  6435. dragBar: true,
  6436. showClose: true,
  6437. blurStyle:BlurStyle.Thin,
  6438. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6439. backgroundColor:Color.Transparent,
  6440. title: { title: '详情信息' }
  6441. })
  6442. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6443. .onClick(() => {
  6444. if(this.isGridMusic||this.twoFingerType==4){
  6445. this.longItemFilePathDetail = item.filePath
  6446. }else{
  6447. this.isShowDetail = !this.isShowDetail
  6448. }
  6449. })
  6450. MenuItem({
  6451. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  6452. content: $r('app.string.share')
  6453. })
  6454. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6455. .onClick(() => {
  6456. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  6457. this.longItemFilePath = ''
  6458. })
  6459. }
  6460. .font({ size: 14, weight: FontWeight.Normal })
  6461. }
  6462. .width(180)
  6463. }
  6464. .height('auto')
  6465. .enableScrollInteraction(true)
  6466. .scrollBar(this.isGridMusic?BarState.On:BarState.Off)
  6467. }
  6468. }
  6469. private listMaxScrollOffsetY: number = 0
  6470. private selectedIndex: number = -1
  6471. setlistTwoFingers() {
  6472. this.pinchValue = this.scaleValue;
  6473. Logger.info('this.pinchValue = ' + this.pinchValue);
  6474. if (this.pinchValue >= 1) {
  6475. this.twoFingerType++
  6476. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  6477. if (this.twoFingerType > 3) {
  6478. this.twoFingerType = 1
  6479. this.isGridMusic = true
  6480. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6481. }
  6482. } else {
  6483. this.twoFingerType--
  6484. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  6485. if (this.twoFingerType < 1) {
  6486. this.twoFingerType = 4
  6487. this.columns = 1
  6488. }
  6489. }
  6490. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  6491. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6492. this.pinchValue = 1;
  6493. this.scaleValue = 1;
  6494. }
  6495. @Builder
  6496. getList(){
  6497. Stack() {
  6498. Refresh({ refreshing: $$this.isRefreshing, refreshingContent: this.contentNode }) {
  6499. this.getListView()
  6500. }
  6501. .pullDownRatio(this.ratioL)
  6502. .pullToRefresh(true)
  6503. .refreshOffset(0)
  6504. .onOffsetChange((offset: number) => {
  6505. // 越接近最大距离,下拉跟手系数越小。
  6506. this.ratioL = 1 - Math.pow((offset / this.maxRefreshingHeight), 3);
  6507. })
  6508. .onStateChange((refreshStatus: RefreshStatus) => {
  6509. console.info('onecold Refresh onStatueChange state is ' + refreshStatus);
  6510. })
  6511. .onRefreshing(async () => {
  6512. if(this.modeType==0){
  6513. this.getHistoryList(false)
  6514. this.asyncCurrentPathOnlyFile()
  6515. }else if(this.modeType == 1){
  6516. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6517. }else if(this.modeType == 2){
  6518. workerInstance.postMessage({ code: 3, data: this.context });
  6519. }else if(this.modeType == 3){
  6520. workerInstance.postMessage({ code: 4, data: this.context });
  6521. }else if(this.modeType == 4){
  6522. this.doSongListTask()
  6523. }
  6524. console.log('onRefreshing test');
  6525. })
  6526. if (this.isLoadingPage) {
  6527. Row() {
  6528. LoadingProgress()
  6529. .width(24)
  6530. .height(24)
  6531. .color(this.themeColor)
  6532. Text('加载中...')
  6533. .margin({ left: 8 })
  6534. .fontSize(13)
  6535. .fontColor($r('app.color.text_color'))
  6536. }
  6537. .padding({ left: 12, right: 12, top: 6, bottom: 6 })
  6538. .backgroundColor(this.isDarkMode ? '#66000000' : '#66FFFFFF')
  6539. .borderRadius(16)
  6540. .align(Alignment.Bottom)
  6541. .margin({ bottom: this.bottomBarHeight + this.bottomSafeHeight + 14 })
  6542. }
  6543. }
  6544. }
  6545. // 扫描当前目录下的文件,不扫描子目录
  6546. asyncCurrentPathOnlyFile(){
  6547. if(this.modeType==0){
  6548. const task = new taskpool.Task(scanCurrentDirectoryTask, getContext(this), this.currentPath,
  6549. this.lockPath,PreferencesUtil.getStringSync('COVER_API',''));
  6550. taskpool.execute(task, taskpool.Priority.HIGH).then(()=>{
  6551. if(this.modeType==0){
  6552. setTimeout(()=>{
  6553. this.isRefreshing =false
  6554. this.deleteCache(this.currentPath)
  6555. this.getSortedFiles(this.currentPath)
  6556. },500)
  6557. }
  6558. }).catch((e:object)=>{
  6559. this.isRefreshing =false
  6560. console.info("onecold task1 catch e: " + e);
  6561. })
  6562. }
  6563. }
  6564. @Builder
  6565. getListView() {
  6566. List({ scroller: this.listScroller }) {
  6567. // ListItemGroup({ header: this.coverHeader() }) {
  6568. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  6569. ListItem() {
  6570. Column() {
  6571. if (item.type === CommonConstants.TYPE_IS_DIR
  6572. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  6573. this.DirItem(item, index)
  6574. } else {
  6575. this.MusicItem(item, index)
  6576. }
  6577. }
  6578. }
  6579. .clickEffect({ level: ClickEffectLevel.LIGHT })
  6580. .swipeAction((
  6581. ((this.isSwipe && !this.isScrolling) &&
  6582. (this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack)))
  6583. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  6584. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath),
  6585. edgeEffect: SwipeEdgeEffect.None } : {}) //左滑
  6586. .onClick(() => {
  6587. if (this.isMultiSelect) {
  6588. if (this.isSelectableLocalItem(item)) {
  6589. const isChecked = this.isLocalItemSelected(item);
  6590. this.handleFileSelection(item, !isChecked);
  6591. }
  6592. return
  6593. }
  6594. this.doPlay(item, index)
  6595. })
  6596. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  6597. }
  6598. .onScrollStart(() => {
  6599. this.isScrolling = true
  6600. this.listVisibleStart = -1
  6601. this.listVisibleEnd = -1
  6602. this.listScrollAlphaCheckAt = 0
  6603. this.listScrollPagingCheckAt = 0
  6604. this.listScrollLastAlphaStart = -1
  6605. this.listScrollLastPagingEnd = -1
  6606. if (this.alphaBetRebuildTimer) {
  6607. clearTimeout(this.alphaBetRebuildTimer)
  6608. this.alphaBetRebuildTimer = 0
  6609. }
  6610. this.showAlphabetIndex()
  6611. })
  6612. .onScrollIndex((start: number,center:number,end:number) => {
  6613. this.selectedIndex = start
  6614. this.listVisibleStart = start
  6615. this.listVisibleEnd = end
  6616. this.lastVisibleEndIndex = end
  6617. if (!this.isMediaLibraryWarmupWindow()) {
  6618. this.warmupListVisibleThumbs(start, end)
  6619. }
  6620. const now = Date.now()
  6621. const alphaDelta = this.listScrollLastAlphaStart >= 0 ? Math.abs(start - this.listScrollLastAlphaStart) : 999
  6622. if (!this.isMediaLibraryWarmupWindow() &&
  6623. start >= 0 && start < this.videoLocalList.length &&
  6624. (alphaDelta >= 2 || now - this.listScrollAlphaCheckAt >= 48)) {
  6625. this.listScrollAlphaCheckAt = now
  6626. this.listScrollLastAlphaStart = start
  6627. const nextAlphaIndex = this.findAlphaBetIndex(this.videoLocalList[start])
  6628. if (nextAlphaIndex !== this.selectAlphaBetIndex) {
  6629. this.selectAlphaBetIndex = nextAlphaIndex
  6630. }
  6631. }
  6632. const pagingDelta = this.listScrollLastPagingEnd >= 0 ? Math.abs(end - this.listScrollLastPagingEnd) : 999
  6633. if (pagingDelta >= 2 || now - this.listScrollPagingCheckAt >= 32) {
  6634. this.listScrollPagingCheckAt = now
  6635. this.listScrollLastPagingEnd = end
  6636. this.tryTriggerLoadNextPageByScroll(end)
  6637. }
  6638. })
  6639. .onScrollStop(() => {
  6640. if(this.isScrolling){
  6641. this.isScrolling = false
  6642. }
  6643. this.flushPendingCoverThumbRefresh()
  6644. if (this.alphaBetDirty) {
  6645. this.scheduleAlphaBetRebuild(0)
  6646. }
  6647. this.hideAlphabetIndexAfterDelay(1500)
  6648. })
  6649. .onReachEnd(() => {
  6650. if(this.modeType === 4 )//歌单不能加载下一页
  6651. return;
  6652. // 触底加载下一页
  6653. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  6654. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  6655. return;
  6656. }
  6657. if (this.hasMoreData && !this.isLoadingPage && !this.isPagingTransition) {
  6658. this.scheduleLoadNextPage();
  6659. }
  6660. })
  6661. .scrollBar(BarState.Off)
  6662. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  6663. .gesture(PinchGesture({ fingers: 2 })
  6664. .onActionEnd((event: GestureEvent) => {
  6665. this.setlistTwoFingers()
  6666. })
  6667. .onActionUpdate(e => {
  6668. this.scaleValue = this.pinchValue * e.scale
  6669. })
  6670. .onActionStart(e => {
  6671. }))
  6672. .contentStartOffset(this.topSafeHeight + 55)
  6673. .scrollBar(BarState.Off)
  6674. .contentEndOffset(this.bottomBarHeight+this.bottomSafeHeight)
  6675. .cachedCount(this.modeType == 1 ? 4 : 8)
  6676. // .reuseId('list_item')
  6677. .borderRadius(20)
  6678. .layoutWeight(1)
  6679. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  6680. .lanes(
  6681. new BreakpointType<number>({
  6682. sm: 1,
  6683. md: 2,
  6684. lg: 2,
  6685. xl: 3,
  6686. xxl: 4
  6687. }).getValue(this.currentBreakpoint),
  6688. new BreakpointType<number>({
  6689. sm: 0,
  6690. md: 12,
  6691. lg: 12,
  6692. xl: 16,
  6693. xxl: 20
  6694. }).getValue(this.currentBreakpoint)
  6695. )
  6696. .onAreaChange((oldValue: Area, newValue: Area) => {
  6697. this.listArea = newValue
  6698. if (this.twoFingerType == 3) {
  6699. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  6700. } else if (this.twoFingerType == 2) {
  6701. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  6702. } else if (this.twoFingerType == 1) {
  6703. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  6704. }
  6705. })
  6706. .onScrollFrameBegin((offset: number) => {
  6707. const currentOffsetY = this.listScroller.currentOffset().yOffset;
  6708. this.updateTitleBarByScrollOffset(currentOffsetY)
  6709. return { offsetRemain: offset };
  6710. })
  6711. }
  6712. setBarHeightNormal() {
  6713. this.hideDone = false;
  6714. this.getUIContext().animateTo({
  6715. duration: 300
  6716. }, () => {
  6717. this.bottomBarHeight = 68 + 0;
  6718. this.topBarHeight = 50 + 0;
  6719. this.barOpacity = 1;
  6720. this.barBottomOpacity = 1
  6721. this.currentYOffset = 0;
  6722. this.isHiding = false;
  6723. });
  6724. }
  6725. setBarHeightHide(offset: number) {
  6726. if (offset > 0 && !this.hideDone) {
  6727. this.currentYOffset += offset;
  6728. if (this.currentYOffset <= 100) {
  6729. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  6730. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  6731. this.barOpacity = 1 - this.currentYOffset / 100;
  6732. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  6733. } else {
  6734. this.topBarHeight = 0;
  6735. this.bottomBarHeight = 0;
  6736. this.barBottomOpacity = 0
  6737. this.barOpacity = 0;
  6738. this.hideDone = true;
  6739. }
  6740. this.isHiding = true;
  6741. }
  6742. if (offset < 0 && this.isHiding) {
  6743. this.hideDone = false;
  6744. this.getUIContext().animateTo({
  6745. duration: 300
  6746. }, () => {
  6747. this.bottomBarHeight = 68 + 0;
  6748. this.topBarHeight = 50 + 0;
  6749. this.barOpacity = 1;
  6750. this.barBottomOpacity = 1
  6751. this.currentYOffset = 0;
  6752. this.isHiding = false;
  6753. });
  6754. }
  6755. }
  6756. //这个方法没隐藏bottomBar,只隐藏topbar
  6757. setBarHeightHide2(offset: number) {
  6758. if (offset > 0 && !this.hideDone) {
  6759. this.currentYOffset += offset;
  6760. if (this.currentYOffset <= 100) {
  6761. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  6762. this.barOpacity = 1 - this.currentYOffset / 100;
  6763. } else {
  6764. this.topBarHeight = 0;
  6765. this.barOpacity = 0;
  6766. this.hideDone = true;
  6767. }
  6768. this.isHiding = true;
  6769. }
  6770. if (offset < 0 && this.isHiding) {
  6771. this.hideDone = false;
  6772. this.getUIContext().animateTo({
  6773. duration: 300
  6774. }, () => {
  6775. this.topBarHeight = 50 + 0;
  6776. this.barOpacity = 1;
  6777. this.currentYOffset = 0;
  6778. this.isHiding = false;
  6779. });
  6780. }
  6781. }
  6782. private async doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean,isOpen?:boolean) {
  6783. Logger.info(`heanup doPlay被调用 - 歌曲: ${item.name}, 文件路径: ${item.filePath}, 索引: ${index}, 类型: ${item.type}, isFromSonPlayList: ${isFromSonPlayList}`)
  6784. switch (item.type) {
  6785. case CommonConstants.TYPE_IS_DIR:
  6786. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  6787. let shouldScrollTopNow = true
  6788. let offsetB = 0
  6789. if(this.twoFingerType==4){
  6790. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6791. let cur = this.waterScroller.currentOffset()
  6792. if (cur && typeof cur.yOffset === 'number') {
  6793. offsetB = cur.yOffset
  6794. }
  6795. }
  6796. this.mScrollMap.set('lastWaterDirScrollOffset', offsetB)
  6797. }else
  6798. if (this.isGridMusic) {
  6799. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6800. let cur = this.scroller.currentOffset()
  6801. if (cur && typeof cur.yOffset === 'number') {
  6802. offsetB = cur.yOffset
  6803. }
  6804. }
  6805. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  6806. } else {
  6807. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6808. let cur = this.listScroller.currentOffset()
  6809. if (cur && typeof cur.yOffset === 'number') {
  6810. offsetB = cur.yOffset
  6811. }
  6812. }
  6813. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  6814. }
  6815. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  6816. this.showVerifyDialog()
  6817. this.currentTitleName = '私密音频'
  6818. this.currentTitleCover = $r('app.media.alt')
  6819. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  6820. this.titleName = '最近播放'
  6821. this.currentTitleCover = $r('app.media.alt')
  6822. this.currentTitleName = '最近播放'
  6823. //加载动画效果
  6824. this.updateListData(this.historyList, true)
  6825. // this.videoLocalList = this.historyList
  6826. if (ArrayUtil.isEmpty(this.historyList)) {
  6827. ToastUtil.showToast('最近播放记录空空如也')
  6828. } else {
  6829. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  6830. }
  6831. this.isHistory = true
  6832. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  6833. this.titleName = '我的收藏'
  6834. this.currentTitleName = '我的收藏'
  6835. this.currentTitleCover = $r('app.media.alt')
  6836. //加载动画效果
  6837. this.updateListData(this.favList, true)
  6838. if (ArrayUtil.isEmpty(this.favList)) {
  6839. ToastUtil.showToast('无音乐收藏记录')
  6840. } else {
  6841. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  6842. }
  6843. this.isFavMusic = true
  6844. } else {
  6845. this.currentTitleName = item.name
  6846. this.currentPath = item.filePath
  6847. this.currentTitleCover = $r('app.media.alt')
  6848. shouldScrollTopNow = false
  6849. this.getSortedFiles(this.currentPath, false, undefined, undefined, undefined, true, true)
  6850. }
  6851. //进入歌单的时候的滚动位置在顶部
  6852. if (shouldScrollTopNow) {
  6853. if(this.twoFingerType==4){
  6854. setTimeout(() => {
  6855. this.waterScroller.scrollEdge(Edge.Top)
  6856. this.scroller.scrollEdge(Edge.Top)
  6857. }, 200)
  6858. }else{
  6859. if (this.isGridMusic) {
  6860. this.scroller.scrollToIndex(0,false)
  6861. }else{
  6862. this.listScroller.scrollToIndex(0,false)
  6863. }
  6864. }
  6865. }
  6866. this.rightTopImage = $r('sys.symbol.chevron_left')
  6867. break;
  6868. case CommonConstants.TYPE_IS_ARTIST:
  6869. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  6870. let offsetA = 0
  6871. if(this.twoFingerType==4){
  6872. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6873. let cur = this.waterScroller.currentOffset()
  6874. if (cur && typeof cur.yOffset === 'number') {
  6875. offsetA = cur.yOffset
  6876. }
  6877. }
  6878. this.mScrollMap.set('lastWaterArtistScrollOffset', offsetA)
  6879. }else
  6880. if (this.isGridMusic) {
  6881. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6882. let cur = this.scroller.currentOffset()
  6883. if (cur && typeof cur.yOffset === 'number') {
  6884. offsetA = cur.yOffset
  6885. }
  6886. }
  6887. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  6888. } else {
  6889. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6890. let cur = this.listScroller.currentOffset()
  6891. if (cur && typeof cur.yOffset === 'number') {
  6892. offsetA = cur.yOffset
  6893. }
  6894. }
  6895. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  6896. }
  6897. // 进入艺术家详情页前,先加载详情页的排序类型
  6898. // 注意:需要临时设置isCanBack=true,以便loadSortTypeForCurrentMode读取详情页的排序设置
  6899. const artistOriginalIsCanBack = this.isCanBack;
  6900. this.isCanBack = true;
  6901. const artistDetailSortType = this.loadSortTypeForCurrentMode();
  6902. this.isCanBack = artistOriginalIsCanBack; // 恢复原值
  6903. Logger.info('heanup LocalMusic', `进入艺术家详情页: 加载详情页排序 sortType=${artistDetailSortType}`);
  6904. // 缓存键需要包含排序类型,因为不同的排序类型会产生不同的数据
  6905. const artistCacheKey = `${item.name}_sort_${artistDetailSortType}`;
  6906. let mList = this.artistMap.get(artistCacheKey)
  6907. if (mList === undefined || ArrayUtil.isEmpty(mList)) {
  6908. // 使用详情页的排序类型查询
  6909. mList = await this.table.querySongsByArtist(item.name, artistDetailSortType, this.isShowFileName);
  6910. if (ArrayUtil.isNotEmpty(mList)) {
  6911. this.artistMap.set(artistCacheKey, mList);
  6912. }
  6913. }
  6914. // 设置当前排序类型为详情页排序
  6915. this.sortType = artistDetailSortType;
  6916. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  6917. // 注意:不再调用 Utility.doSortListAscending,因为数据已经按 artistDetailSortType 排序了
  6918. const nextArtistCountMap = new Map(this.artistSongCountMap);
  6919. nextArtistCountMap.set(item.name, mList.length);
  6920. this.artistSongCountMap = nextArtistCountMap;
  6921. this.isCanBack = true
  6922. this.hasMoreData = false
  6923. this.isLoadingPage = false
  6924. this.pageCache.clear()
  6925. this.pageHasMoreCache.clear()
  6926. this.pageTotalCountCache.clear()
  6927. this.prefetchingPages.clear()
  6928. this.lastScrollTriggerPage = -1
  6929. this.lastVisibleEndIndex = -1
  6930. this.isPagingTransition = false
  6931. if (this.pagingScheduleTimer) {
  6932. clearTimeout(this.pagingScheduleTimer)
  6933. this.pagingScheduleTimer = 0
  6934. }
  6935. this.totalCount = mList.length
  6936. this.titleName = item.name
  6937. this.currentTitleName = '艺术家:' + item.name
  6938. if (item.pixelMapPath) {
  6939. this.currentTitleCover = item.pixelMapPath
  6940. }
  6941. this.updateListData(mList, true, true) // 详情页立即替换列表,避免旧列表顶部闪现
  6942. } else {
  6943. ToastUtil.showToast('未找到该艺术家的歌曲');
  6944. return;
  6945. }
  6946. this.rightTopImage = $r('sys.symbol.chevron_left')
  6947. //进入歌单的时候的滚动位置在顶部
  6948. if(this.twoFingerType==4){
  6949. setTimeout(() => {
  6950. this.waterScroller.scrollEdge(Edge.Top)
  6951. this.scroller.scrollEdge(Edge.Top)
  6952. }, 380)
  6953. }else{
  6954. if (this.isGridMusic) {
  6955. this.scroller.scrollEdge(Edge.Top)
  6956. }else{
  6957. this.listScroller.scrollEdge(Edge.Top)
  6958. }
  6959. }
  6960. break;
  6961. case CommonConstants.TYPE_IS_ALBUM:
  6962. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  6963. let offset = 0
  6964. if(this.twoFingerType==4){
  6965. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6966. let cur = this.waterScroller.currentOffset()
  6967. if (cur && typeof cur.yOffset === 'number') {
  6968. offset = cur.yOffset
  6969. }
  6970. }
  6971. this.mScrollMap.set('lastWaterAlBumScrollOffset', offset)
  6972. }else
  6973. if (this.isGridMusic) {
  6974. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6975. let cur = this.scroller.currentOffset()
  6976. if (cur && typeof cur.yOffset === 'number') {
  6977. offset = cur.yOffset
  6978. }
  6979. }
  6980. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  6981. } else {
  6982. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6983. let cur = this.listScroller.currentOffset()
  6984. if (cur && typeof cur.yOffset === 'number') {
  6985. offset = cur.yOffset
  6986. }
  6987. }
  6988. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  6989. }
  6990. // 进入专辑详情页前,先加载详情页的排序类型
  6991. // 注意:需要临时设置isCanBack=true,以便loadSortTypeForCurrentMode读取详情页的排序设置
  6992. const albumOriginalIsCanBack = this.isCanBack;
  6993. this.isCanBack = true;
  6994. const albumDetailSortType = this.loadSortTypeForCurrentMode();
  6995. this.isCanBack = albumOriginalIsCanBack; // 恢复原值
  6996. Logger.info('heanup LocalMusic', `进入专辑详情页: 加载详情页排序 sortType=${albumDetailSortType}`);
  6997. // 缓存键需要包含排序类型,因为不同的排序类型会产生不同的数据
  6998. const albumCacheKey = `${item.name}_sort_${albumDetailSortType}`;
  6999. let albumList = this.albumMap.get(albumCacheKey)
  7000. if (albumList === undefined || ArrayUtil.isEmpty(albumList)) {
  7001. // 使用详情页的排序类型查询
  7002. albumList = await this.table.querySongsByAlbum(item.name, albumDetailSortType, this.isShowFileName);
  7003. if (ArrayUtil.isNotEmpty(albumList)) {
  7004. this.albumMap.set(albumCacheKey, albumList);
  7005. }
  7006. }
  7007. // 设置当前排序类型为详情页排序
  7008. this.sortType = albumDetailSortType;
  7009. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  7010. // 注意:不再调用 Utility.doSortListAscending,因为数据已经按 albumDetailSortType 排序了
  7011. const nextAlbumCountMap = new Map(this.albumSongCountMap);
  7012. nextAlbumCountMap.set(item.name, albumList.length);
  7013. this.albumSongCountMap = nextAlbumCountMap;
  7014. this.isCanBack = true
  7015. this.hasMoreData = false
  7016. this.isLoadingPage = false
  7017. this.pageCache.clear()
  7018. this.pageHasMoreCache.clear()
  7019. this.pageTotalCountCache.clear()
  7020. this.prefetchingPages.clear()
  7021. this.lastScrollTriggerPage = -1
  7022. this.lastVisibleEndIndex = -1
  7023. this.isPagingTransition = false
  7024. if (this.pagingScheduleTimer) {
  7025. clearTimeout(this.pagingScheduleTimer)
  7026. this.pagingScheduleTimer = 0
  7027. }
  7028. this.totalCount = albumList.length
  7029. this.titleName = item.name
  7030. this.currentTitleName = '专辑:' + item.name
  7031. if (item.pixelMapPath) {
  7032. this.currentTitleCover = item.pixelMapPath
  7033. }
  7034. this.updateListData(albumList, true, true) // 详情页立即替换列表,避免旧列表顶部闪现
  7035. this.mScrollMap.set(item.name, this.selectedIndex)
  7036. this.rightTopImage = $r('sys.symbol.chevron_left')
  7037. } else {
  7038. ToastUtil.showToast('未找到该专辑的歌曲');
  7039. return;
  7040. }
  7041. //进入歌单的时候的滚动位置在顶部
  7042. if(this.twoFingerType==4){
  7043. setTimeout(() => {
  7044. this.waterScroller.scrollEdge(Edge.Top)
  7045. this.scroller.scrollEdge(Edge.Top)
  7046. }, 380)
  7047. }else{
  7048. if (this.isGridMusic) {
  7049. this.scroller.scrollEdge(Edge.Top)
  7050. }else{
  7051. this.listScroller.scrollEdge(Edge.Top)
  7052. }
  7053. }
  7054. break;
  7055. case CommonConstants.TYPE_IS_CSJAD:
  7056. return
  7057. break;
  7058. case CommonConstants.TYPE_LOCAL:
  7059. if (this.isIsoLocalFile(item)) {
  7060. await this.openIsoArchiveDialog(item)
  7061. return
  7062. }
  7063. if(item&&item.filePath.toLowerCase().endsWith('.cue')){
  7064. const cueinfo:CueInfo = await parseCueFile(item.filePath)
  7065. const cueTracks:CueTrack[] = cueinfo.tracks
  7066. console.log('onecold cue cueTracks =', JSON.stringify(cueTracks));
  7067. if(ArrayUtil.isNotEmpty(cueTracks)){
  7068. this.showCueDialog(cueTracks,cueinfo)
  7069. }
  7070. // this.showCueSheet = !this.showCueSheet
  7071. return
  7072. }
  7073. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  7074. this.stop();
  7075. }
  7076. if (isOpen) {
  7077. this.currentSong = item
  7078. if (index !== undefined) {
  7079. this.curIndex = index
  7080. }
  7081. this.songList = []
  7082. this.songList.push(item)
  7083. this.sonDataSource.pushArrayData(this.songList)
  7084. this.playQueueScope = 'single'
  7085. }else if(isFromSonPlayList){ //点击来自右下角的播放列表
  7086. this.currentSong = item
  7087. if (index !== undefined) {
  7088. this.curIndex = index
  7089. }
  7090. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  7091. Logger.info(`heanup isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  7092. this.playQueueScope = 'playlist'
  7093. // 确保歌单路径列表已设置(从songList重新构建,以防被清空)
  7094. if (this.currentPlaylistSongFilePaths.length === 0 && this.songList.length > 0) {
  7095. this.currentPlaylistSongFilePaths = this.songList.map(song => song.filePath);
  7096. Logger.info(`heanup isFromSonPlayList - 重新构建歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  7097. }
  7098. }else {
  7099. const globalVideoList = this.buildPlayQueueFromView();
  7100. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  7101. if (this.curIndex < 0) {
  7102. globalVideoList.push(item);
  7103. this.curIndex = globalVideoList.length - 1;
  7104. }
  7105. this.songList = globalVideoList
  7106. this.sonDataSource.pushArrayData(this.songList)
  7107. this.currentSong = this.songList[this.curIndex]
  7108. // 只在非歌单模式下清空歌单路径列表
  7109. if (this.modeType !== 4) {
  7110. this.currentPlaylistSongFilePaths = [];
  7111. Logger.info(`heanup doPlay设置播放列表 - 总歌曲数: ${this.songList.length}, 当前索引: ${this.curIndex}, 当前歌曲: ${this.currentSong?.name}, 已清空歌单路径列表(modeType=${this.modeType})`)
  7112. } else {
  7113. // 歌单模式:确保歌单路径列表已设置
  7114. if (this.currentPlaylistSongFilePaths.length === 0 && this.songList.length > 0) {
  7115. this.currentPlaylistSongFilePaths = this.songList.map(song => song.filePath);
  7116. Logger.info(`heanup doPlay设置播放列表 - 从songList重新构建歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  7117. } else {
  7118. Logger.info(`heanup doPlay设置播放列表 - 歌单模式,保持歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  7119. }
  7120. }
  7121. }
  7122. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  7123. try {
  7124. const localUrl = await this.resolvePlaybackUrlForCurrentSong('doPlay-local');
  7125. this.videoUrl = localUrl || this.currentSong.filePath
  7126. } catch (error) {
  7127. Logger.error(TAG, `本地歌曲构建播放地址失败: ${(error as Error).message}`);
  7128. this.videoUrl = this.currentSong.filePath
  7129. }
  7130. this.name = this.currentSong.name
  7131. this.cover = this.currentSong.pixelMapPath
  7132. this.artist = this.currentSong.artist
  7133. LogUtil.info('onecold this.currentSong.cover =' + this.currentSong.pixelMapPath)
  7134. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  7135. this.startPlayOrResumePlay()
  7136. break;
  7137. case CommonConstants.TYPE_WEBDAV:
  7138. case CommonConstants.TYPE_SMB:
  7139. case CommonConstants.TYPE_NAVIDROME:
  7140. case CommonConstants.TYPE_FTP:
  7141. case CommonConstants.TYPE_BAIDU:
  7142. case CommonConstants.TYPE_JELLYFIN:
  7143. case CommonConstants.TYPE_EMBY:
  7144. case CommonConstants.TYPE_AUDIOSTATION:
  7145. case CommonConstants.TYPE_PLEX:
  7146. case CommonConstants.TYPE_DAOLIYU:
  7147. // 处理网络音频播放(WebDAV/SMB/Navidrome/Jellyfin/Emby/AudioStation/Plex/道理鱼/Baidu)
  7148. Logger.info(`heanup 处理云端音频播放: ${item.name}, URL: ${item.filePath}`)
  7149. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  7150. this.stop();
  7151. }
  7152. if (isOpen) {
  7153. this.currentSong = item
  7154. if (index !== undefined) {
  7155. this.curIndex = index
  7156. }
  7157. this.songList = []
  7158. this.songList.push(item)
  7159. this.sonDataSource.pushArrayData(this.songList)
  7160. } else if (isFromSonPlayList) {
  7161. // 点击来自右下角的播放列表
  7162. this.currentSong = item
  7163. if (index !== undefined) {
  7164. this.curIndex = index
  7165. }
  7166. // 设置播放队列作用域为歌单
  7167. this.playQueueScope = 'playlist'
  7168. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  7169. Logger.info(`heanup 网络音频 isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}, playQueueScope=${this.playQueueScope}`)
  7170. } else {
  7171. // 从全局网络音频列表中查找
  7172. let globalVideoList = this.videoLocalList.filter(video => isRemoteCloudType(video.type)) as VideoItem[];
  7173. this.curIndex = globalVideoList.findIndex(video => video.filePath === item.filePath);
  7174. if (this.curIndex === -1 && index !== undefined) {
  7175. this.curIndex = index;
  7176. }
  7177. this.songList = globalVideoList.length > 0 ? globalVideoList : [item];
  7178. this.currentSong = this.songList[this.curIndex];
  7179. this.sonDataSource.pushArrayData(this.songList)
  7180. }
  7181. await this.hydrateRemoteSongFromDb(this.currentSong);
  7182. await this.hydrateRemoteSongFromDb(this.currentSong);
  7183. AppStorage.setOrCreate('currentSong', this.currentSong);
  7184. const remotePlayLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  7185. const playbackUrl = await this.resolvePlaybackUrlForCurrentSong('doPlay-remote');
  7186. if (!playbackUrl) {
  7187. if (remotePlayLoading) {
  7188. this.hideLoadIng();
  7189. }
  7190. return;
  7191. }
  7192. this.videoUrl = playbackUrl;
  7193. Logger.info(TAG, `WebDAV URL同步构建完成(分支2): ${this.videoUrl}`);
  7194. this.name = this.currentSong.name
  7195. this.cover = this.currentSong.pixelMapPath
  7196. this.artist = this.currentSong.artist
  7197. Logger.info(`heanup 准备播放网络音频 - 歌名: ${this.name}, 艺术家: ${this.artist}, 完整URL: ${this.videoUrl}`)
  7198. this.startPlayOrResumePlay()
  7199. break;
  7200. }
  7201. }
  7202. private async openIsoArchiveDialog(item: VideoItem): Promise<void> {
  7203. if (!item || StrUtil.isEmpty(item.filePath)) {
  7204. Logger.error(TAG, `heanup ISO open dialog invalid path=${item ? item.filePath : ''}`)
  7205. ToastUtil.showToast('ISO 文件无效')
  7206. return
  7207. }
  7208. if (this.isIsoExtracting) {
  7209. if (ArrayUtil.isNotEmpty(this.isoAudioEntries)) {
  7210. if (this.isoSourceFilePath !== item.filePath) {
  7211. ToastUtil.showToast('当前有 ISO 提取任务正在后台执行,已打开提取进度窗口')
  7212. }
  7213. this.presentIsoArchiveDialog()
  7214. return
  7215. }
  7216. ToastUtil.showToast('当前有 ISO 提取任务正在后台执行')
  7217. return
  7218. }
  7219. Logger.info(TAG, `heanup ISO open dialog path=${item.filePath}, name=${item.fileName || item.name}`)
  7220. this.closeIsoDialog()
  7221. this.isoSourceFilePath = item.filePath
  7222. this.isoSourceFileName = item.fileName || item.name
  7223. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  7224. progress: 0,
  7225. backCancel: false,
  7226. autoCancel: false,
  7227. loadColor: this.themeColor,
  7228. fontColor: this.themeColor
  7229. })
  7230. try {
  7231. const task = new taskpool.Task(listIsoAudioEntriesTask, item.filePath)
  7232. const entries = await taskpool.execute(task, taskpool.Priority.HIGH) as IsoArchiveAudioEntry[]
  7233. this.isoAudioEntries = Array.isArray(entries) ? entries : []
  7234. Logger.info(TAG, `heanup ISO list entries done count=${this.isoAudioEntries.length}, path=${item.filePath}`)
  7235. if (ArrayUtil.isEmpty(this.isoAudioEntries)) {
  7236. Logger.error(TAG, `heanup ISO list entries empty path=${item.filePath}`)
  7237. ToastUtil.showToast('ISO 内未发现可提取的媒体文件')
  7238. this.closeIsoDialog()
  7239. return
  7240. }
  7241. this.selectedIsoAudioPaths = []
  7242. } catch (error) {
  7243. Logger.error(TAG, `heanup 解析 ISO 失败: ${(error as Error).message}`)
  7244. ToastUtil.showToast('解析 ISO 失败')
  7245. this.closeIsoDialog()
  7246. return
  7247. } finally {
  7248. if (this.loadingProgressDialogId) {
  7249. DialogHelper.closeDialog(this.loadingProgressDialogId)
  7250. this.loadingProgressDialogId = ''
  7251. }
  7252. }
  7253. this.presentIsoArchiveDialog()
  7254. }
  7255. private presentIsoArchiveDialog(): void {
  7256. if (this.isoComponentId > 0) {
  7257. return
  7258. }
  7259. this.getUIContext().getPromptAction().openCustomDialog({
  7260. builder: () => {
  7261. this.isoComptentBuilder()
  7262. },
  7263. isModal: true,
  7264. showInSubWindow: false,
  7265. maskColor: Color.Transparent,
  7266. dialogTransition: TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  7267. .animation({ duration: 600, curve: Curve.Smooth }),
  7268. maskTransition: TransitionEffect.opacity(0.5)
  7269. .animation({ duration: 600, curve: Curve.Smooth })
  7270. }).then((dialogId: number) => {
  7271. this.isoComponentId = dialogId
  7272. }).catch((error: BusinessError) => {
  7273. Logger.error(TAG, `heanup 打开 ISO 弹窗失败: ${error.message}`)
  7274. this.closeIsoDialog()
  7275. })
  7276. }
  7277. private toggleIsoEntrySelection(path: string, checked: boolean): void {
  7278. const selectedPathSet: Set<string> = new Set<string>(this.selectedIsoAudioPaths)
  7279. if (checked) {
  7280. selectedPathSet.add(path)
  7281. } else {
  7282. selectedPathSet.delete(path)
  7283. }
  7284. this.selectedIsoAudioPaths = this.isoAudioEntries
  7285. .filter((entry: IsoArchiveAudioEntry) => selectedPathSet.has(entry.path))
  7286. .map((entry: IsoArchiveAudioEntry) => entry.path)
  7287. Logger.info(TAG,
  7288. `heanup ISO toggle selection path=${path}, checked=${checked}, total=${this.selectedIsoAudioPaths.length}`)
  7289. }
  7290. private toggleIsoEntrySelectAll(): void {
  7291. if (this.selectedIsoAudioPaths.length === this.isoAudioEntries.length) {
  7292. this.selectedIsoAudioPaths = []
  7293. Logger.info(TAG, 'heanup ISO toggle select all cleared')
  7294. return
  7295. }
  7296. this.selectedIsoAudioPaths = this.isoAudioEntries.map((entry: IsoArchiveAudioEntry) => entry.path)
  7297. Logger.info(TAG, `heanup ISO toggle select all count=${this.selectedIsoAudioPaths.length}`)
  7298. }
  7299. private startIsoExtractProgressWatcher(entries: Array<IsoArchiveAudioEntry>, destinationDir: string): void {
  7300. this.stopIsoExtractProgressWatcher()
  7301. this.isoExtractExpectedOutputPaths = this.buildIsoExtractExpectedOutputPaths(entries, destinationDir)
  7302. this.isoExtractTotalBytes = entries.reduce((total: number, entry: IsoArchiveAudioEntry) => {
  7303. const size = entry && entry.size > 0 ? entry.size : 0
  7304. return total + size
  7305. }, 0)
  7306. this.isoExtractReceivedTaskProgress = false
  7307. this.isoExtractDisplayedProgress = 0
  7308. this.isoExtractLastActivityTime = Date.now()
  7309. if (this.isoExtractTotalBytes <= 0 || ArrayUtil.isEmpty(this.isoExtractExpectedOutputPaths)) {
  7310. return
  7311. }
  7312. this.isoExtractProgressTimer = setInterval(() => {
  7313. this.updateIsoExtractProgressFromFiles()
  7314. }, 500)
  7315. }
  7316. private stopIsoExtractProgressWatcher(): void {
  7317. if (this.isoExtractProgressTimer) {
  7318. clearInterval(this.isoExtractProgressTimer)
  7319. this.isoExtractProgressTimer = 0
  7320. }
  7321. this.isoExtractExpectedOutputPaths = []
  7322. this.isoExtractTotalBytes = 0
  7323. this.isoExtractReceivedTaskProgress = false
  7324. this.isoExtractLastActivityTime = 0
  7325. }
  7326. private markIsoExtractActivity(): void {
  7327. this.isoExtractLastActivityTime = Date.now()
  7328. }
  7329. private updateIsoExtractProgressFromFiles(): void {
  7330. if (this.isoExtractTotalBytes <= 0 || ArrayUtil.isEmpty(this.isoExtractExpectedOutputPaths) ||
  7331. this.isoExtractReceivedTaskProgress) {
  7332. return
  7333. }
  7334. let writtenBytes = 0
  7335. let existingCount = 0
  7336. for (let i = 0; i < this.isoExtractExpectedOutputPaths.length; i++) {
  7337. const outputPath = this.isoExtractExpectedOutputPaths[i]
  7338. if (!FileUtil.accessSync(outputPath)) {
  7339. continue
  7340. }
  7341. existingCount++
  7342. try {
  7343. const stat = fs.statSync(outputPath) as fs.Stat
  7344. if (typeof stat.size === 'number' && stat.size > 0) {
  7345. writtenBytes += stat.size
  7346. }
  7347. } catch (_error) {
  7348. }
  7349. }
  7350. let progress = 0
  7351. if (writtenBytes > 0) {
  7352. progress = Math.ceil((writtenBytes / this.isoExtractTotalBytes) * 100)
  7353. if (progress > 99) {
  7354. progress = 99
  7355. }
  7356. this.markIsoExtractActivity()
  7357. } else if (existingCount > 0) {
  7358. progress = 1
  7359. this.markIsoExtractActivity()
  7360. }
  7361. if (progress > 0) {
  7362. this.updateIsoExtractProgressState(progress,
  7363. `正在提取 ${progress}% (${existingCount}/${this.isoExtractExpectedOutputPaths.length})`)
  7364. return
  7365. }
  7366. if (this.isoExtractTask && this.isoExtractLastActivityTime > 0 &&
  7367. Date.now() - this.isoExtractLastActivityTime > this.isoExtractStallTimeoutMs) {
  7368. Logger.warn(TAG, `heanup ISO 提取进度长时间无变化: timeout=${this.isoExtractStallTimeoutMs}`)
  7369. this.markIsoExtractActivity()
  7370. this.updateIsoExtractProgressState(1, '准备提取 1%')
  7371. }
  7372. }
  7373. private updateIsoExtractProgressState(progress: number, message: string, currentName: string = '',
  7374. force: boolean = false): void {
  7375. let safeProgress = progress
  7376. if (safeProgress < 0) {
  7377. safeProgress = 0
  7378. }
  7379. if (safeProgress > 100) {
  7380. safeProgress = 100
  7381. }
  7382. if (!force && safeProgress < this.isoExtractDisplayedProgress) {
  7383. return
  7384. }
  7385. this.isoExtractDisplayedProgress = safeProgress
  7386. this.isoExtractProgress = safeProgress
  7387. this.isoExtractProgressText = message
  7388. if (force || StrUtil.isNotEmpty(currentName)) {
  7389. this.isoExtractCurrentEntryName = currentName
  7390. }
  7391. }
  7392. private resetIsoExtractProgressState(): void {
  7393. this.isoExtractProgress = 0
  7394. this.isoExtractProgressText = ''
  7395. this.isoExtractCurrentEntryName = ''
  7396. this.isoExtractDisplayedProgress = 0
  7397. }
  7398. private buildIsoExtractExpectedOutputPaths(entries: Array<IsoArchiveAudioEntry>, destinationDir: string): Array<string> {
  7399. const outputPaths: Array<string> = []
  7400. const occupiedPaths: Set<string> = new Set<string>()
  7401. for (let i = 0; i < entries.length; i++) {
  7402. const entry = entries[i]
  7403. const fileName = entry.name || this.getIsoLastPathSegment(entry.path)
  7404. const outputPath = this.buildIsoExpectedOutputPath(destinationDir, fileName, occupiedPaths)
  7405. occupiedPaths.add(outputPath)
  7406. outputPaths.push(outputPath)
  7407. }
  7408. return outputPaths
  7409. }
  7410. private buildIsoExpectedOutputPath(destinationDir: string, fileName: string, occupiedPaths: Set<string>): string {
  7411. const cleanName = this.sanitizeIsoOutputFileName(fileName)
  7412. const extension = this.getIsoOutputFileExtension(cleanName)
  7413. const baseName = extension.length > 0 ? cleanName.substring(0, cleanName.length - extension.length) : cleanName
  7414. let candidatePath = `${this.trimIsoOutputTrailingSeparator(destinationDir)}/${cleanName}`
  7415. let suffix = 0
  7416. while (occupiedPaths.has(candidatePath) || FileUtil.accessSync(candidatePath)) {
  7417. suffix++
  7418. candidatePath = `${this.trimIsoOutputTrailingSeparator(destinationDir)}/${baseName} (${suffix})${extension}`
  7419. }
  7420. return candidatePath
  7421. }
  7422. private sanitizeIsoOutputFileName(fileName: string): string {
  7423. const lastSegment = this.getIsoLastPathSegment(fileName)
  7424. let sanitized = ''
  7425. for (let i = 0; i < lastSegment.length; i++) {
  7426. const char = lastSegment[i]
  7427. if (char === '/' || char === '\\' || char === ':' || char === '*' || char === '?' || char === '"' ||
  7428. char === '<' || char === '>' || char === '|') {
  7429. sanitized += '_'
  7430. } else {
  7431. sanitized += char
  7432. }
  7433. }
  7434. if (sanitized.trim().length === 0) {
  7435. return 'iso_audio.bin'
  7436. }
  7437. return sanitized
  7438. }
  7439. private getIsoLastPathSegment(path: string): string {
  7440. const normalizedPath = path.replace(/\\/g, '/')
  7441. const lastSeparator = normalizedPath.lastIndexOf('/')
  7442. if (lastSeparator < 0) {
  7443. return normalizedPath
  7444. }
  7445. return normalizedPath.substring(lastSeparator + 1)
  7446. }
  7447. private getIsoOutputFileExtension(fileName: string): string {
  7448. const lastDot = fileName.lastIndexOf('.')
  7449. if (lastDot < 0) {
  7450. return ''
  7451. }
  7452. return fileName.substring(lastDot)
  7453. }
  7454. private trimIsoOutputTrailingSeparator(path: string): string {
  7455. if (path.endsWith('/')) {
  7456. return path.substring(0, path.length - 1)
  7457. }
  7458. return path
  7459. }
  7460. private cancelIsoExtraction(reason?: string): void {
  7461. const currentTask = this.isoExtractTask
  7462. Logger.info(TAG,
  7463. `heanup ISO cancel request reason=${reason || ''}, hasTask=${currentTask ? 'true' : 'false'}`)
  7464. this.isoExtractCanceled = true
  7465. this.isoExtractCancelMessage = reason ? reason : ''
  7466. this.isoExtractTask = undefined
  7467. this.updateIsoExtractProgressState(this.isoExtractProgress, '正在停止提取...', this.isoExtractCurrentEntryName, true)
  7468. if (currentTask) {
  7469. try {
  7470. taskpool.terminateTask(currentTask)
  7471. } catch (error) {
  7472. Logger.error(TAG, `heanup 终止 ISO 提取任务失败: ${(error as Error).message}`)
  7473. }
  7474. }
  7475. }
  7476. private moveIsoExtractionToBackground(): void {
  7477. this.closeIsoDialog(false)
  7478. ToastUtil.showToast('ISO 提取已转入后台')
  7479. }
  7480. private async extractSelectedIsoAudioFiles(): Promise<void> {
  7481. if (this.isIsoExtracting) {
  7482. return
  7483. }
  7484. if (ArrayUtil.isEmpty(this.selectedIsoAudioPaths)) {
  7485. ToastUtil.showToast('请先选择要提取的文件')
  7486. return
  7487. }
  7488. const selectedPathSet: Set<string> = new Set<string>(this.selectedIsoAudioPaths)
  7489. const selectedEntries = this.isoAudioEntries
  7490. .filter((entry: IsoArchiveAudioEntry) => selectedPathSet.has(entry.path))
  7491. if (ArrayUtil.isEmpty(selectedEntries)) {
  7492. ToastUtil.showToast('未找到要提取的文件')
  7493. return
  7494. }
  7495. const hasSacdTrack: boolean = selectedEntries.some((entry: IsoArchiveAudioEntry) => entry.entryType === 'sacd_track')
  7496. const destinationDir: string = this.currentPath
  7497. this.isIsoExtracting = true
  7498. this.isoExtractCanceled = false
  7499. this.isoExtractCancelMessage = ''
  7500. this.isoExtractDestinationDir = destinationDir
  7501. Logger.info(TAG,
  7502. `heanup ISO extract start file=${this.isoSourceFilePath}, selected=${selectedEntries.length}, ` +
  7503. `hasSacd=${hasSacdTrack}, destinationDir=${destinationDir}`)
  7504. Logger.info(TAG,
  7505. `heanup ISO selected entries: ${selectedEntries.map((entry: IsoArchiveAudioEntry) => entry.path).join(', ')}`)
  7506. this.resetIsoExtractProgressState()
  7507. this.updateIsoExtractProgressState(1, '准备提取 1%', '', true)
  7508. this.startIsoExtractProgressWatcher(selectedEntries, destinationDir)
  7509. try {
  7510. const extractStartedAt = Date.now()
  7511. const outputPaths: string[] = this.buildIsoExtractExpectedOutputPaths(selectedEntries, destinationDir)
  7512. const payloadJson = JSON.stringify({
  7513. isoPath: this.isoSourceFilePath,
  7514. destinationDir,
  7515. entries: selectedEntries,
  7516. outputPaths
  7517. })
  7518. const task = new taskpool.Task(extractIsoAudioEntriesTask, payloadJson)
  7519. this.isoExtractTask = task
  7520. task.onReceiveData((progressData: IsoExtractProgressMessage) => {
  7521. this.markIsoExtractActivity()
  7522. const progress = typeof progressData.progress === 'number' ? Math.floor(progressData.progress) : 0
  7523. Logger.info(TAG,
  7524. `heanup ISO task receive stage=${progressData.stage || ''}, progress=${progress}, name=${progressData.name || ''}`)
  7525. if (progress > 1 && !this.isoExtractReceivedTaskProgress) {
  7526. this.isoExtractReceivedTaskProgress = true
  7527. if (this.isoExtractProgressTimer) {
  7528. clearInterval(this.isoExtractProgressTimer)
  7529. this.isoExtractProgressTimer = 0
  7530. }
  7531. Logger.info(TAG, `heanup ISO 提取切换为任务进度: progress=${progress}, stage=${progressData.stage || ''}`)
  7532. }
  7533. const stageText = progressData.stage === 'prepare' ? '准备提取' :
  7534. (progressData.stage === 'done' ? '提取完成' : (progressData.stage === 'error' ? '提取异常' : '正在提取'))
  7535. if (progress > this.isoExtractDisplayedProgress || progressData.stage !== 'extract') {
  7536. Logger.info(TAG,
  7537. `heanup ISO 提取任务进度: stage=${progressData.stage || ''}, progress=${progress}, ` +
  7538. `name=${progressData.name || ''}`)
  7539. }
  7540. this.updateIsoExtractProgressState(progress, `${stageText} ${progress}%`, progressData.name || '')
  7541. })
  7542. const result = await taskpool.execute(task, taskpool.Priority.HIGH) as IsoExtractTaskResult
  7543. const extractElapsedMs = Date.now() - extractStartedAt
  7544. this.isoExtractTask = undefined
  7545. Logger.info(TAG, `heanup ISO extract task completed canceled=${this.isoExtractCanceled}, elapsedMs=${extractElapsedMs}`)
  7546. if (this.isoExtractCanceled) {
  7547. return
  7548. }
  7549. const extractedPaths = result?.extractedPaths || []
  7550. const failedEntries = result?.failedEntries || []
  7551. const failureDetails = result?.failureDetails || []
  7552. Logger.info(TAG,
  7553. `heanup ISO extract result extracted=${extractedPaths.length}, failed=${failedEntries.length}, details=${failureDetails.length}`)
  7554. let importErrorMessage: string = ''
  7555. let importedCount: number = 0
  7556. if (ArrayUtil.isNotEmpty(extractedPaths)) {
  7557. const importStartedAt = Date.now()
  7558. try {
  7559. await this.postProcessExtractedIsoFiles(extractedPaths, selectedEntries, outputPaths)
  7560. importedCount = await this.importExtractedFilesToDirectory(extractedPaths, destinationDir)
  7561. Logger.info(TAG,
  7562. `heanup ISO import extracted files success elapsedMs=${Date.now() - importStartedAt}, ` +
  7563. `importedCount=${importedCount}`)
  7564. } catch (importError) {
  7565. importErrorMessage = (importError as Error).message || '导入媒体库失败'
  7566. Logger.error(TAG,
  7567. `heanup ISO import extracted files failed elapsedMs=${Date.now() - importStartedAt}, ` +
  7568. `message=${importErrorMessage}`)
  7569. }
  7570. }
  7571. if (extractedPaths.length > 0 && failedEntries.length > 0) {
  7572. if (StrUtil.isNotEmpty(importErrorMessage)) {
  7573. ToastUtil.showToast(`提取完成,成功 ${extractedPaths.length} 个,失败 ${failedEntries.length} 个,导入失败`)
  7574. } else if (importedCount > 0) {
  7575. ToastUtil.showToast(`提取完成,成功 ${extractedPaths.length} 个,失败 ${failedEntries.length} 个,已入库 ${importedCount} 个音频文件`)
  7576. } else {
  7577. ToastUtil.showToast(`提取完成,成功 ${extractedPaths.length} 个,失败 ${failedEntries.length} 个`)
  7578. }
  7579. } else if (extractedPaths.length > 0) {
  7580. if (StrUtil.isNotEmpty(importErrorMessage)) {
  7581. ToastUtil.showToast(`提取完成,但导入媒体库失败: ${importErrorMessage}`)
  7582. } else if (importedCount > 0) {
  7583. ToastUtil.showToast(`提取完成,已提取 ${extractedPaths.length} 个文件,入库 ${importedCount} 个音频文件`)
  7584. } else {
  7585. ToastUtil.showToast(`提取完成,已提取 ${extractedPaths.length} 个文件`)
  7586. }
  7587. } else if (ArrayUtil.isNotEmpty(failureDetails)) {
  7588. const firstFailure: IsoExtractFailureDetail = failureDetails[0]
  7589. const reasonText = firstFailure.reason && firstFailure.reason.length > 0 ? firstFailure.reason : '提取失败'
  7590. ToastUtil.showToast(reasonText)
  7591. } else if (hasSacdTrack) {
  7592. ToastUtil.showToast('SACD ISO 轨道提取失败')
  7593. } else {
  7594. ToastUtil.showToast('提取失败')
  7595. }
  7596. } catch (error) {
  7597. this.isoExtractTask = undefined
  7598. if (this.isoExtractCanceled) {
  7599. return
  7600. }
  7601. Logger.error(TAG, `heanup 提取 ISO 文件失败: ${(error as Error).message}`)
  7602. ToastUtil.showToast('提取 ISO 文件失败')
  7603. } finally {
  7604. const shouldResetDialogState: boolean = this.isoComponentId <= 0
  7605. this.stopIsoExtractProgressWatcher()
  7606. this.isoExtractTask = undefined
  7607. this.isIsoExtracting = false
  7608. Logger.info(TAG,
  7609. `heanup ISO extract finally canceled=${this.isoExtractCanceled}, cancelMessage=${this.isoExtractCancelMessage}`)
  7610. if (this.isoExtractCanceled && this.isoExtractCancelMessage.length > 0) {
  7611. ToastUtil.showToast(this.isoExtractCancelMessage)
  7612. }
  7613. this.isoExtractCanceled = false
  7614. this.isoExtractCancelMessage = ''
  7615. if (shouldResetDialogState) {
  7616. this.resetIsoDialogState()
  7617. } else {
  7618. this.selectedIsoAudioPaths = []
  7619. this.resetIsoExtractProgressState()
  7620. }
  7621. }
  7622. }
  7623. private async postProcessExtractedIsoFiles(extractedPaths: Array<string>, selectedEntries: Array<IsoArchiveAudioEntry>,
  7624. outputPaths: Array<string>): Promise<void> {
  7625. if (ArrayUtil.isEmpty(extractedPaths) || ArrayUtil.isEmpty(selectedEntries) || ArrayUtil.isEmpty(outputPaths)) {
  7626. return
  7627. }
  7628. const entryByOutputPath: Map<string, IsoArchiveAudioEntry> = new Map<string, IsoArchiveAudioEntry>()
  7629. for (let i = 0; i < outputPaths.length && i < selectedEntries.length; i++) {
  7630. entryByOutputPath.set(outputPaths[i], selectedEntries[i])
  7631. }
  7632. for (let i = 0; i < extractedPaths.length; i++) {
  7633. const extractedPath = extractedPaths[i]
  7634. const entry = entryByOutputPath.get(extractedPath)
  7635. if (!entry) {
  7636. continue
  7637. }
  7638. await this.postProcessExtractedIsoEntry(extractedPath, entry)
  7639. }
  7640. }
  7641. private async postProcessExtractedIsoEntry(filePath: string, entry: IsoArchiveAudioEntry): Promise<void> {
  7642. if (!Utility.isMusicByExtension(filePath)) {
  7643. return
  7644. }
  7645. const hasEmbeddedMetadata: boolean = StrUtil.isNotEmpty(entry.title) || StrUtil.isNotEmpty(entry.album) ||
  7646. StrUtil.isNotEmpty(entry.artist) || StrUtil.isNotEmpty(entry.albumArtist) || StrUtil.isNotEmpty(entry.comment) ||
  7647. !!(entry.trackNumber && entry.trackNumber > 0)
  7648. if (entry.entryType !== 'sacd_track' && !hasEmbeddedMetadata) {
  7649. return
  7650. }
  7651. const tags: FFMpegTags = this.buildIsoExtractedMetadata(entry)
  7652. if (Object.keys(tags).length > 0) {
  7653. try {
  7654. const metadataResult = await repairAudioMetadata(filePath, '', tags, true, '')
  7655. Logger.info(TAG,
  7656. `heanup ISO metadata post-process path=${filePath}, success=${metadataResult}, type=${entry.entryType || ''}`)
  7657. } catch (error) {
  7658. Logger.error(TAG, `heanup ISO metadata post-process failed path=${filePath}, message=${(error as Error).message}`)
  7659. }
  7660. }
  7661. if (!filePath.toLowerCase().endsWith('.dsf')) {
  7662. return
  7663. }
  7664. const coverUrl = await this.resolveIsoExtractCoverUrl(entry)
  7665. if (StrUtil.isEmpty(coverUrl)) {
  7666. return
  7667. }
  7668. try {
  7669. const coverResult = await changeMusicCover(this.context, filePath, coverUrl, true, '')
  7670. Logger.info(TAG, `heanup ISO cover post-process path=${filePath}, success=${coverResult}`)
  7671. } catch (error) {
  7672. Logger.error(TAG, `heanup ISO cover post-process failed path=${filePath}, message=${(error as Error).message}`)
  7673. }
  7674. }
  7675. private buildIsoExtractedMetadata(entry: IsoArchiveAudioEntry): FFMpegTags {
  7676. const metadata: FFMpegTags = {}
  7677. const title = entry.title || this.getIsoEntryBaseName(entry.name || entry.path)
  7678. if (StrUtil.isNotEmpty(title)) {
  7679. metadata.title = title
  7680. metadata.TITLE = title
  7681. }
  7682. if (StrUtil.isNotEmpty(entry.artist)) {
  7683. metadata.artist = entry.artist
  7684. metadata.ARTIST = entry.artist
  7685. }
  7686. if (StrUtil.isNotEmpty(entry.album)) {
  7687. metadata.album = entry.album
  7688. metadata.ALBUM = entry.album
  7689. }
  7690. if (entry.trackNumber && entry.trackNumber > 0) {
  7691. metadata.track = `${entry.trackNumber}`
  7692. metadata.TRACK = `${entry.trackNumber}`
  7693. }
  7694. if (StrUtil.isNotEmpty(entry.albumArtist)) {
  7695. metadata.ALBUMARTIST = entry.albumArtist
  7696. metadata.album_artist = entry.albumArtist
  7697. metadata.TPE2 = entry.albumArtist
  7698. }
  7699. if (StrUtil.isNotEmpty(entry.comment)) {
  7700. metadata.comment = entry.comment
  7701. metadata.COMMENT = entry.comment
  7702. metadata.COMM = entry.comment
  7703. }
  7704. return metadata
  7705. }
  7706. private getIsoEntryBaseName(fileName: string): string {
  7707. const lastSegment = this.getIsoLastPathSegment(fileName)
  7708. const lastDot = lastSegment.lastIndexOf('.')
  7709. if (lastDot <= 0) {
  7710. return lastSegment
  7711. }
  7712. return lastSegment.substring(0, lastDot)
  7713. }
  7714. private async resolveIsoExtractCoverUrl(entry: IsoArchiveAudioEntry): Promise<string> {
  7715. const title = entry.title || this.getIsoEntryBaseName(entry.name || entry.path)
  7716. const artist = entry.artist || entry.albumArtist || ''
  7717. if (StrUtil.isEmpty(title) || PreferencesUtil.getStringSync('COVER_API', '') === '') {
  7718. return ''
  7719. }
  7720. try {
  7721. const coverUrl = await NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', ''))
  7722. if (StrUtil.isNotEmpty(coverUrl) && coverUrl !== 'unknown') {
  7723. return coverUrl
  7724. }
  7725. } catch (error) {
  7726. Logger.error(TAG,
  7727. `heanup ISO resolve cover failed title=${title}, artist=${artist}, message=${(error as Error).message}`)
  7728. }
  7729. return ''
  7730. }
  7731. private async importExtractedFilesToDirectory(paths: Array<string>, destinationDir: string): Promise<number> {
  7732. if (ArrayUtil.isEmpty(paths)) {
  7733. return 0
  7734. }
  7735. let importedCount: number = 0
  7736. for (let i = 0; i < paths.length; i++) {
  7737. const filePath = paths[i]
  7738. if (destinationDir === this.lockPath || !Utility.isMeidaByExtension(filePath) ||
  7739. filePath.endsWith('.lrc') || filePath.endsWith('.srt') || Utility.isIsoByExtension(filePath)) {
  7740. continue
  7741. }
  7742. const mediaItem = await Utility.uriGetMusicAssetsFromFile(this.context, filePath,
  7743. CommonConstants.TYPE_LOCAL, this.autoParseMusicName)
  7744. await new Promise<void>((resolve) => {
  7745. this.table.insert(mediaItem, (_id: number) => resolve())
  7746. })
  7747. importedCount++
  7748. }
  7749. this.cache.delete(destinationDir)
  7750. if (this.currentPath === destinationDir) {
  7751. this.pageCache.clear()
  7752. this.pageHasMoreCache.clear()
  7753. this.pageTotalCountCache.clear()
  7754. if (destinationDir === this.lockPath) {
  7755. this.getSortedFiles(destinationDir, true)
  7756. } else {
  7757. await this.resetAndLoadFirstPage()
  7758. }
  7759. }
  7760. return importedCount
  7761. }
  7762. private resetIsoDialogState(): void {
  7763. this.isoAudioEntries = []
  7764. this.selectedIsoAudioPaths = []
  7765. this.isoSourceFileName = ''
  7766. this.isoSourceFilePath = ''
  7767. this.isoExtractDestinationDir = ''
  7768. this.isIsoExtracting = false
  7769. this.stopIsoExtractProgressWatcher()
  7770. this.isoExtractTask = undefined
  7771. this.resetIsoExtractProgressState()
  7772. }
  7773. private closeIsoDialog(reset: boolean = true): void {
  7774. if (this.isoComponentId > 0) {
  7775. try {
  7776. this.getUIContext().getPromptAction().closeCustomDialog(this.isoComponentId)
  7777. } catch (_error) {
  7778. }
  7779. this.isoComponentId = 0
  7780. }
  7781. if (!reset) {
  7782. return
  7783. }
  7784. this.resetIsoDialogState()
  7785. }
  7786. @Builder
  7787. isoComptentBuilder() {
  7788. IsoExtractComptent({
  7789. isoFileName: this.isoSourceFileName,
  7790. entries: this.isoAudioEntries,
  7791. selectedPaths: this.selectedIsoAudioPaths,
  7792. isLongNameRoLL: this.isLongNameRoLL,
  7793. isExtracting: this.isIsoExtracting,
  7794. extractProgress: this.isoExtractProgress,
  7795. extractProgressText: this.isoExtractProgressText,
  7796. extractCurrentName: this.isoExtractCurrentEntryName,
  7797. onToggleSelection: (path: string, checked: boolean) => {
  7798. this.toggleIsoEntrySelection(path, checked)
  7799. },
  7800. onToggleSelectAll: () => {
  7801. this.toggleIsoEntrySelectAll()
  7802. },
  7803. onExtract: async () => {
  7804. await this.extractSelectedIsoAudioFiles()
  7805. },
  7806. onRunInBackground: () => {
  7807. this.moveIsoExtractionToBackground()
  7808. },
  7809. onStopExtract: () => {
  7810. this.cancelIsoExtraction('已取消 ISO 提取')
  7811. },
  7812. onCancel: () => {
  7813. if (this.isIsoExtracting) {
  7814. this.moveIsoExtractionToBackground()
  7815. return
  7816. }
  7817. this.closeIsoDialog()
  7818. }
  7819. })
  7820. }
  7821. private cueComponentId: number = 0
  7822. private async handleCueTrackImport(cueinfo: CueInfo): Promise<void> {
  7823. try {
  7824. let sourceItem = Utility.getItemByFilePath(this.videoLocalList, cueinfo.filePath);
  7825. if (!sourceItem) {
  7826. sourceItem = await this.table.queryVideoByFilePath(cueinfo.filePath) || undefined;
  7827. }
  7828. const importedItems = await importCueTracks(this.context, this.table, cueinfo, sourceItem);
  7829. if (ArrayUtil.isEmpty(importedItems)) {
  7830. ToastUtil.showToast('未导入到任何分轨');
  7831. return;
  7832. }
  7833. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId);
  7834. await this.resetAndLoadFirstPage();
  7835. ToastUtil.showToast(`分轨完成,已入库 ${importedItems.length} 首`);
  7836. } catch (error) {
  7837. Logger.error(TAG, `CUE 分轨入库失败: ${(error as Error).message}`);
  7838. ToastUtil.showToast('分轨失败');
  7839. }
  7840. }
  7841. //显示cue分轨列表对话框
  7842. showCueDialog(cueTracks:CueTrack[],cueinfo:CueInfo){
  7843. this.getUIContext().getPromptAction().openCustomDialog({
  7844. builder: () => {
  7845. this.cueComptentBuilder(cueTracks,cueinfo)
  7846. },
  7847. isModal:true,
  7848. showInSubWindow:false,
  7849. maskColor: Color.Transparent,
  7850. dialogTransition: // 设置弹窗内容显示的过渡效果
  7851. TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  7852. .animation({ duration: 600, curve: Curve.Smooth }),
  7853. maskTransition: // 设置蒙层显示的过渡效果
  7854. TransitionEffect.opacity(0.5)
  7855. .animation({ duration: 600, curve: Curve.Smooth })
  7856. }).then((dialogId: number) => {
  7857. this.cueComponentId = dialogId
  7858. })
  7859. .catch((error: BusinessError) => {
  7860. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  7861. })
  7862. }
  7863. @Builder
  7864. cueComptentBuilder(cueTracks:CueTrack[]=[],cueinfo:CueInfo){
  7865. CueComptent({
  7866. title:cueinfo.title,
  7867. cueTracks:cueTracks,
  7868. isLongNameRoLL:this.isLongNameRoLL,
  7869. onCancel:()=>{
  7870. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId)
  7871. },
  7872. onSplitTracks: async ()=>{
  7873. await this.handleCueTrackImport(cueinfo)
  7874. },
  7875. onDoItemClick: async (item: CueTrack, index: number)=>{
  7876. //获取cueinfo对应的filePath
  7877. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  7878. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, cueinfo.filePath)
  7879. this.currentSong = Utility.getItemByFilePath(globalVideoList, cueinfo.filePath)
  7880. console.info('onecold cueinfo.filePath=', cueinfo.filePath)
  7881. console.info('onecold this.currentSong =', JSON.stringify(this.currentSong))
  7882. if (this.currentSong){
  7883. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  7884. this.stop();//播放之前先停止之前播放。
  7885. }
  7886. this.songList = globalVideoList
  7887. this.sonDataSource.pushArrayData(this.songList)
  7888. if (this.currentSong) {
  7889. try {
  7890. const cueUrl = await this.resolvePlaybackUrlForCurrentSong('cue-track-play');
  7891. if (!cueUrl) {
  7892. return;
  7893. }
  7894. this.videoUrl = cueUrl;
  7895. } catch (error) {
  7896. Logger.error(TAG, `CUE 点播构建播放地址失败: ${(error as Error).message}`);
  7897. this.videoUrl = this.currentSong.filePath;
  7898. }
  7899. }
  7900. this.name = item.title||this.currentSong.name
  7901. this.cover = this.currentSong.pixelMapPath
  7902. this.artist = item.performer||this.currentSong.artist
  7903. this.currentSong.name = this.name
  7904. this.currentSong.artist = this.artist
  7905. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  7906. this.startPlayOrResumePlay(item.startOffset)//从cue的某个位置开始播放
  7907. }
  7908. }
  7909. })
  7910. }
  7911. @State isFrontWhite: boolean = false
  7912. private showCoverScaleGuideIfNeeded(): void {
  7913. const hasShown = PreferencesUtil.getBooleanSync(PREF_PLAY_COVER_SCALE_GUIDE_SHOWN, false)
  7914. if (hasShown) {
  7915. return
  7916. }
  7917. this.isShowCoverScaleGuide = true
  7918. setTimeout(() => {
  7919. if (this.isShowCoverScaleGuide) {
  7920. this.dismissCoverScaleGuide()
  7921. }
  7922. }, 9000)
  7923. }
  7924. private dismissCoverScaleGuide(): void {
  7925. this.isShowCoverScaleGuide = false
  7926. PreferencesUtil.put(PREF_PLAY_COVER_SCALE_GUIDE_SHOWN, true)
  7927. }
  7928. setShowPlayTrue(){
  7929. this.getUIContext()?.animateTo({
  7930. duration: 500,
  7931. curve: Curve.Friction
  7932. }, () => {
  7933. this.isShowPlay = true;
  7934. this.showCoverScaleGuideIfNeeded()
  7935. });
  7936. }
  7937. setShowPlayFalse(){
  7938. this.getUIContext()?.animateTo({
  7939. duration: 500,
  7940. curve: Curve.Friction
  7941. }, () => {
  7942. this.isShowPlay = false;
  7943. });
  7944. this.isShowCoverScaleGuide = false
  7945. }
  7946. //打开播放页
  7947. showPlayerView() {
  7948. this.showCoverScaleGuideIfNeeded()
  7949. console.info('onecold showPlayerView this.songList'+ JSON.stringify(this.songList))
  7950. if (ArrayUtil.isNotEmpty(this.songList)) {
  7951. // this.setShowPlayTrue()
  7952. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
  7953. this.initLyric(lyricPath);
  7954. this.startAutoHide();
  7955. } else {
  7956. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  7957. }
  7958. }
  7959. //打开播放列表
  7960. openPlayList(){
  7961. if (ArrayUtil.isNotEmpty(this.songList)) {
  7962. this.isShowSheet = !this.isShowSheet;
  7963. this.isFrontWhite = false
  7964. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  7965. this.scrollIndex()
  7966. // 只有在播放本地音乐时才自动加载完整列表
  7967. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_LOCAL) {
  7968. void this.hydrateFullMediaPlayListIfNeeded();
  7969. }
  7970. } else {
  7971. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  7972. }
  7973. }
  7974. scrollIndex(){
  7975. try {
  7976. setTimeout(() => {
  7977. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  7978. if(this.curIndex>60){
  7979. this.playListScroller.scrollToIndex(this.curIndex,false, ScrollAlign.CENTER)
  7980. }else{
  7981. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  7982. }
  7983. })
  7984. }, 123)
  7985. }catch (error) {
  7986. console.error(`onecold scrollIndex出错: ${error}`);
  7987. }
  7988. }
  7989. scrollIndexMain(dialogId?:string){
  7990. try {
  7991. setTimeout(() => {
  7992. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  7993. console.info('heanup scrollIndexMain this.curIndex='+this.curIndex)
  7994. if(dialogId)
  7995. DialogHelper.closeDialog(dialogId)
  7996. let isAni:boolean = false
  7997. if(this.curIndex<50){
  7998. isAni = true
  7999. }
  8000. if(this.twoFingerType==4){
  8001. this.waterScroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  8002. }else{
  8003. if(this.isGridMusic){
  8004. this.scroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  8005. }else{
  8006. this.listScroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  8007. }
  8008. }
  8009. })
  8010. }, 123)
  8011. }catch (error) {
  8012. console.error(`onecold scrollIndexMain出错: ${error}`);
  8013. }
  8014. }
  8015. // 智能定位当前播放歌曲,如果当前页没有则加载完整列表
  8016. async locateCurrentSong(): Promise<void> {
  8017. if (!this.currentSong) {
  8018. console.warn("heanup locateCurrentSong: 当前没有播放的歌曲");
  8019. return;
  8020. }
  8021. // 检查当前播放歌曲是否在已加载的列表中
  8022. const targetIndex = Utility.getIndexFromList(this.videoLocalList, this.currentSong.filePath);
  8023. if (targetIndex > 0) {
  8024. // 歌曲在当前列表中,直接滚动
  8025. console.info("heanup locateCurrentSong: 找到歌曲,索引=" + targetIndex);
  8026. this.curIndex = targetIndex;
  8027. this.scrollIndexMain();
  8028. } else {
  8029. // 歌曲不在当前列表中,加载当前歌曲再第几页完整列表后再定位
  8030. console.info("heanup locateCurrentSong: 歌曲不在当前列表,开始加载完整列表");
  8031. const dialogID = DialogHelper.showLoadingDialog()
  8032. await this.hydrateFullMediaPlayListIfNeeded(false);
  8033. this.curIndex = Utility.getIndexFromList(this.videoLocalList, this.currentSong.filePath);
  8034. this.scrollIndexMain(dialogID);
  8035. }
  8036. }
  8037. //播放列表布局
  8038. @Builder
  8039. PlayListSheet() {
  8040. Column() {
  8041. this.PlayList()
  8042. }
  8043. .width('100%')
  8044. .height('100%')
  8045. }
  8046. @State titleStr: string = ''
  8047. @State ablumStr: string = ''
  8048. @State artistStr: string = ''
  8049. @State lyricConStr: string = ''
  8050. @State currentEditItem: string = ''
  8051. @State yearStr: string = ''
  8052. @State trackStr: string = ''
  8053. @State genreStr: string = ''
  8054. @State imagePathStr: string = ''
  8055. @State albumArtistStr: string = ''
  8056. @State composerStr: string = ''
  8057. @State lyricistStr: string = ''
  8058. @State commentStr: string = ''
  8059. @State discStr: string = ''
  8060. doUpdateData() {
  8061. setTimeout(async () => {
  8062. if (this.modeType === 0) {
  8063. this.deleteCache(this.currentPath)
  8064. await this.resetAndLoadFirstPage();
  8065. }else if (this.modeType === 1){
  8066. await this.resetAndLoadFirstPage();
  8067. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  8068. }
  8069. }, 500)
  8070. }
  8071. doAllUpdateData() {
  8072. setTimeout(async () => {
  8073. if (this.modeType === 0) {
  8074. this.deleteCache(this.currentPath)
  8075. await this.resetAndLoadFirstPage();
  8076. }else{
  8077. await this.resetAndLoadFirstPage();
  8078. }
  8079. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  8080. workerInstance.postMessage({ code: 3, data: this.context });
  8081. workerInstance.postMessage({ code: 4, data: this.context });
  8082. }, 999)
  8083. }
  8084. private delayMs(ms: number): Promise<void> {
  8085. return new Promise(resolve => {
  8086. setTimeout(() => resolve(), ms);
  8087. });
  8088. }
  8089. private async appendItemsSmoothly(items: VideoItem[]): Promise<void> {
  8090. if (!items || items.length === 0) {
  8091. return;
  8092. }
  8093. const isMediaLibraryListMode = this.isMediaLibraryListMode();
  8094. const isHeavyGridWaterMode = this.isGridMusic || this.twoFingerType == 4;
  8095. const directAppendThreshold = isHeavyGridWaterMode ? 8 : (isMediaLibraryListMode ? 6 : 12);
  8096. if (!this.isScrolling || items.length <= directAppendThreshold) {
  8097. this.videoLocalList.push(...items);
  8098. this.dataSource.appendArrayData(items);
  8099. return;
  8100. }
  8101. const chunkSize = isHeavyGridWaterMode
  8102. ? Math.max(3, Math.min(6, Math.floor(this.pageSize * 0.15)))
  8103. : (isMediaLibraryListMode
  8104. ? Math.max(2, Math.min(4, Math.floor(this.pageSize * 0.08)))
  8105. : Math.max(4, Math.min(8, Math.floor(this.pageSize * 0.18))));
  8106. const chunkDelay = isHeavyGridWaterMode ? 12 : (isMediaLibraryListMode ? 10 : 8);
  8107. for (let index = 0; index < items.length; index += chunkSize) {
  8108. const chunk = items.slice(index, Math.min(index + chunkSize, items.length));
  8109. this.videoLocalList.push(...chunk);
  8110. this.dataSource.appendArrayData(chunk);
  8111. if (index + chunkSize < items.length) {
  8112. await this.delayMs(chunkDelay);
  8113. }
  8114. }
  8115. }
  8116. /**
  8117. * 加载指定页的数据
  8118. */
  8119. private async loadPage(pageIndex: number, append: boolean = true): Promise<void> {
  8120. try {
  8121. // 1. 检查缓存
  8122. if (this.pageCache.has(pageIndex)) {
  8123. Logger.info('heanup LocalMusic', `loadPage: 从缓存加载 page=${pageIndex}`);
  8124. const inMediaLibraryWarmup = this.modeType === 1 && pageIndex === 0 && !append && this.isMediaLibraryWarmupWindow();
  8125. const cachedData = this.pageCache.get(pageIndex)!;
  8126. const cachedHasMore = this.pageHasMoreCache.get(pageIndex);
  8127. const cachedTotal = this.pageTotalCountCache.get(pageIndex);
  8128. if (cachedHasMore !== undefined) {
  8129. this.hasMoreData = cachedHasMore;
  8130. }
  8131. if (cachedTotal !== undefined) {
  8132. this.totalCount = cachedTotal;
  8133. if (this.modeType === 1) {
  8134. this.mediaKuCount = cachedTotal;
  8135. }
  8136. }
  8137. if (append) {
  8138. this.prefetchListThumbsFromItems(cachedData, 26);
  8139. this.prefetchGridWaterThumbsFromItems(cachedData, this.twoFingerType == 4 ? 56 : 42);
  8140. await this.appendItemsSmoothly(cachedData);
  8141. } else {
  8142. this.videoLocalList = cachedData;
  8143. this.dataSource.pushArrayData(this.videoLocalList);
  8144. if (inMediaLibraryWarmup) {
  8145. this.prefetchListThumbsFromItems(cachedData, 8);
  8146. } else {
  8147. this.prefetchListThumbsFromItems(cachedData, 30);
  8148. this.prefetchGridWaterThumbsFromItems(cachedData, this.twoFingerType == 4 ? 56 : 42);
  8149. }
  8150. }
  8151. this.setButtonStatus();
  8152. if (inMediaLibraryWarmup) {
  8153. this.scheduleAlphaBetRebuild(900);
  8154. } else {
  8155. this.markAlphaBetDirty();
  8156. }
  8157. if (this.hasMoreData) {
  8158. if (inMediaLibraryWarmup) {
  8159. if (this.mediaLibraryWarmupPrefetchTimer) {
  8160. clearTimeout(this.mediaLibraryWarmupPrefetchTimer);
  8161. }
  8162. this.mediaLibraryWarmupPrefetchTimer = setTimeout(() => {
  8163. this.mediaLibraryWarmupPrefetchTimer = 0;
  8164. if (this.modeType === 1 && !this.isCanBack) {
  8165. this.prefetchFollowingPages(pageIndex + 1);
  8166. }
  8167. }, 900) as number;
  8168. } else {
  8169. this.prefetchFollowingPages(pageIndex + 1);
  8170. }
  8171. }
  8172. return;
  8173. }
  8174. this.isLoadingPage = true;
  8175. Logger.info('heanup LocalMusic', `loadPage: 开始加载 page=${pageIndex}, size=${this.pageSize}, mode=${this.modeType}`);
  8176. // 2. 构造查询参数
  8177. const options: PageQueryOptions = {
  8178. pageIndex: pageIndex,
  8179. pageSize: this.pageSize,
  8180. sortType: this.sortType,
  8181. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  8182. isShowFileName: this.isShowFileName
  8183. };
  8184. // 根据 modeType 补充查询条件
  8185. if (this.modeType === 0) {
  8186. options.parentPath = this.currentPath;
  8187. }
  8188. // 3. 执行查询
  8189. let result: PageQueryResult = { items: [], totalCount: 0, hasMore: false };
  8190. switch (this.modeType) {
  8191. case 0:
  8192. result = await this.table.queryByParentPathPaged(options);
  8193. result.items = this.filterOutLocalIsoItems(result.items);
  8194. // modeType=0时,第一页需要添加文件夹列表
  8195. if (pageIndex === 0 && !this.isSearchMode) {
  8196. const directories: VideoItem[] = await this.loadDirectories(this.currentPath);
  8197. const isoItems: VideoItem[] = this.getLocalIsoItems(this.currentPath);
  8198. result.items = [...directories, ...isoItems, ...result.items];
  8199. result.totalCount += directories.length + isoItems.length;
  8200. }
  8201. break;
  8202. case 1:
  8203. result = await this.table.queryMediaLibraryPaged(options);
  8204. break;
  8205. case 2:
  8206. result = await this.table.queryArtistsPaged(options);
  8207. break;
  8208. case 3:
  8209. result = await this.table.queryAlbumsPaged(options);
  8210. break;
  8211. default:
  8212. result = await this.table.queryMediaLibraryPaged(options);
  8213. break;
  8214. }
  8215. if (!result || result.items.length === 0) {
  8216. Logger.info('heanup LocalMusic', 'loadPage: 查询结果为空');
  8217. this.isLoadingPage = false;
  8218. this.hasMoreData = false;
  8219. // 仅首页为空时清空,后续页为空只终止继续分页
  8220. if (pageIndex === 0) {
  8221. this.totalCount = 0;
  8222. this.videoLocalList = [];
  8223. this.dataSource.pushArrayData(this.videoLocalList);
  8224. this.setButtonStatus();
  8225. this.markAlphaBetDirty();
  8226. }
  8227. return;
  8228. }
  8229. // 4. 更新状态和缓存
  8230. this.totalCount = result.totalCount;
  8231. this.hasMoreData = result.hasMore;
  8232. if (this.modeType === 1) {
  8233. this.mediaKuCount = result.totalCount;
  8234. }
  8235. if (this.modeType === 2 && result.countMap) {
  8236. this.mergeArtistCountMap(result.countMap);
  8237. } else if (this.modeType === 3 && result.countMap) {
  8238. this.mergeAlbumCountMap(result.countMap);
  8239. }
  8240. Logger.info('heanup LocalMusic', `loadPage: 查询完成 items=${result.items.length}, total=${result.totalCount}, hasMore=${result.hasMore}`);
  8241. // 缓存管理 - 只保留最近3页
  8242. this.pageCache.set(pageIndex, result.items);
  8243. this.pageHasMoreCache.set(pageIndex, result.hasMore);
  8244. this.pageTotalCountCache.set(pageIndex, result.totalCount);
  8245. this.cleanOldCache(pageIndex);
  8246. // 5. 更新显示列表
  8247. const inMediaLibraryWarmup = this.modeType === 1 && pageIndex === 0 && !append && this.isMediaLibraryWarmupWindow();
  8248. if (append) {
  8249. this.prefetchListThumbsFromItems(result.items, 26);
  8250. this.prefetchGridWaterThumbsFromItems(result.items, this.twoFingerType == 4 ? 56 : 42);
  8251. await this.appendItemsSmoothly(result.items);
  8252. } else {
  8253. this.videoLocalList = result.items;
  8254. this.dataSource.pushArrayData(this.videoLocalList);
  8255. if (inMediaLibraryWarmup) {
  8256. this.prefetchListThumbsFromItems(result.items, 8);
  8257. } else {
  8258. this.prefetchListThumbsFromItems(result.items, 30);
  8259. this.prefetchGridWaterThumbsFromItems(result.items, this.twoFingerType == 4 ? 56 : 42);
  8260. }
  8261. }
  8262. this.setButtonStatus();
  8263. if (inMediaLibraryWarmup) {
  8264. this.scheduleAlphaBetRebuild(900);
  8265. } else {
  8266. this.markAlphaBetDirty();
  8267. }
  8268. if (inMediaLibraryWarmup) {
  8269. if (this.mediaLibraryWarmupPrefetchTimer) {
  8270. clearTimeout(this.mediaLibraryWarmupPrefetchTimer);
  8271. }
  8272. this.mediaLibraryWarmupPrefetchTimer = setTimeout(() => {
  8273. this.mediaLibraryWarmupPrefetchTimer = 0;
  8274. if (this.modeType === 1 && !this.isCanBack) {
  8275. this.prefetchFollowingPages(pageIndex + 1);
  8276. }
  8277. }, 900) as number;
  8278. } else {
  8279. this.prefetchFollowingPages(pageIndex + 1);
  8280. }
  8281. this.isLoadingPage = false;
  8282. } catch (err) {
  8283. const error = err as Error;
  8284. Logger.error('heanup LocalMusic', `loadPage error: ${error.message}`);
  8285. // ToastUtil.showToast('加载数据失败');
  8286. this.isLoadingPage = false;
  8287. this.hasMoreData = false;
  8288. }
  8289. }
  8290. /**
  8291. * 清理旧缓存 - 只保留当前页前后各1页
  8292. */
  8293. private cleanOldCache(currentPage: number): void {
  8294. const pagesToKeep = new Set([currentPage - 1, currentPage, currentPage + 1]);
  8295. const keysToDelete: number[] = [];
  8296. this.pageCache.forEach((_, page) => {
  8297. if (!pagesToKeep.has(page)) {
  8298. keysToDelete.push(page);
  8299. }
  8300. });
  8301. keysToDelete.forEach(page => {
  8302. this.pageCache.delete(page);
  8303. this.pageHasMoreCache.delete(page);
  8304. this.pageTotalCountCache.delete(page);
  8305. });
  8306. if (keysToDelete.length > 0) {
  8307. Logger.info('heanup LocalMusic', `cleanOldCache: 清理了 ${keysToDelete.length} 页缓存`);
  8308. }
  8309. }
  8310. private async prefetchNextPage(nextPage: number): Promise<void> {
  8311. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  8312. return;
  8313. }
  8314. if (!this.hasMoreData || this.pageCache.has(nextPage) || this.prefetchingPages.has(nextPage)) {
  8315. return;
  8316. }
  8317. const expectedModeType = this.modeType;
  8318. const expectedSortType = this.sortType;
  8319. const expectedIsShowFileName = this.isShowFileName;
  8320. const expectedSearchKeyword = this.isSearchMode ? this.searchText : '';
  8321. const expectedParentPath = this.currentPath;
  8322. this.prefetchingPages.add(nextPage);
  8323. try {
  8324. const options: PageQueryOptions = {
  8325. pageIndex: nextPage,
  8326. pageSize: this.pageSize,
  8327. sortType: this.sortType,
  8328. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  8329. isShowFileName: this.isShowFileName
  8330. };
  8331. if (this.modeType === 0) {
  8332. options.parentPath = this.currentPath;
  8333. }
  8334. let result: PageQueryResult = { items: [], totalCount: 0, hasMore: false };
  8335. switch (this.modeType) {
  8336. case 0:
  8337. result = await this.table.queryByParentPathPaged(options);
  8338. result.items = this.filterOutLocalIsoItems(result.items);
  8339. break;
  8340. case 1:
  8341. result = await this.table.queryMediaLibraryPaged(options);
  8342. break;
  8343. case 2:
  8344. result = await this.table.queryArtistsPaged(options);
  8345. if (result.countMap) {
  8346. this.mergeArtistCountMap(result.countMap);
  8347. }
  8348. break;
  8349. case 3:
  8350. result = await this.table.queryAlbumsPaged(options);
  8351. if (result.countMap) {
  8352. this.mergeAlbumCountMap(result.countMap);
  8353. }
  8354. break;
  8355. default:
  8356. result = await this.table.queryMediaLibraryPaged(options);
  8357. break;
  8358. }
  8359. const currentSearchKeyword = this.isSearchMode ? this.searchText : '';
  8360. if (expectedModeType !== this.modeType ||
  8361. expectedSortType !== this.sortType ||
  8362. expectedIsShowFileName !== this.isShowFileName ||
  8363. expectedSearchKeyword !== currentSearchKeyword ||
  8364. (expectedModeType === 0 && expectedParentPath !== this.currentPath)) {
  8365. Logger.info('heanup LocalMusic', `prefetchNextPage: 上下文已变化,放弃写入 page=${nextPage}`);
  8366. return;
  8367. }
  8368. this.pageHasMoreCache.set(nextPage, result.hasMore);
  8369. this.pageTotalCountCache.set(nextPage, result.totalCount);
  8370. if (result.items.length > 0) {
  8371. this.pageCache.set(nextPage, result.items);
  8372. this.prefetchGridWaterThumbsFromItems(result.items, this.twoFingerType == 4 ? 48 : 36);
  8373. this.cleanOldCache(nextPage);
  8374. if (nextPage === this.currentPage + 1 && !this.isLoadingPage && !this.isPagingTransition
  8375. && this.lastVisibleEndIndex >= 0 && this.videoLocalList.length > 0) {
  8376. const seenRatio = (this.lastVisibleEndIndex + 1) / Math.max(this.videoLocalList.length, 1);
  8377. if (seenRatio >= Math.max(0.14, this.getDynamicAppendStartRatio() - 0.12)) {
  8378. Logger.info('heanup LocalMusic',
  8379. `prefetchNextPage: 下一页缓存已就绪,提前衔接 page=${nextPage}, ratio=${seenRatio}`);
  8380. this.scheduleLoadNextPage(8);
  8381. }
  8382. }
  8383. }
  8384. } catch (err) {
  8385. const error = err as Error;
  8386. Logger.warn('heanup LocalMusic', `prefetchNextPage error: ${error.message}`);
  8387. } finally {
  8388. this.prefetchingPages.delete(nextPage);
  8389. }
  8390. }
  8391. private mergeArtistCountMap(countMap: Map<string, number>): void {
  8392. const nextMap = new Map(this.artistSongCountMap);
  8393. countMap.forEach((count, artist) => {
  8394. nextMap.set(artist, count);
  8395. });
  8396. this.artistSongCountMap = nextMap;
  8397. }
  8398. private mergeAlbumCountMap(countMap: Map<string, number>): void {
  8399. const nextMap = new Map(this.albumSongCountMap);
  8400. countMap.forEach((count, album) => {
  8401. nextMap.set(album, count);
  8402. });
  8403. this.albumSongCountMap = nextMap;
  8404. }
  8405. private getArtistSongCount(artist: string): number {
  8406. return this.artistSongCountMap.get(artist) ?? this.artistMap.get(artist)?.length ?? 0;
  8407. }
  8408. private getAlbumSongCount(album: string): number {
  8409. return this.albumSongCountMap.get(album) ?? this.albumMap.get(album)?.length ?? 0;
  8410. }
  8411. /**
  8412. * 加载文件夹列表(仅用于modeType=0的首页模式)
  8413. */
  8414. private async loadDirectories(curPath: string): Promise<VideoItem[]> {
  8415. try {
  8416. Logger.info('heanup LocalMusic', `loadDirectories: 开始加载文件夹 path=${curPath}`);
  8417. // 检查缓存
  8418. const cacheKey = curPath + "_dirList";
  8419. const cachedDirList = this.findCache(cacheKey);
  8420. if (cachedDirList !== undefined && Array.isArray(cachedDirList)) {
  8421. Logger.info('heanup LocalMusic', `loadDirectories: 从缓存加载 count=${cachedDirList.length}`);
  8422. return cachedDirList as VideoItem[];
  8423. }
  8424. // 从文件系统读取
  8425. const fileList = FileUtil.listFileSync(curPath);
  8426. const directories: VideoItem[] = [];
  8427. for (let i = 0; i < fileList.length; i++) {
  8428. const path = curPath + '/' + fileList[i];
  8429. if (FileUtil.isDirectory(path)) {
  8430. const item: VideoItem = new VideoItem(
  8431. fileList[i].toString(),
  8432. fileList[i].toString(),
  8433. path,
  8434. CommonConstants.TYPE_IS_DIR,
  8435. 0,
  8436. ''
  8437. );
  8438. if (this.isShowDir(item.name)) {
  8439. directories.push(item);
  8440. }
  8441. }
  8442. }
  8443. // 排序
  8444. Utility.doSortListAscending(directories);
  8445. // 缓存文件夹列表
  8446. if (curPath === this.rootPath) {
  8447. this.dirList = directories;
  8448. this.addCache(cacheKey, directories);
  8449. }
  8450. Logger.info('heanup LocalMusic', `loadDirectories: 加载完成 count=${directories.length}`);
  8451. return directories;
  8452. } catch (err) {
  8453. const error = err as Error;
  8454. Logger.error('heanup LocalMusic', `loadDirectories error: ${error.message}`);
  8455. return [];
  8456. }
  8457. }
  8458. /**
  8459. * 构建播放队列(避免一次性加载全量)
  8460. */
  8461. private buildPlayQueueFromView(): Array<VideoItem> {
  8462. if (this.modeType === 4) {
  8463. this.playQueueScope = 'playlist';
  8464. return this.currentSongList;
  8465. }
  8466. if (this.isHistory) {
  8467. this.playQueueScope = 'history';
  8468. return this.historyList;
  8469. }
  8470. if (this.isFavMusic) {
  8471. this.playQueueScope = 'fav';
  8472. return this.favList;
  8473. }
  8474. this.playQueueScope = 'view';
  8475. return Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL);
  8476. }
  8477. private openSpecialLocalList(target: string): void {
  8478. this.mType = 0
  8479. this.isShowDrawer = false
  8480. this.offsetX = 0
  8481. this.isHistory = false
  8482. this.isFavMusic = false
  8483. if (target === 'recent') {
  8484. this.titleName = '最近播放'
  8485. this.currentTitleName = '最近播放'
  8486. this.currentTitleCover = $r('app.media.alt')
  8487. this.updateListData(this.historyList, true)
  8488. if (ArrayUtil.isNotEmpty(this.historyList)) {
  8489. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  8490. }
  8491. this.isHistory = true
  8492. return
  8493. }
  8494. if (target === 'favorite') {
  8495. this.titleName = '我的收藏'
  8496. this.currentTitleName = '我的收藏'
  8497. this.currentTitleCover = $r('app.media.alt')
  8498. this.updateListData(this.favList, true)
  8499. if (ArrayUtil.isNotEmpty(this.favList)) {
  8500. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  8501. }
  8502. this.isFavMusic = true
  8503. }
  8504. }
  8505. private async tryLoadNextPageForPlayback(): Promise<void> {
  8506. if (this.playQueueScope !== 'view') {
  8507. return;
  8508. }
  8509. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  8510. return;
  8511. }
  8512. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  8513. return;
  8514. }
  8515. await this.loadNextPage();
  8516. const nextList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL);
  8517. if (nextList.length > this.songList.length) {
  8518. this.songList = nextList;
  8519. this.sonDataSource.pushArrayData(this.songList);
  8520. }
  8521. }
  8522. /**
  8523. * 加载更多流媒体歌曲(Navidrome/Jellyfin/Emby/AudioStation/Plex)
  8524. * 当播放列表弹窗滚动到底部时调用
  8525. */
  8526. private async loadMoreNavidromeSongs(): Promise<void> {
  8527. const beforeCount = this.songList.length;
  8528. const hasMore = hasMoreData();
  8529. Logger.info('heanup', `开始加载更多流媒体歌曲, 当前数量=${beforeCount}, hasMoreData=${hasMore}`);
  8530. if (!hasMore) {
  8531. Logger.info('heanup', '没有更多数据可加载(hasMoreData=false)');
  8532. return;
  8533. }
  8534. // 触发加载更多(会更新NavidromePlaylistStore中的数据)
  8535. const success = await triggerLoadMoreSongs(1);
  8536. Logger.info('heanup', `triggerLoadMoreSongs返回: ${success}`);
  8537. if (success) {
  8538. // 获取更新后的完整列表
  8539. const updatedList = getNavidromeVideoItems();
  8540. Logger.info('heanup', `更新后列表长度: ${updatedList.length}`);
  8541. if (updatedList.length > beforeCount) {
  8542. Logger.info('heanup', `流媒体歌曲加载成功: ${beforeCount} -> ${updatedList.length}`);
  8543. this.songList = updatedList;
  8544. this.sonDataSource.pushArrayData(this.songList);
  8545. } else {
  8546. Logger.info('heanup', '列表长度未增加');
  8547. }
  8548. } else {
  8549. Logger.info('heanup', '流媒体歌曲加载未返回新数据(triggerLoadMoreSongs=false)');
  8550. }
  8551. }
  8552. /**
  8553. * 重置分页状态并加载首页
  8554. */
  8555. private async resetAndLoadFirstPage(clearExistingList: boolean = true): Promise<void> {
  8556. Logger.info('heanup LocalMusic', 'resetAndLoadFirstPage: 重置分页状态');
  8557. this.currentPage = 0;
  8558. if (clearExistingList) {
  8559. this.videoLocalList = [];
  8560. }
  8561. this.pageCache.clear();
  8562. this.pageHasMoreCache.clear();
  8563. this.pageTotalCountCache.clear();
  8564. this.prefetchingPages.clear();
  8565. this.hasMoreData = true;
  8566. this.totalCount = 0;
  8567. this.lastScrollTriggerPage = -1;
  8568. this.lastVisibleEndIndex = -1;
  8569. this.listScrollAlphaCheckAt = 0;
  8570. this.listScrollPagingCheckAt = 0;
  8571. this.listScrollLastAlphaStart = -1;
  8572. this.listScrollLastPagingEnd = -1;
  8573. this.gridScrollPagingCheckAt = 0;
  8574. this.gridScrollLastPagingEnd = -1;
  8575. this.waterScrollPagingCheckAt = 0;
  8576. this.waterScrollLastPagingEnd = -1;
  8577. this.listVisibleStart = -1;
  8578. this.listVisibleEnd = -1;
  8579. this.listThumbWarmupCheckAt = 0;
  8580. this.listThumbWarmupStart = -1;
  8581. this.listThumbWarmupEnd = -1;
  8582. this.gridThumbWarmupCheckAt = 0;
  8583. this.gridThumbWarmupStart = -1;
  8584. this.gridThumbWarmupEnd = -1;
  8585. this.waterThumbWarmupCheckAt = 0;
  8586. this.waterThumbWarmupStart = -1;
  8587. this.waterThumbWarmupEnd = -1;
  8588. this.gridVisibleStart = -1;
  8589. this.gridVisibleEnd = -1;
  8590. this.waterVisibleStart = -1;
  8591. this.waterVisibleEnd = -1;
  8592. this.gridWaterLastActiveTs = 0;
  8593. this.isPagingTransition = false;
  8594. if (this.pagingScheduleTimer) {
  8595. clearTimeout(this.pagingScheduleTimer);
  8596. this.pagingScheduleTimer = 0;
  8597. }
  8598. if (this.gridWaterScrollIdleTimer) {
  8599. clearTimeout(this.gridWaterScrollIdleTimer);
  8600. this.gridWaterScrollIdleTimer = 0;
  8601. }
  8602. this.coverThumbCache.clearPending();
  8603. this.pendingCoverThumbRefresh = false;
  8604. if (this.modeType === 2) {
  8605. this.artistSongCountMap = new Map();
  8606. } else if (this.modeType === 3) {
  8607. this.albumSongCountMap = new Map();
  8608. }
  8609. await this.loadPage(0, false);
  8610. }
  8611. private markGridWaterScrollingActive(): void {
  8612. if (!this.isScrolling) {
  8613. this.isScrolling = true;
  8614. }
  8615. const now = Date.now();
  8616. if (now - this.gridWaterLastActiveTs < 80) {
  8617. return;
  8618. }
  8619. this.gridWaterLastActiveTs = now;
  8620. if (this.gridWaterScrollIdleTimer) {
  8621. clearTimeout(this.gridWaterScrollIdleTimer);
  8622. }
  8623. this.gridWaterScrollIdleTimer = setTimeout(() => {
  8624. this.gridWaterScrollIdleTimer = 0;
  8625. if (this.isScrolling) {
  8626. this.isScrolling = false;
  8627. }
  8628. this.flushPendingCoverThumbRefresh();
  8629. }, 120);
  8630. }
  8631. private updateTitleBarByScrollOffset(currentOffsetY: number): void {
  8632. if (!this.autoHideTitle) {
  8633. return;
  8634. }
  8635. const now = Date.now();
  8636. if (now - this.titleBarLastCheckTs < 36) {
  8637. return;
  8638. }
  8639. this.titleBarLastCheckTs = now;
  8640. const delta = currentOffsetY - this.prevOffsetY;
  8641. if (Math.abs(delta) < this.titleBarToggleMinDelta) {
  8642. return;
  8643. }
  8644. if (delta > 0) {
  8645. if (this.isShowTitleBar) {
  8646. this.isShowTitleBar = false;
  8647. }
  8648. } else {
  8649. if (!this.isShowTitleBar) {
  8650. this.isShowTitleBar = true;
  8651. }
  8652. }
  8653. this.prevOffsetY = currentOffsetY;
  8654. }
  8655. private shouldPrefetchSecondPage(): boolean {
  8656. if (this.isMediaLibraryListMode()) {
  8657. return this.pageSize <= 120;
  8658. }
  8659. if (this.pageSize > 60) {
  8660. return false;
  8661. }
  8662. return this.isGridMusic || this.twoFingerType == 4;
  8663. }
  8664. private isMediaLibraryListMode(): boolean {
  8665. return this.modeType === 1 && !this.isGridMusic && this.twoFingerType != 4;
  8666. }
  8667. private isMediaLibraryWarmupWindow(): boolean {
  8668. if (this.modeType !== 1 || this.isCanBack) {
  8669. return false;
  8670. }
  8671. if (this.mediaLibraryEnterTs <= 0) {
  8672. return false;
  8673. }
  8674. return Date.now() - this.mediaLibraryEnterTs < 1800;
  8675. }
  8676. private getDynamicPreloadStartRatio(): number {
  8677. if (this.twoFingerType == 4) {
  8678. return 0.10;
  8679. }
  8680. if (this.isGridMusic) {
  8681. return 0.14;
  8682. }
  8683. if (this.isMediaLibraryListMode()) {
  8684. return 0.12;
  8685. }
  8686. return this.preloadStartRatio;
  8687. }
  8688. private getDynamicAppendStartRatio(): number {
  8689. if (this.twoFingerType == 4) {
  8690. return 0.18;
  8691. }
  8692. if (this.isGridMusic) {
  8693. return 0.22;
  8694. }
  8695. if (this.isMediaLibraryListMode()) {
  8696. return 0.22;
  8697. }
  8698. return this.appendStartRatio;
  8699. }
  8700. private getDynamicEarlyAppendReserveCount(): number {
  8701. if (this.twoFingerType == 4) {
  8702. return Math.max(this.earlyAppendReserveCount, Math.floor(this.pageSize * 0.9));
  8703. }
  8704. if (this.isGridMusic) {
  8705. return Math.max(this.earlyAppendReserveCount, Math.floor(this.pageSize * 0.82));
  8706. }
  8707. if (this.isMediaLibraryListMode()) {
  8708. return Math.max(this.earlyAppendReserveCount, Math.floor(this.pageSize * 0.75));
  8709. }
  8710. return this.earlyAppendReserveCount;
  8711. }
  8712. private prefetchFollowingPages(nextPage: number): void {
  8713. void this.prefetchNextPage(nextPage);
  8714. if (this.shouldPrefetchSecondPage()) {
  8715. void this.prefetchNextPage(nextPage + 1);
  8716. }
  8717. }
  8718. private scrollToTopForCurrentLayout(): void {
  8719. if (this.twoFingerType == 4) {
  8720. this.waterScroller.scrollEdge(Edge.Top);
  8721. this.scroller.scrollEdge(Edge.Top);
  8722. return;
  8723. }
  8724. if (this.isGridMusic) {
  8725. this.scroller.scrollEdge(Edge.Top);
  8726. return;
  8727. }
  8728. this.listScroller.scrollEdge(Edge.Top);
  8729. }
  8730. private getListImageSource(item: VideoItem, index: number, coverVersion: number = 0): ResourceStr {
  8731. const fallback = item.type == CommonConstants.TYPE_IS_DIR ? $r('app.media.dir_alt') : $r('app.media.alt');
  8732. if (coverVersion < -1) {
  8733. return fallback;
  8734. }
  8735. if (StrUtil.isEmpty(item.pixelMapPath)) {
  8736. return fallback;
  8737. }
  8738. const sourceUri = item.pixelMapPath as string;
  8739. this.initCoverThumbCacheIfNeeded();
  8740. const targetSize = this.getListThumbTargetSize();
  8741. const cachedThumb = this.coverThumbCache.getThumbUri(sourceUri, targetSize);
  8742. if (cachedThumb) {
  8743. return cachedThumb;
  8744. }
  8745. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  8746. const preloadBuffer = Math.max(8, Math.floor(this.pageSize * 0.2));
  8747. const hasRange = this.listVisibleStart >= 0 && this.listVisibleEnd >= 0;
  8748. const isNearVisible = !hasRange ||
  8749. (index >= this.listVisibleStart - preloadBuffer && index <= this.listVisibleEnd + preloadBuffer);
  8750. if (isNearVisible) {
  8751. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  8752. }
  8753. }
  8754. return sourceUri;
  8755. }
  8756. private getListThumbTargetSize(): number {
  8757. if (this.twoFingerType == 1) {
  8758. return 96;
  8759. }
  8760. if (this.twoFingerType == 2) {
  8761. return 112;
  8762. }
  8763. return 128;
  8764. }
  8765. private prefetchListThumbsFromItems(items: VideoItem[], limit: number = 24): void {
  8766. if (!this.isMediaLibraryListMode() || !items || items.length === 0) {
  8767. return;
  8768. }
  8769. this.initCoverThumbCacheIfNeeded();
  8770. const targetSize = this.getListThumbTargetSize();
  8771. const maxCount = Math.min(limit, items.length);
  8772. for (let i = 0; i < maxCount; i++) {
  8773. const item = items[i];
  8774. if (StrUtil.isEmpty(item.pixelMapPath)) {
  8775. continue;
  8776. }
  8777. const sourceUri = item.pixelMapPath as string;
  8778. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  8779. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  8780. }
  8781. }
  8782. }
  8783. private warmupListVisibleThumbs(start: number, end: number): void {
  8784. if (!this.isMediaLibraryListMode()) {
  8785. return;
  8786. }
  8787. if (start < 0 || end < 0 || this.videoLocalList.length <= 0) {
  8788. return;
  8789. }
  8790. const now = Date.now();
  8791. const startDelta = this.listThumbWarmupStart >= 0 ? Math.abs(start - this.listThumbWarmupStart) : 999;
  8792. const endDelta = this.listThumbWarmupEnd >= 0 ? Math.abs(end - this.listThumbWarmupEnd) : 999;
  8793. if (startDelta < 2 && endDelta < 2 && now - this.listThumbWarmupCheckAt < 90) {
  8794. return;
  8795. }
  8796. this.listThumbWarmupCheckAt = now;
  8797. this.listThumbWarmupStart = start;
  8798. this.listThumbWarmupEnd = end;
  8799. this.initCoverThumbCacheIfNeeded();
  8800. const targetSize = this.getListThumbTargetSize();
  8801. const preloadAhead = Math.max(14, Math.floor(this.pageSize * 0.4));
  8802. const begin = Math.max(0, start - 4);
  8803. const last = Math.min(this.videoLocalList.length - 1, end + preloadAhead);
  8804. for (let index = begin; index <= last; index++) {
  8805. const item = this.videoLocalList[index];
  8806. if (!item || StrUtil.isEmpty(item.pixelMapPath)) {
  8807. continue;
  8808. }
  8809. const sourceUri = item.pixelMapPath as string;
  8810. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  8811. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  8812. }
  8813. }
  8814. }
  8815. private prefetchGridWaterThumbsFromItems(items: VideoItem[], limit: number = 42): void {
  8816. if (!(this.isGridMusic || this.twoFingerType == 4) || !items || items.length === 0) {
  8817. return;
  8818. }
  8819. this.initCoverThumbCacheIfNeeded();
  8820. const isWater = this.twoFingerType == 4;
  8821. const targetSize = this.getCoverThumbTargetSize(isWater);
  8822. const maxCount = Math.min(limit, items.length);
  8823. for (let i = 0; i < maxCount; i++) {
  8824. const item = items[i];
  8825. if (!item || StrUtil.isEmpty(item.pixelMapPath)) {
  8826. continue;
  8827. }
  8828. const sourceUri = item.pixelMapPath as string;
  8829. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  8830. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  8831. }
  8832. }
  8833. }
  8834. private warmupGridWaterVisibleThumbs(start: number, end: number, isWater: boolean): void {
  8835. if (!(this.isGridMusic || this.twoFingerType == 4)) {
  8836. return;
  8837. }
  8838. if (start < 0 || end < 0 || this.videoLocalList.length <= 0) {
  8839. return;
  8840. }
  8841. const now = Date.now();
  8842. let lastStart = -1;
  8843. let lastEnd = -1;
  8844. let lastCheckAt = 0;
  8845. if (isWater) {
  8846. lastStart = this.waterThumbWarmupStart;
  8847. lastEnd = this.waterThumbWarmupEnd;
  8848. lastCheckAt = this.waterThumbWarmupCheckAt;
  8849. } else {
  8850. lastStart = this.gridThumbWarmupStart;
  8851. lastEnd = this.gridThumbWarmupEnd;
  8852. lastCheckAt = this.gridThumbWarmupCheckAt;
  8853. }
  8854. const startDelta = lastStart >= 0 ? Math.abs(start - lastStart) : 999;
  8855. const endDelta = lastEnd >= 0 ? Math.abs(end - lastEnd) : 999;
  8856. if (startDelta < 2 && endDelta < 2 && now - lastCheckAt < 70) {
  8857. return;
  8858. }
  8859. if (isWater) {
  8860. this.waterThumbWarmupCheckAt = now;
  8861. this.waterThumbWarmupStart = start;
  8862. this.waterThumbWarmupEnd = end;
  8863. } else {
  8864. this.gridThumbWarmupCheckAt = now;
  8865. this.gridThumbWarmupStart = start;
  8866. this.gridThumbWarmupEnd = end;
  8867. }
  8868. this.initCoverThumbCacheIfNeeded();
  8869. const columns = isWater ? Math.max(this.columns, 1) :
  8870. (this.twoFingerType == 1 ? 4 : this.twoFingerType == 2 ? 3 : 2);
  8871. const preloadAhead = Math.max(columns * (isWater ? 8 : 6), isWater ? 24 : 18);
  8872. const begin = Math.max(0, start - Math.max(columns * 2, 4));
  8873. const last = Math.min(this.videoLocalList.length - 1, end + preloadAhead);
  8874. const targetSize = this.getCoverThumbTargetSize(isWater);
  8875. for (let index = begin; index <= last; index++) {
  8876. const item = this.videoLocalList[index];
  8877. if (!item || StrUtil.isEmpty(item.pixelMapPath)) {
  8878. continue;
  8879. }
  8880. const sourceUri = item.pixelMapPath as string;
  8881. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  8882. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  8883. }
  8884. }
  8885. }
  8886. private getGridWaterImageSource(item: VideoItem, index: number, isWater: boolean,
  8887. coverVersion: number = 0): ResourceStr {
  8888. const fallback = item.type == CommonConstants.TYPE_IS_DIR ? $r('app.media.dir_alt') : $r('app.media.alt');
  8889. if (coverVersion < -1) {
  8890. return fallback;
  8891. }
  8892. if (StrUtil.isEmpty(item.pixelMapPath)) {
  8893. return fallback;
  8894. }
  8895. const sourceUri = item.pixelMapPath as string;
  8896. this.initCoverThumbCacheIfNeeded();
  8897. const isRemoteCover = this.coverThumbCache.isRemoteImageSource(sourceUri);
  8898. const targetSize = this.getCoverThumbTargetSize(isWater);
  8899. const cachedThumb = this.coverThumbCache.getThumbUri(sourceUri, targetSize);
  8900. if (cachedThumb) {
  8901. return cachedThumb;
  8902. }
  8903. const visibleStart = isWater ? this.waterVisibleStart : this.gridVisibleStart;
  8904. const visibleEnd = isWater ? this.waterVisibleEnd : this.gridVisibleEnd;
  8905. const columns = isWater ? Math.max(this.columns, 1) :
  8906. (this.twoFingerType == 1 ? 4 : this.twoFingerType == 2 ? 3 : 2);
  8907. const preloadBuffer = Math.max(columns * 2, 8);
  8908. const isVisibleRangeReady = visibleStart >= 0 && visibleEnd >= 0;
  8909. const isNearVisible = !isVisibleRangeReady || (index >= visibleStart - preloadBuffer && index <= visibleEnd + preloadBuffer);
  8910. if (!isRemoteCover && isNearVisible) {
  8911. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  8912. }
  8913. if (!this.isScrolling) {
  8914. return sourceUri;
  8915. }
  8916. if (isNearVisible) {
  8917. return sourceUri;
  8918. }
  8919. return fallback;
  8920. }
  8921. private flushPendingCoverThumbRefresh(): void {
  8922. if (!this.pendingCoverThumbRefresh) {
  8923. return;
  8924. }
  8925. this.pendingCoverThumbRefresh = false;
  8926. this.coverThumbVersion++;
  8927. }
  8928. private initCoverThumbCacheIfNeeded(): void {
  8929. if (this.coverThumbCacheReady) {
  8930. return;
  8931. }
  8932. this.coverThumbCache.setContext(this.context);
  8933. this.coverThumbCache.setOnThumbReady(() => {
  8934. if (this.isScrolling) {
  8935. this.pendingCoverThumbRefresh = true;
  8936. return;
  8937. }
  8938. this.coverThumbVersion++;
  8939. });
  8940. this.coverThumbCacheReady = true;
  8941. }
  8942. private getCoverThumbTargetSize(isWater: boolean): number {
  8943. if (isWater) {
  8944. if (this.columns >= 4) {
  8945. return 160;
  8946. }
  8947. if (this.columns == 3) {
  8948. return 200;
  8949. }
  8950. return 260;
  8951. }
  8952. const baseSize = Math.max(this.getGridWight(), this.getGridHeight());
  8953. if (this.twoFingerType == 1) {
  8954. return baseSize;
  8955. }
  8956. if (this.twoFingerType == 2) {
  8957. return Math.floor(baseSize * 1.1);
  8958. }
  8959. return Math.floor(baseSize * 1.15);
  8960. }
  8961. private tryTriggerLoadForWaterByOffset(currentOffsetY: number): void {
  8962. if (this.videoLocalList.length <= 0) {
  8963. return;
  8964. }
  8965. const columns = Math.max(this.columns, 1);
  8966. const viewportHeight = this.windowHeight > 0 ? this.windowHeight : 900;
  8967. const estimatedCardHeight = this.columns >= 3 ? 196 : 228;
  8968. const startRow = Math.max(0, Math.floor(Math.max(currentOffsetY, 0) / estimatedCardHeight) - 1);
  8969. const estimatedRows = Math.ceil((Math.max(currentOffsetY, 0) + viewportHeight) / estimatedCardHeight);
  8970. const startIndex = Math.min(this.videoLocalList.length - 1, startRow * columns);
  8971. const estimatedEnd = Math.min(this.videoLocalList.length - 1, estimatedRows * columns + columns);
  8972. this.waterVisibleStart = startIndex;
  8973. this.waterVisibleEnd = estimatedEnd;
  8974. this.lastVisibleEndIndex = estimatedEnd;
  8975. this.warmupGridWaterVisibleThumbs(startIndex, estimatedEnd, true);
  8976. const now = Date.now();
  8977. const pagingDelta = this.waterScrollLastPagingEnd >= 0 ? Math.abs(estimatedEnd - this.waterScrollLastPagingEnd) : 999;
  8978. if (pagingDelta >= 3 || now - this.waterScrollPagingCheckAt >= 80) {
  8979. this.waterScrollPagingCheckAt = now;
  8980. this.waterScrollLastPagingEnd = estimatedEnd;
  8981. this.tryTriggerLoadNextPageByScroll(estimatedEnd);
  8982. }
  8983. }
  8984. private tryTriggerLoadNextPageByScroll(endIndex: number): void {
  8985. if (this.modeType === 4) {
  8986. return;
  8987. }
  8988. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  8989. return;
  8990. }
  8991. if (this.isHistory || this.isFavMusic) {
  8992. return;
  8993. }
  8994. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  8995. return;
  8996. }
  8997. if (endIndex < 0 || endIndex >= this.videoLocalList.length) {
  8998. return;
  8999. }
  9000. const nextPage = this.currentPage + 1;
  9001. const next2Page = this.currentPage + 2;
  9002. const totalLoaded = this.videoLocalList.length;
  9003. const seenRatio = (endIndex + 1) / Math.max(totalLoaded, 1);
  9004. const remainCount = this.videoLocalList.length - endIndex - 1;
  9005. const preloadStartRatio = this.getDynamicPreloadStartRatio();
  9006. const appendStartRatio = this.getDynamicAppendStartRatio();
  9007. const earlyAppendReserveCount = this.getDynamicEarlyAppendReserveCount();
  9008. const emergencyDistance = Math.max(12, Math.floor(this.pageSize * 0.5));
  9009. if (seenRatio >= preloadStartRatio) {
  9010. if (!this.pageCache.has(nextPage)) {
  9011. void this.prefetchNextPage(nextPage);
  9012. }
  9013. if (this.shouldPrefetchSecondPage() && !this.pageCache.has(next2Page)) {
  9014. void this.prefetchNextPage(next2Page);
  9015. }
  9016. }
  9017. const shouldAppendEarly = this.pageCache.has(nextPage) &&
  9018. (seenRatio >= appendStartRatio || remainCount <= earlyAppendReserveCount);
  9019. const shouldGapAppend = this.pageCache.has(nextPage) &&
  9020. seenRatio >= (appendStartRatio - 0.08) &&
  9021. remainCount <= Math.max(earlyAppendReserveCount, Math.floor(this.pageSize * 0.9));
  9022. const shouldEmergencyLoad = remainCount <= emergencyDistance;
  9023. if (!shouldAppendEarly && !shouldGapAppend && !shouldEmergencyLoad) {
  9024. return;
  9025. }
  9026. if (this.lastScrollTriggerPage === this.currentPage) {
  9027. return;
  9028. }
  9029. this.lastScrollTriggerPage = this.currentPage;
  9030. Logger.info('heanup LocalMusic',
  9031. `tryTriggerLoadNextPageByScroll: end=${endIndex}, remain=${remainCount}, ratio=${seenRatio}, page=${this.currentPage}`);
  9032. this.scheduleLoadNextPage(8);
  9033. }
  9034. private scheduleLoadNextPage(delayMs: number = 0): void {
  9035. if (this.pagingScheduleTimer) {
  9036. return;
  9037. }
  9038. this.pagingScheduleTimer = setTimeout(() => {
  9039. this.pagingScheduleTimer = 0;
  9040. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  9041. return;
  9042. }
  9043. void this.loadNextPage();
  9044. }, delayMs);
  9045. }
  9046. /**
  9047. * 加载下一页
  9048. */
  9049. private async loadNextPage(): Promise<void> {
  9050. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  9051. return;
  9052. }
  9053. this.isPagingTransition = true;
  9054. this.currentPage++;
  9055. Logger.info('heanup LocalMusic', `loadNextPage: 加载第 ${this.currentPage} 页`);
  9056. try {
  9057. await this.loadPage(this.currentPage, true);
  9058. } finally {
  9059. this.isPagingTransition = false;
  9060. }
  9061. }
  9062. //编辑信息
  9063. async doEdit(item: VideoItem) {
  9064. if (!item) {
  9065. return
  9066. }
  9067. if (StrUtil.isEmpty(this.titleStr)) {
  9068. ToastUtil.showToast('标题不能为空')
  9069. return
  9070. }
  9071. //内嵌音乐标签不能开启监听
  9072. // this.deletionWatcher?.stop();
  9073. this.loadingDialogId = DialogHelper.showLoadingDialog()
  9074. if (isRemoteCloudType(item.type)) {
  9075. await this.saveRemoteSongEdit(item);
  9076. return;
  9077. }
  9078. await PermissionUtil.activatePermission(item.filePath)
  9079. let tempOutPath = ''
  9080. // 如果不是 packName 包下的文件,则直接路径用this.currentPath
  9081. if(!item.filePath.toLowerCase().includes(this.packName)){
  9082. tempOutPath = this.currentPath + '/' + item.fileName
  9083. }
  9084. console.info('onecold tempOutPath ='+tempOutPath)
  9085. //用户更改了封面,那就内嵌下封面
  9086. if(StrUtil.isNotEmpty(this.imagePathStr)){
  9087. const resultCover:boolean = await changeMusicCover(this.context,
  9088. item.filePath,this.imagePathStr,true,tempOutPath);
  9089. this.imagePathStr = ''
  9090. if(resultCover){
  9091. ToastUtil.showToast('内嵌封面成功')
  9092. }
  9093. }
  9094. const metadata:FFMpegTags = {
  9095. title: this.titleStr,
  9096. artist: this.artistStr,
  9097. album: this.ablumStr,
  9098. TYER:this.yearStr,
  9099. genre:this.genreStr,
  9100. track:this.trackStr,
  9101. album_artist:this.albumArtistStr,
  9102. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  9103. COMPOSER:this.composerStr,
  9104. lyricist:this.lyricistStr,
  9105. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  9106. comment:this.commentStr,
  9107. disc:this.discStr,
  9108. };
  9109. let newInput = item.filePath
  9110. //内嵌标签歌路径如果不是包含包名,输入newInput要赋值tempOutPath,然后tempOutPath为空
  9111. if(!item.filePath.toLowerCase().includes(this.packName)&&FileUtil.accessSync(tempOutPath)){
  9112. newInput = tempOutPath
  9113. tempOutPath = ''
  9114. }
  9115. const isWav:boolean = newInput.toLowerCase().endsWith('.wav')
  9116. ||newInput.toLowerCase().endsWith('.ape')
  9117. ||newInput.toLowerCase().endsWith('.dsf')
  9118. ||newInput.toLowerCase().endsWith('.dff');
  9119. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  9120. const result:boolean = await repairAudioMetadata(
  9121. newInput,
  9122. this.lyricConStr,
  9123. metadata,
  9124. true,
  9125. tempOutPath
  9126. );
  9127. // ToastUtil.showToast('result ='+ result)
  9128. if (result||isWav) {
  9129. if(!item.filePath.includes(this.packName)){
  9130. //内嵌成功的歌路径如果不是包含包名,则要入库
  9131. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newInput,
  9132. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  9133. this.table.insert(newItem, (id: number) => {
  9134. //加入数据库
  9135. if(this.modeType==0){
  9136. this.deleteCache(this.currentPath)
  9137. this.getSortedFiles(this.currentPath)
  9138. }
  9139. });
  9140. }
  9141. const task = new taskpool.Task(
  9142. updateInfoDb,
  9143. this.context,
  9144. item.filePath,
  9145. this.titleStr,
  9146. this.artistStr,
  9147. this.ablumStr,
  9148. this.lyricConStr,
  9149. this.yearStr,this.genreStr,
  9150. this.trackStr,this.albumArtistStr,
  9151. this.composerStr, this.lyricistStr,
  9152. this.commentStr,this.discStr
  9153. );
  9154. taskpool.execute(task, taskpool.Priority.HIGH).then((result) => {
  9155. if (result) {
  9156. console.log(" onecold 编辑信息成功,数据库已同步");
  9157. if(isWav){
  9158. ToastUtil.showToast('dsf、wav、dff或者ape格式有可能内嵌失败,但是编辑信息成功')
  9159. }else{
  9160. ToastUtil.showToast('内嵌音乐标签成功')
  9161. }
  9162. this.isShowMoreView = false
  9163. this.name = this.titleStr
  9164. this.syncEditedFields(item)
  9165. if (item.filePath == this.currentSong?.filePath) {
  9166. this.currentSong.name = this.titleStr
  9167. this.artist = this.artistStr
  9168. this.currentSong.artist = this.artistStr
  9169. this.currentSong.album = this.ablumStr
  9170. this.currentSong.year = this.yearStr
  9171. this.currentSong.genre = this.genreStr
  9172. this.currentSong.track = this.trackStr
  9173. this.currentSong.lyricContent = this.lyricConStr
  9174. this.currentSong.ALBUMARTIST = this.albumArtistStr
  9175. this.currentSong.COMPOSER = this.composerStr
  9176. this.currentSong.LYRICIST = this.lyricistStr
  9177. this.currentSong.COMMENT = this.commentStr
  9178. }
  9179. this.syncListsAfterEdit(item.filePath)
  9180. this.doUpateEditedFields(item)
  9181. //this.doUpdateData()
  9182. } else {
  9183. // ToastUtil.showToast('保存失败' + error?.toString())
  9184. console.error(" onecold 编辑信息数据库失败 ");
  9185. }
  9186. // 关闭进度条
  9187. DialogHelper.closeDialog(this.loadingDialogId)
  9188. }).catch((error: Error) => {
  9189. // 关闭进度条
  9190. DialogHelper.closeDialog(this.loadingDialogId)
  9191. console.error('onecold Subtitle sync failed:', error);
  9192. });
  9193. console.log(' onecold 元数据标签更新成功,');
  9194. } else {
  9195. // 关闭进度条
  9196. DialogHelper.closeDialog(this.loadingDialogId)
  9197. ToastUtil.showToast('内嵌音乐标签失败')
  9198. console.log('onecold 内嵌音乐标签失败');
  9199. }
  9200. this.longItemFilePath = ''
  9201. this.tempLyricContent = ''
  9202. this.isShowEdit = false
  9203. }
  9204. private normalizeEditedCoverPath(path: string): string {
  9205. if (StrUtil.isEmpty(path)) {
  9206. return '';
  9207. }
  9208. const lowerPath = path.toLowerCase();
  9209. if (lowerPath.startsWith('http://') || lowerPath.startsWith('https://')
  9210. || lowerPath.startsWith('file://') || lowerPath.startsWith('data:')) {
  9211. return path;
  9212. }
  9213. return fileUri.getUriFromPath(path);
  9214. }
  9215. private emitRemoteMetadataUpdated(item: VideoItem): void {
  9216. if (!item || StrUtil.isEmpty(item.filePath)) {
  9217. return;
  9218. }
  9219. const payload: WebDavMetadataUpdatePayload = {
  9220. filePath: item.filePath,
  9221. pixelMapPath: item.pixelMapPath,
  9222. isCustomCover: item.isCustomCover,
  9223. md5Str: item.md5Str,
  9224. name: item.name,
  9225. artist: item.artist
  9226. };
  9227. const eventUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
  9228. emitter.emit(eventUpdate, { data: [payload] });
  9229. }
  9230. private syncRemoteManagerSong(item: VideoItem): void {
  9231. if (!item || StrUtil.isEmpty(item.filePath)) {
  9232. return;
  9233. }
  9234. const remoteManager = RemoteDriveManager.getInstance();
  9235. const target = Utility.getItemByFilePath(remoteManager.webDavSongs, item.filePath);
  9236. if (!target) {
  9237. return;
  9238. }
  9239. this.mergeVideoItemFromSource(target, item);
  9240. }
  9241. private async saveRemoteSongEdit(item: VideoItem): Promise<void> {
  9242. try {
  9243. this.syncEditedFields(item);
  9244. if (StrUtil.isNotEmpty(this.imagePathStr)) {
  9245. item.pixelMapPath = this.normalizeEditedCoverPath(this.imagePathStr);
  9246. item.isCustomCover = 1;
  9247. }
  9248. this.name = this.titleStr;
  9249. if (this.currentSong && item.filePath === this.currentSong.filePath) {
  9250. this.syncEditedFields(this.currentSong);
  9251. if (StrUtil.isNotEmpty(item.pixelMapPath)) {
  9252. mergeCoverWithPriority(this.currentSong, item.pixelMapPath, item.isCustomCover ?? 0);
  9253. this.cover = this.currentSong.pixelMapPath || item.pixelMapPath;
  9254. }
  9255. this.artist = this.currentSong.artist ?? '';
  9256. this.currentSong = cloneVideoItem(this.currentSong);
  9257. AppStorage.setOrCreate('currentSong', this.currentSong);
  9258. }
  9259. this.syncListsAfterEdit(item.filePath);
  9260. this.syncRemoteManagerSong(item);
  9261. await this.persistRemoteMetadataToDb(item);
  9262. this.emitRemoteMetadataUpdated(item);
  9263. ToastUtil.showToast(StrUtil.isNotEmpty(item.pixelMapPath) ? '网盘歌曲信息已保存' : '网盘歌曲标签已保存');
  9264. } catch (error) {
  9265. Logger.error(TAG, `saveRemoteSongEdit 失败: ${(error as Error).message}`);
  9266. ToastUtil.showToast('网盘歌曲编辑失败');
  9267. } finally {
  9268. DialogHelper.closeDialog(this.loadingDialogId);
  9269. this.longItemFilePath = '';
  9270. this.tempLyricContent = '';
  9271. this.isShowEdit = false;
  9272. this.imagePathStr = '';
  9273. this.isShowMoreView = false;
  9274. }
  9275. }
  9276. // 内嵌标签更新当前内嵌的Item
  9277. async doUpateEditedFields(item: VideoItem) {
  9278. // 找到当前项在 videoLocalList 中的索引
  9279. const index = this.videoLocalList.findIndex(video => video.filePath === item.filePath);
  9280. if (index !== -1) {
  9281. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  9282. const updatedItem = await this.table.queryVideoByFilePath(item.filePath)
  9283. // 只有当查询结果不为 null 时才更新列表
  9284. if (updatedItem !== null) {
  9285. // 更新 videoLocalList 中的项(通过创建新数组触发响应式更新)
  9286. this.videoLocalList = [
  9287. ...this.videoLocalList.slice(0, index),
  9288. updatedItem,
  9289. ...this.videoLocalList.slice(index + 1)
  9290. ];
  9291. // 同步更新 LazyDataSource
  9292. this.dataSource.pushArrayData(this.videoLocalList)
  9293. } else {
  9294. ToastUtil.showToast('未找到更新的数据');
  9295. }
  9296. }
  9297. DialogHelper.closeDialog(this.loadingDialogId)
  9298. }
  9299. @Builder
  9300. editSheet(item: VideoItem) {
  9301. Scroll() {
  9302. Column() {
  9303. this.editDetail(item)
  9304. }
  9305. }
  9306. .width('100%')
  9307. .height('100%')
  9308. }
  9309. @Builder
  9310. editDetail(item: VideoItem) {
  9311. Column() {
  9312. if (item) {
  9313. Row() {
  9314. Stack() {
  9315. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  9316. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  9317. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
  9318. item.pixelMapPath)
  9319. .fillColor(this.themeColor)
  9320. .height(88)
  9321. .width(88)
  9322. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  9323. .borderRadius(12)
  9324. .clip(true)
  9325. .opacity(this.opacityItem)// 绑定透明度
  9326. .margin({ left: 25 })
  9327. }
  9328. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  9329. .onClick(async () => {
  9330. const imagePath:string | undefined = await this.goSelectImage(item);
  9331. if (imagePath) {
  9332. //用户更改过图片
  9333. this.imagePathStr = imagePath
  9334. }
  9335. })
  9336. .width('28%')
  9337. Row() {
  9338. Column() {
  9339. Text(item.name)
  9340. .fontSize(17)
  9341. .maxLines(1)
  9342. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9343. .animation({
  9344. duration: 555,
  9345. curve: 'Linear',
  9346. })
  9347. .fontColor(this.themeColor)
  9348. .margin({ left: 8 })
  9349. Row() {
  9350. Text(item.artist)
  9351. .fontSize(14)
  9352. .maxLines(1)
  9353. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9354. .padding({ top: 8 })
  9355. .fontColor(this.themeColor)
  9356. .margin({ left: 8 })
  9357. }
  9358. }
  9359. .height('100%')
  9360. .width(100)
  9361. .layoutWeight(1)
  9362. .justifyContent(FlexAlign.Center)
  9363. .alignItems(HorizontalAlign.Start)
  9364. Column() {
  9365. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9366. Row(){
  9367. SymbolGlyph($r('sys.symbol.picture'))
  9368. .fontSize(18)
  9369. .fontColor([Color.White])
  9370. Text('获取封面')
  9371. .margin({ left: 4 })
  9372. .fontSize(11)
  9373. .fontColor(Color.White)
  9374. .fontWeight(480)
  9375. .textAlign(TextAlign.Center)
  9376. }
  9377. .justifyContent(FlexAlign.Center)
  9378. }
  9379. .height(38)
  9380. .width(100)
  9381. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9382. .backgroundColor(this.themeColor)
  9383. .stateEffect(true)
  9384. .margin({ right: 35 })
  9385. .onClick(async () => {
  9386. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  9387. this.showTipsDialog();
  9388. return; // Return empty string when no API is configured
  9389. }
  9390. const imagePath:string | undefined = await this.doSearchCover(item,
  9391. this.titleStr,this.artistStr);
  9392. console.info('onecold imagePath = '+imagePath)
  9393. if (StrUtil.isNotEmpty(imagePath)) {
  9394. //用户更改过图片
  9395. this.imagePathStr = imagePath
  9396. ToastUtil.showToast('获取封面成功')
  9397. }else{
  9398. ToastUtil.showToast('获取封面失败,请重试')
  9399. }
  9400. })
  9401. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9402. Row(){
  9403. SymbolGlyph($r('sys.symbol.input_mode'))
  9404. .fontSize(18)
  9405. .fontColor([Color.White])
  9406. Text('获取歌词')
  9407. .margin({ left: 4 })
  9408. .fontSize(11)
  9409. .fontColor(Color.White)
  9410. .fontWeight(480)
  9411. .textAlign(TextAlign.Center)
  9412. }
  9413. .justifyContent(FlexAlign.Center)
  9414. }
  9415. .height(38)
  9416. .width(100)
  9417. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9418. .backgroundColor(this.themeColor)
  9419. .stateEffect(true)
  9420. .margin({ top: 9, right: 35 })
  9421. .onClick(async () => {
  9422. //判断有没有设置api
  9423. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  9424. if (StrUtil.isEmpty(apiUrl)) {
  9425. this.isLyricSetting = false
  9426. this.showTipsDialog()
  9427. return
  9428. }
  9429. let res: string | undefined = await getApiLyric(apiUrl,
  9430. this.titleStr, this.artistStr, false);
  9431. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  9432. this.lyricConStr = res;
  9433. ToastUtil.showToast('获取歌词成功')
  9434. }else{
  9435. ToastUtil.showToast('获取歌词失败,请重试')
  9436. }
  9437. })
  9438. }
  9439. .justifyContent(FlexAlign.Start)
  9440. }
  9441. .height('100%')
  9442. .justifyContent(FlexAlign.Start)
  9443. .layoutWeight(1)
  9444. }
  9445. .width('100%')
  9446. .height(98)
  9447. Row() {
  9448. Text('标题:')
  9449. .fontSize(14)
  9450. .fontColor($r('app.color.text_color'))
  9451. .margin({ left: 22 })
  9452. TextInput({ text: this.titleStr })
  9453. .height(40)
  9454. .maxLines(1)
  9455. .fontSize(14)
  9456. .layoutWeight(1)
  9457. .fontColor($r('app.color.text_color'))
  9458. .margin({ right: 15, left: 10 })
  9459. .onChange((val: string) => {
  9460. this.titleStr = val
  9461. })
  9462. Button('修复乱码',{ type: ButtonType.Capsule, stateEffect: true})
  9463. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9464. .backgroundColor(this.themeColor)
  9465. .fontSize(10)
  9466. .margin({ right: 20})
  9467. .onClick(async () => {
  9468. let hwTags = await extractHwMediaMetadata(item.filePath)
  9469. let artist = hwTags?.artist|| '';
  9470. let title = hwTags?.title|| '';
  9471. let album = hwTags?.album|| '';
  9472. console.info('onecold 乱码修正 artist='+artist);
  9473. console.info('onecold 乱码修正 title='+title);
  9474. console.info('onecold 乱码修正 album='+album);
  9475. this.titleStr = title;
  9476. this.artistStr = artist;
  9477. this.ablumStr = album;
  9478. })
  9479. }
  9480. .width('100%')
  9481. .margin({ top: 10, bottom: 10 })
  9482. .justifyContent(FlexAlign.Start)
  9483. Row() {
  9484. Text('艺术家:')
  9485. .fontSize(14)
  9486. .fontColor($r('app.color.text_color'))
  9487. .margin({ left: 22 })
  9488. TextInput({ text: this.artistStr })
  9489. .height(40)
  9490. .maxLines(1)
  9491. .fontSize(14)
  9492. .layoutWeight(1)
  9493. .fontColor($r('app.color.text_color'))
  9494. .margin({ right: 20, left: 10 })
  9495. .onChange((val: string) => {
  9496. this.artistStr = val
  9497. })
  9498. }
  9499. .width('100%')
  9500. .margin({ top: 10, bottom: 10 })
  9501. .justifyContent(FlexAlign.Start)
  9502. Row() {
  9503. Text('专辑名:')
  9504. .fontSize(14)
  9505. .fontColor($r('app.color.text_color'))
  9506. .margin({ left: 22 })
  9507. TextInput({ text: this.ablumStr})
  9508. .height(40)
  9509. .maxLines(1)
  9510. .fontSize(14)
  9511. .layoutWeight(1)
  9512. .fontColor($r('app.color.text_color'))
  9513. .margin({ right: 20, left: 10 })
  9514. .onChange((val: string) => {
  9515. this.ablumStr = val
  9516. })
  9517. }
  9518. .width('100%')
  9519. .margin({ top: 10, bottom: 10 })
  9520. .justifyContent(FlexAlign.Start)
  9521. Row() {
  9522. Column(){
  9523. Column(){
  9524. Text('歌词:')
  9525. .fontSize(14)
  9526. .fontColor($r('app.color.text_color'))
  9527. .margin({ top:9,left: 22 })
  9528. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9529. SymbolGlyph($r('sys.symbol.trash_fill'))
  9530. .fontSize(25)
  9531. .alignSelf(ItemAlign.Center)
  9532. .margin({ left: 22,top:25})
  9533. }
  9534. .backgroundColor(Color.Transparent)
  9535. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  9536. Visibility.None:Visibility.Visible)
  9537. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9538. .onClick(()=>{
  9539. this.lyricConStr = ''
  9540. this.lyricContent = ''
  9541. this.tempLyricContent = ''
  9542. })
  9543. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9544. SymbolGlyph($r('sys.symbol.plus'))
  9545. .fontSize(25)
  9546. .alignSelf(ItemAlign.Center)
  9547. .margin({ left: 22,top:25})
  9548. }
  9549. .backgroundColor(Color.Transparent)
  9550. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9551. .onClick( ()=>{
  9552. this.callFilePickerSelectFileForLyric()
  9553. })
  9554. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9555. SymbolGlyph($r('sys.symbol.traditional_square'))
  9556. .fontSize(25)
  9557. .alignSelf(ItemAlign.Center)
  9558. .margin({ left: 22,top:25})
  9559. }
  9560. .backgroundColor(Color.Transparent)
  9561. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  9562. Visibility.None:Visibility.Visible)
  9563. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9564. .onClick( ()=>{
  9565. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  9566. this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
  9567. })
  9568. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9569. Image($r('app.media.jianti'))
  9570. .height(25)
  9571. .fillColor($r('app.color.text_color'))
  9572. .alignSelf(ItemAlign.Center)
  9573. .margin({ left: 22,top:25})
  9574. }
  9575. .backgroundColor(Color.Transparent)
  9576. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  9577. Visibility.None:Visibility.Visible)
  9578. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9579. .onClick( ()=>{
  9580. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  9581. this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
  9582. })
  9583. }
  9584. .layoutWeight(1)
  9585. }
  9586. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  9587. this.tempLyricContent })
  9588. .type(TextAreaType.NORMAL)
  9589. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
  9590. .fontSize(14)
  9591. .layoutWeight(1)
  9592. .fontColor($r('app.color.text_color'))
  9593. .margin({ right: 20, left: 10 })
  9594. .onChange((val: string) => {
  9595. this.lyricConStr = val
  9596. })
  9597. }
  9598. .width('100%')
  9599. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
  9600. .margin({ top: 10, bottom: 10 })
  9601. .justifyContent(FlexAlign.Start)
  9602. Row() {
  9603. Text('年份:')
  9604. .fontSize(14)
  9605. .fontColor($r('app.color.text_color'))
  9606. .margin({ left: 22 })
  9607. TextInput({ text: item.year })
  9608. .height(40)
  9609. .maxLines(1)
  9610. .fontSize(14)
  9611. .type(InputType.Number)
  9612. .layoutWeight(1)
  9613. .fontColor($r('app.color.text_color'))
  9614. .margin({ right: 20, left: 10 })
  9615. .onChange((val: string) => {
  9616. this.yearStr = val
  9617. })
  9618. }
  9619. .width('100%')
  9620. .margin({ top: 10, bottom: 10 })
  9621. .justifyContent(FlexAlign.Start)
  9622. Row() {
  9623. Text('音轨号:')
  9624. .fontSize(14)
  9625. .fontColor($r('app.color.text_color'))
  9626. .margin({ left: 22 })
  9627. TextInput({ text:item.track=='未知'?'': item.track })
  9628. .height(40)
  9629. .maxLines(1)
  9630. .fontSize(14)
  9631. .type(InputType.Number)
  9632. .layoutWeight(1)
  9633. .fontColor($r('app.color.text_color'))
  9634. .margin({ right: 20, left: 10 })
  9635. .onChange((val: string) => {
  9636. this.trackStr = val
  9637. })
  9638. }
  9639. .width('100%')
  9640. .margin({ top: 10, bottom: 10 })
  9641. .justifyContent(FlexAlign.Start)
  9642. Row() {
  9643. Text('碟号:')
  9644. .fontSize(14)
  9645. .fontColor($r('app.color.text_color'))
  9646. .margin({ left: 22 })
  9647. TextInput({ text:item.disc })
  9648. .height(40)
  9649. .maxLines(1)
  9650. .fontSize(14)
  9651. .type(InputType.Number)
  9652. .layoutWeight(1)
  9653. .fontColor($r('app.color.text_color'))
  9654. .margin({ right: 20, left: 10 })
  9655. .onChange((val: string) => {
  9656. this.discStr = val
  9657. })
  9658. }
  9659. .width('100%')
  9660. .margin({ top: 10, bottom: 10 })
  9661. .justifyContent(FlexAlign.Start)
  9662. Row() {
  9663. Text('风格:')
  9664. .fontSize(14)
  9665. .fontColor($r('app.color.text_color'))
  9666. .margin({ left: 22 })
  9667. TextInput({ text: item.genre })
  9668. .height(40)
  9669. .maxLines(1)
  9670. .fontSize(14)
  9671. .layoutWeight(1)
  9672. .fontColor($r('app.color.text_color'))
  9673. .margin({ right: 20, left: 10 })
  9674. .onChange((val: string) => {
  9675. this.genreStr = val
  9676. })
  9677. }
  9678. .width('100%')
  9679. .margin({ top: 10, bottom: 10 })
  9680. .justifyContent(FlexAlign.Start)
  9681. Row() {
  9682. Text('专辑艺术家:')
  9683. .fontSize(14)
  9684. .fontColor($r('app.color.text_color'))
  9685. .margin({ left: 22 })
  9686. TextInput({ text: item.ALBUMARTIST })
  9687. .height(40)
  9688. .maxLines(1)
  9689. .fontSize(14)
  9690. .layoutWeight(1)
  9691. .fontColor($r('app.color.text_color'))
  9692. .margin({ right: 20, left: 10 })
  9693. .onChange((val: string) => {
  9694. this.albumArtistStr = val
  9695. })
  9696. }
  9697. .width('100%')
  9698. .margin({ top: 10, bottom: 10 })
  9699. .justifyContent(FlexAlign.Start)
  9700. Row() {
  9701. Text('作曲:')
  9702. .fontSize(14)
  9703. .fontColor($r('app.color.text_color'))
  9704. .margin({ left: 22 })
  9705. TextInput({ text: item.COMPOSER })
  9706. .height(40)
  9707. .maxLines(1)
  9708. .fontSize(14)
  9709. .layoutWeight(1)
  9710. .fontColor($r('app.color.text_color'))
  9711. .margin({ right: 20, left: 10 })
  9712. .onChange((val: string) => {
  9713. this.composerStr = val
  9714. })
  9715. }
  9716. .width('100%')
  9717. .margin({ top: 10, bottom: 10 })
  9718. .justifyContent(FlexAlign.Start)
  9719. Row() {
  9720. Text('作词:')
  9721. .fontSize(14)
  9722. .fontColor($r('app.color.text_color'))
  9723. .margin({ left: 22 })
  9724. TextInput({ text: item.LYRICIST })
  9725. .height(40)
  9726. .maxLines(1)
  9727. .fontSize(14)
  9728. .layoutWeight(1)
  9729. .fontColor($r('app.color.text_color'))
  9730. .margin({ right: 20, left: 10 })
  9731. .onChange((val: string) => {
  9732. this.lyricistStr = val
  9733. })
  9734. }
  9735. .width('100%')
  9736. .margin({ top: 10, bottom: 10 })
  9737. .justifyContent(FlexAlign.Start)
  9738. Row() {
  9739. Text('注释:')
  9740. .fontSize(14)
  9741. .fontColor($r('app.color.text_color'))
  9742. .margin({ left: 22 })
  9743. TextInput({ text: item.COMMENT })
  9744. .height(40)
  9745. .maxLines(1)
  9746. .fontSize(14)
  9747. .layoutWeight(1)
  9748. .fontColor($r('app.color.text_color'))
  9749. .margin({ right: 20, left: 10 })
  9750. .onChange((val: string) => {
  9751. this.commentStr = val
  9752. })
  9753. }
  9754. .width('100%')
  9755. .margin({ top: 10, bottom: 10 })
  9756. .justifyContent(FlexAlign.Start)
  9757. Row() {
  9758. Button('保存')
  9759. .fontColor(Color.White)
  9760. .layoutWeight(1)
  9761. .height(50)
  9762. .width(100)
  9763. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9764. .backgroundColor(this.themeColor)
  9765. .stateEffect(true)
  9766. .margin({ right: 20, bottom: 20 })
  9767. .onClick(async () => {
  9768. this.doEdit(item)
  9769. })
  9770. Button('取消')
  9771. .fontColor(Color.White)
  9772. .layoutWeight(1)
  9773. .height(50)
  9774. .width(100)
  9775. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9776. .backgroundColor(this.themeColor)
  9777. .stateEffect(true)
  9778. .margin({ left: 20, bottom: 20 })
  9779. .onClick(async () => {
  9780. if(this.isGridMusic){
  9781. this.longItemFilePath =''
  9782. }else{
  9783. this.isShowEdit = false
  9784. }
  9785. this.setEditStrEmpty()
  9786. if(this.isShowPlay){
  9787. this.isShowEdit = false
  9788. }
  9789. })
  9790. }
  9791. .margin({
  9792. left: 38,
  9793. right: 38,
  9794. top: 10,
  9795. bottom: 10
  9796. })
  9797. .width(250)
  9798. .height(60)
  9799. }
  9800. }
  9801. .margin({ bottom: 20 })
  9802. }
  9803. setEditStrEmpty(){
  9804. this.imagePathStr = ''
  9805. this.lyricConStr = ''
  9806. this.artistStr = ''
  9807. this.titleStr = ''
  9808. this.ablumStr = ''
  9809. this.genreStr = ''
  9810. this.yearStr = ''
  9811. this.trackStr = ''
  9812. this.albumArtistStr = ''
  9813. this.composerStr = ''
  9814. this.lyricistStr = ''
  9815. this.commentStr = ''
  9816. this.discStr = ''
  9817. }
  9818. initEditFields(item?: VideoItem) {
  9819. if (!item) {
  9820. this.setEditStrEmpty()
  9821. return
  9822. }
  9823. this.imagePathStr = ''
  9824. this.titleStr = item.name ?? ''
  9825. this.artistStr = item.artist ?? ''
  9826. this.ablumStr = item.album ?? ''
  9827. this.genreStr = item.genre ?? ''
  9828. this.yearStr = item.year ?? ''
  9829. this.trackStr = item.track ?? ''
  9830. this.albumArtistStr = item.ALBUMARTIST ?? ''
  9831. this.composerStr = item.COMPOSER ?? ''
  9832. this.lyricistStr = item.LYRICIST ?? ''
  9833. this.commentStr = item.COMMENT ?? ''
  9834. this.discStr = item.disc ?? ''
  9835. this.lyricConStr = item.lyricContent ?? ''
  9836. }
  9837. private syncEditedFields(target?: VideoItem) {
  9838. if (!target) {
  9839. return
  9840. }
  9841. target.name = this.titleStr
  9842. target.artist = this.artistStr
  9843. target.album = this.ablumStr
  9844. target.lyricContent = this.lyricConStr
  9845. target.year = this.yearStr
  9846. target.genre = this.genreStr
  9847. target.track = this.trackStr
  9848. target.ALBUMARTIST = this.albumArtistStr
  9849. target.COMPOSER = this.composerStr
  9850. target.LYRICIST = this.lyricistStr
  9851. target.COMMENT = this.commentStr
  9852. target.disc = this.discStr
  9853. }
  9854. private replaceItemInList(list: Array<VideoItem> | undefined, filePath: string,
  9855. apply?: (next: Array<VideoItem>) => void) {
  9856. if (!list || ArrayUtil.isEmpty(list)) {
  9857. return
  9858. }
  9859. const index = list.findIndex((video: VideoItem) => video.filePath === filePath)
  9860. if (index < 0) {
  9861. return
  9862. }
  9863. const nextList = [...list]
  9864. this.syncEditedFields(nextList[index])
  9865. apply?.(nextList)
  9866. }
  9867. private syncListsAfterEdit(filePath: string) {
  9868. this.replaceItemInList(this.videoLocalList, filePath, (next: Array<VideoItem>) => {
  9869. this.videoLocalList = next
  9870. this.dataSource.pushArrayData(next)
  9871. })
  9872. this.replaceItemInList(this.songList, filePath, (next: Array<VideoItem>) => {
  9873. this.songList = next
  9874. this.sonDataSource.pushArrayData(next)
  9875. })
  9876. this.replaceItemInList(this.favList, filePath, (next: Array<VideoItem>) => {
  9877. this.favList = next
  9878. })
  9879. this.replaceItemInList(this.historyList, filePath, (next: Array<VideoItem>) => {
  9880. this.historyList = next
  9881. })
  9882. this.replaceItemInList(this.currentSongList, filePath, (next: Array<VideoItem>) => {
  9883. this.currentSongList = next
  9884. })
  9885. this.replaceItemInList(this.mediaKuList, filePath, (next: Array<VideoItem>) => {
  9886. this.mediaKuList = next
  9887. })
  9888. this.replaceItemInList(this.filteredList, filePath, (next: Array<VideoItem>) => {
  9889. this.filteredList = next
  9890. })
  9891. this.replaceItemInList(this.artistList, filePath, (next: Array<VideoItem>) => {
  9892. this.artistList = next
  9893. })
  9894. this.replaceItemInList(this.albumList, filePath, (next: Array<VideoItem>) => {
  9895. this.albumList = next
  9896. })
  9897. this.listRefreshKey++
  9898. }
  9899. private refreshLazyListViews(mainListUpdated: boolean, playlistUpdated: boolean): void {
  9900. if (!mainListUpdated && !playlistUpdated) {
  9901. return;
  9902. }
  9903. this.listRefreshKey++;
  9904. if (mainListUpdated) {
  9905. this.dataSource.notifyDataReload();
  9906. }
  9907. if (playlistUpdated) {
  9908. this.sonDataSource.notifyDataReload();
  9909. }
  9910. }
  9911. @Builder
  9912. detailSheet(item:VideoItem) {
  9913. Scroll() {
  9914. Column() {
  9915. this.songDetail(item)
  9916. }
  9917. }
  9918. .width('100%')
  9919. .height('100%')
  9920. }
  9921. @Builder
  9922. songDetail(currentItem:VideoItem) {
  9923. Column() {
  9924. if (currentItem) {
  9925. Row() {
  9926. Stack() {
  9927. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.alt') :
  9928. currentItem.pixelMapPath)
  9929. .fillColor(this.themeColor)
  9930. .height(80)
  9931. .width(80)
  9932. .borderRadius(10)
  9933. .opacity(this.opacityItem)// 绑定透明度
  9934. .margin({ left: 22 })
  9935. }
  9936. Column() {
  9937. Column() {
  9938. Text(currentItem.name)
  9939. .fontSize(16)
  9940. .maxLines(1)
  9941. .animation({
  9942. duration: 555,
  9943. curve: 'Linear',
  9944. })
  9945. .fontColor($r('app.color.text_color'))
  9946. .margin({ left: 15 })
  9947. }
  9948. .height('100%')
  9949. .width('100%')
  9950. .justifyContent(FlexAlign.Center)
  9951. .alignItems(HorizontalAlign.Start)
  9952. }
  9953. .height('100%')
  9954. }
  9955. .width('100%')
  9956. .height(90)
  9957. .justifyContent(FlexAlign.SpaceBetween)
  9958. Row() {
  9959. Text('艺术家:')
  9960. .fontSize(14)
  9961. .fontColor($r('app.color.text_color'))
  9962. .margin({ left: 22 })
  9963. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  9964. .fontSize(14)
  9965. .fontColor($r('app.color.text_color'))
  9966. .margin({ left: 10 })
  9967. .layoutWeight(1)
  9968. }
  9969. .width('100%')
  9970. .margin({ top: 10, bottom: 10 })
  9971. .justifyContent(FlexAlign.Start)
  9972. Row() {
  9973. Text('专辑名:')
  9974. .fontSize(14)
  9975. .fontColor($r('app.color.text_color'))
  9976. .margin({ left: 22 })
  9977. Text(currentItem?.album ?currentItem.album : '未知专辑')
  9978. .fontSize(14)
  9979. .margin({ left: 10 })
  9980. .fontColor($r('app.color.text_color'))
  9981. .layoutWeight(1)
  9982. }
  9983. .width('100%')
  9984. .margin({ top: 10, bottom: 10 })
  9985. .justifyContent(FlexAlign.Start)
  9986. Row() {
  9987. Text('时长:')
  9988. .fontSize(14)
  9989. .fontColor($r('app.color.text_color'))
  9990. .margin({ left: 22 })
  9991. Text(StrUtil.isEmpty(currentItem.duration)?
  9992. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  9993. .fontSize(14)
  9994. .margin({ left: 10 })
  9995. .fontColor($r('app.color.text_color'))
  9996. .layoutWeight(1)
  9997. }
  9998. .width('100%')
  9999. .margin({ top: 10, bottom: 10 })
  10000. .justifyContent(FlexAlign.Start)
  10001. Row() {
  10002. Text('采样率:')
  10003. .fontSize(14)
  10004. .fontColor($r('app.color.text_color'))
  10005. .margin({ left: 22 })
  10006. Text(Utility.convertToKHz(currentItem.sampleRate))
  10007. .fontSize(14)
  10008. .margin({ left: 10 })
  10009. .fontColor($r('app.color.text_color'))
  10010. .layoutWeight(1)
  10011. }
  10012. .width('100%')
  10013. .margin({ top: 10, bottom: 10 })
  10014. .justifyContent(FlexAlign.Start)
  10015. Row() {
  10016. Text('比特率:')
  10017. .fontSize(14)
  10018. .fontColor($r('app.color.text_color'))
  10019. .margin({ left: 22 })
  10020. Text(currentItem.bit_rate)
  10021. .fontSize(14)
  10022. .margin({ left: 10 })
  10023. .fontColor($r('app.color.text_color'))
  10024. .layoutWeight(1)
  10025. }
  10026. .width('100%')
  10027. .margin({ top: 10, bottom: 10 })
  10028. .justifyContent(FlexAlign.Start)
  10029. Row() {
  10030. Text('位深:')
  10031. .fontSize(14)
  10032. .fontColor($r('app.color.text_color'))
  10033. .margin({ left: 22 })
  10034. Text(`${currentItem.bits_per_raw_sample} bits`)
  10035. .fontSize(14)
  10036. .margin({ left: 10 })
  10037. .fontColor($r('app.color.text_color'))
  10038. .layoutWeight(1)
  10039. }
  10040. .width('100%')
  10041. .margin({ top: 10, bottom: 10 })
  10042. .justifyContent(FlexAlign.Start)
  10043. Row() {
  10044. Text('声道:')
  10045. .fontSize(14)
  10046. .fontColor($r('app.color.text_color'))
  10047. .margin({ left: 22 })
  10048. Text(`${currentItem.channels}`)
  10049. .fontSize(14)
  10050. .margin({ left: 10 })
  10051. .fontColor($r('app.color.text_color'))
  10052. .layoutWeight(1)
  10053. }
  10054. .width('100%')
  10055. .margin({ top: 10, bottom: 10 })
  10056. .justifyContent(FlexAlign.Start)
  10057. Row() {
  10058. Text('声道布局:')
  10059. .fontSize(14)
  10060. .fontColor($r('app.color.text_color'))
  10061. .margin({ left: 22 })
  10062. Text(`${currentItem.channel_layout}`)
  10063. .fontSize(14)
  10064. .margin({ left: 10 })
  10065. .fontColor($r('app.color.text_color'))
  10066. .layoutWeight(1)
  10067. }
  10068. .width('100%')
  10069. .margin({ top: 10, bottom: 10 })
  10070. .justifyContent(FlexAlign.Start)
  10071. Row() {
  10072. Text('起始播放点:')
  10073. .fontSize(14)
  10074. .fontColor($r('app.color.text_color'))
  10075. .margin({ left: 22 })
  10076. Text(`${currentItem.start_time}`)
  10077. .fontSize(14)
  10078. .margin({ left: 10 })
  10079. .fontColor($r('app.color.text_color'))
  10080. .layoutWeight(1)
  10081. }
  10082. .width('100%')
  10083. .margin({ top: 10, bottom: 10 })
  10084. .justifyContent(FlexAlign.Start)
  10085. Row() {
  10086. Text('风格:')
  10087. .fontSize(14)
  10088. .fontColor($r('app.color.text_color'))
  10089. .margin({ left: 22 })
  10090. Text(currentItem.genre)
  10091. .fontSize(14)
  10092. .margin({ left: 10 })
  10093. .fontColor($r('app.color.text_color'))
  10094. .layoutWeight(1)
  10095. }
  10096. .width('100%')
  10097. .margin({ top: 10, bottom: 10 })
  10098. .justifyContent(FlexAlign.Start)
  10099. Row() {
  10100. Text('发行时间:')
  10101. .fontSize(14)
  10102. .fontColor($r('app.color.text_color'))
  10103. .margin({ left: 22 })
  10104. Text(currentItem.year)
  10105. .fontSize(14)
  10106. .margin({ left: 10 })
  10107. .fontColor($r('app.color.text_color'))
  10108. .layoutWeight(1)
  10109. }
  10110. .width('100%')
  10111. .margin({ top: 10, bottom: 10 })
  10112. .justifyContent(FlexAlign.Start)
  10113. Row() {
  10114. Text('质量评分:')
  10115. .fontSize(14)
  10116. .fontColor($r('app.color.text_color'))
  10117. .margin({ left: 22 })
  10118. Text(currentItem.probe_score+"")
  10119. .fontSize(14)
  10120. .margin({ left: 10 })
  10121. .fontColor($r('app.color.text_color'))
  10122. .layoutWeight(1)
  10123. }
  10124. .width('100%')
  10125. .margin({ top: 10, bottom: 10 })
  10126. .justifyContent(FlexAlign.Start)
  10127. Row() {
  10128. Text('音轨号:')
  10129. .fontSize(14)
  10130. .fontColor($r('app.color.text_color'))
  10131. .margin({ left: 22 })
  10132. Text(currentItem.track)
  10133. .fontSize(14)
  10134. .margin({ left: 10 })
  10135. .fontColor($r('app.color.text_color'))
  10136. .layoutWeight(1)
  10137. }
  10138. .width('100%')
  10139. .margin({ top: 10, bottom: 10 })
  10140. .justifyContent(FlexAlign.Start)
  10141. Row() {
  10142. Text('碟号:')
  10143. .fontSize(14)
  10144. .fontColor($r('app.color.text_color'))
  10145. .margin({ left: 22 })
  10146. Text(currentItem.disc)
  10147. .fontSize(14)
  10148. .margin({ left: 10 })
  10149. .fontColor($r('app.color.text_color'))
  10150. .layoutWeight(1)
  10151. }
  10152. .width('100%')
  10153. .margin({ top: 10, bottom: 10 })
  10154. .justifyContent(FlexAlign.Start)
  10155. Row() {
  10156. Text('专辑艺术家:')
  10157. .fontSize(14)
  10158. .fontColor($r('app.color.text_color'))
  10159. .margin({ left: 22 })
  10160. Text(currentItem.ALBUMARTIST)
  10161. .fontSize(14)
  10162. .margin({ left: 10 })
  10163. .fontColor($r('app.color.text_color'))
  10164. .layoutWeight(1)
  10165. }
  10166. .width('100%')
  10167. .margin({ top: 10, bottom: 10 })
  10168. .justifyContent(FlexAlign.Start)
  10169. Row() {
  10170. Text('作曲家:')
  10171. .fontSize(14)
  10172. .fontColor($r('app.color.text_color'))
  10173. .margin({ left: 22 })
  10174. Text(currentItem.COMPOSER)
  10175. .fontSize(14)
  10176. .margin({ left: 10 })
  10177. .fontColor($r('app.color.text_color'))
  10178. .layoutWeight(1)
  10179. }
  10180. .width('100%')
  10181. .margin({ top: 10, bottom: 10 })
  10182. .justifyContent(FlexAlign.Start)
  10183. Row() {
  10184. Text('作词家:')
  10185. .fontSize(14)
  10186. .fontColor($r('app.color.text_color'))
  10187. .margin({ left: 22 })
  10188. Text(currentItem.LYRICIST)
  10189. .fontSize(14)
  10190. .margin({ left: 10 })
  10191. .fontColor($r('app.color.text_color'))
  10192. .layoutWeight(1)
  10193. }
  10194. .width('100%')
  10195. .margin({ top: 10, bottom: 10 })
  10196. .justifyContent(FlexAlign.Start)
  10197. Row() {
  10198. Text('注释:')
  10199. .fontSize(14)
  10200. .fontColor($r('app.color.text_color'))
  10201. .margin({ left: 22 })
  10202. Text(currentItem.COMMENT)
  10203. .fontSize(14)
  10204. .margin({ left: 10 })
  10205. .fontColor($r('app.color.text_color'))
  10206. .layoutWeight(1)
  10207. }
  10208. .width('100%')
  10209. .margin({ top: 10, bottom: 10 })
  10210. .justifyContent(FlexAlign.Start)
  10211. Row() {
  10212. Text('格式:')
  10213. .fontSize(14)
  10214. .fontColor($r('app.color.text_color'))
  10215. .margin({ left: 22 })
  10216. Text(Utility.formatMimeType(currentItem.mimeType))
  10217. .fontSize(14)
  10218. .margin({ left: 10 })
  10219. .fontColor($r('app.color.text_color'))
  10220. .layoutWeight(1)
  10221. }
  10222. .width('100%')
  10223. .margin({ top: 10, bottom: 10 })
  10224. .justifyContent(FlexAlign.Start)
  10225. Row() {
  10226. Text('播放次数:')
  10227. .fontSize(14)
  10228. .fontColor($r('app.color.text_color'))
  10229. .margin({ left: 22 })
  10230. Text(currentItem.playCount?.toString())
  10231. .fontSize(14)
  10232. .margin({ left: 10 })
  10233. .fontColor($r('app.color.text_color'))
  10234. .layoutWeight(1)
  10235. }
  10236. .width('100%')
  10237. .margin({ top: 10, bottom: 10 })
  10238. .justifyContent(FlexAlign.Start)
  10239. Row() {
  10240. Text('流数量:')
  10241. .fontSize(14)
  10242. .fontColor($r('app.color.text_color'))
  10243. .margin({ left: 22 })
  10244. Text(currentItem.nb_streams?.toString())
  10245. .fontSize(14)
  10246. .margin({ left: 10 })
  10247. .fontColor($r('app.color.text_color'))
  10248. .layoutWeight(1)
  10249. }
  10250. .width('100%')
  10251. .margin({ top: 10, bottom: 10 })
  10252. .justifyContent(FlexAlign.Start)
  10253. Row() {
  10254. Text('文件大小:')
  10255. .fontSize(14)
  10256. .fontColor($r('app.color.text_color'))
  10257. .margin({ left: 22 })
  10258. Text(currentItem.size)
  10259. .fontSize(14)
  10260. .margin({ left: 10 })
  10261. .fontColor($r('app.color.text_color'))
  10262. .layoutWeight(1)
  10263. }
  10264. .width('100%')
  10265. .margin({ top: 10, bottom: 10 })
  10266. .justifyContent(FlexAlign.Start)
  10267. Row() {
  10268. Text('文件名:')
  10269. .fontSize(14)
  10270. .fontColor($r('app.color.text_color'))
  10271. .margin({ left: 22 })
  10272. Text(currentItem.fileName)
  10273. .fontSize(14)
  10274. .margin({ left: 10 })
  10275. .fontColor($r('app.color.text_color'))
  10276. .layoutWeight(1)
  10277. }
  10278. .width('100%')
  10279. .margin({ top: 10, bottom: 10 })
  10280. .justifyContent(FlexAlign.Start)
  10281. Row() {
  10282. Text('修改时间:')
  10283. .fontSize(14)
  10284. .fontColor($r('app.color.text_color'))
  10285. .margin({ left: 22 })
  10286. Text(currentItem.cTime)
  10287. .fontSize(14)
  10288. .margin({ left: 10 })
  10289. .fontColor($r('app.color.text_color'))
  10290. .layoutWeight(1)
  10291. }
  10292. .width('100%')
  10293. .margin({ top: 10, bottom: 10 })
  10294. .justifyContent(FlexAlign.Start)
  10295. Row() {
  10296. Text('存放目录:')
  10297. .fontSize(14)
  10298. .fontColor($r('app.color.text_color'))
  10299. .margin({ left: 22 })
  10300. Text(currentItem.filePath)
  10301. .fontSize(12)
  10302. .margin({ left: 10 })
  10303. .fontColor($r('app.color.text_color'))
  10304. .layoutWeight(1)
  10305. }
  10306. .margin({ top: 10, bottom: 10 })
  10307. .width('100%')
  10308. .justifyContent(FlexAlign.Start)
  10309. Row() {
  10310. Text('内嵌歌词:')
  10311. .fontSize(14)
  10312. .fontColor($r('app.color.text_color'))
  10313. .margin({ left: 22 })
  10314. Text(currentItem.lyricContent)
  10315. .fontSize(12)
  10316. .copyOption(CopyOptions.InApp)
  10317. .margin({ left: 10 })
  10318. .fontColor($r('app.color.text_color'))
  10319. .layoutWeight(1)
  10320. }
  10321. .margin({ top: 10, bottom: 10 })
  10322. .width('100%')
  10323. .justifyContent(FlexAlign.Start)
  10324. }
  10325. }
  10326. .margin({ bottom: 20 })
  10327. }
  10328. //定时关闭布局
  10329. @Builder
  10330. TimeCloseSheet() {
  10331. Scroll() {
  10332. Column() {
  10333. this.TimeClose()
  10334. }
  10335. }
  10336. .width('100%')
  10337. .height('100%')
  10338. }
  10339. //倒计时关闭音乐,退出App功能实现。
  10340. @State selectedMinutes: number = 0 // 0表示未开启
  10341. @State remainingSeconds: number = 0
  10342. // 预设时间选项
  10343. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  10344. private formatTime(seconds: number): string {
  10345. const mins = Math.floor(seconds / 60)
  10346. const secs = seconds % 60
  10347. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  10348. }
  10349. // 开始倒计时
  10350. private handleTimeSelect(minutes: number) {
  10351. if (minutes === this.selectedMinutes) {
  10352. this.stopCountdown();
  10353. this.selectedMinutes = 0;
  10354. return;
  10355. }
  10356. this.selectedMinutes = minutes;
  10357. this.remainingSeconds = minutes * 60;
  10358. this.startCountdown(); // 新增调用
  10359. }
  10360. @Builder
  10361. TimeClose() {
  10362. Column() {
  10363. // 倒计时显示区域
  10364. Text(this.selectedMinutes > 0 ?
  10365. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  10366. "定时关闭未开启")
  10367. .fontSize(17)
  10368. .fontColor($r('app.color.text_color'))
  10369. .margin({ top: 2, bottom: 8 });
  10370. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  10371. ForEach(this.presetTimes, (minutes: number, index: number) => {
  10372. // 单行时间选项容器
  10373. Row() {
  10374. // 文字描述区域
  10375. Text(this.getDisplayText(minutes))
  10376. .fontSize(15)
  10377. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  10378. $r('app.color.text_color'))// 选中态颜色变化
  10379. .textAlign(TextAlign.Start)
  10380. .layoutWeight(1); // 占据剩余空间
  10381. // 复选框样式的选择器
  10382. Row() {
  10383. if (minutes === this.selectedMinutes) {
  10384. // 选中状态 - 带勾号的圆形复选框
  10385. Row() {
  10386. // 使用系统内置的勾号图标
  10387. Image($r('sys.media.ohos_ic_public_ok'))
  10388. .width(14)
  10389. .height(14)
  10390. .fillColor(Color.White)
  10391. }
  10392. .width(24)
  10393. .height(24)
  10394. .borderRadius(12)
  10395. .backgroundColor(this.themeColor)
  10396. .justifyContent(FlexAlign.Center)
  10397. .alignItems(VerticalAlign.Center)
  10398. } else {
  10399. // 未选中状态的圆形边框
  10400. Row()
  10401. .width(24)
  10402. .height(24)
  10403. .borderRadius(12)
  10404. .border({
  10405. width: 2,
  10406. color: $r('app.color.text_color'),
  10407. style: BorderStyle.Solid
  10408. })
  10409. .backgroundColor(Color.Transparent)
  10410. }
  10411. }
  10412. .width(24)
  10413. .height(24)
  10414. .margin({ left: 20 })
  10415. .justifyContent(FlexAlign.Center)
  10416. .alignItems(VerticalAlign.Center)
  10417. }
  10418. .width('100%')
  10419. .padding({
  10420. top: 18,
  10421. bottom: 18,
  10422. left: 18,
  10423. right: 18
  10424. })
  10425. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  10426. $r('app.color.bottom_control_background')) // 选中背景高亮
  10427. .borderRadius(12)
  10428. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10429. .margin({ bottom: 18 })
  10430. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  10431. });
  10432. }
  10433. .width('100%')
  10434. .padding(16)
  10435. }
  10436. }
  10437. // 获取显示文本
  10438. private getDisplayText(minutes: number): string {
  10439. if (minutes === -1) {
  10440. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  10441. }
  10442. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  10443. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  10444. }
  10445. // 处理选择事件
  10446. private handleSelect(minutes: number): void {
  10447. if (minutes === -1) { // 自定义
  10448. // 弹出自定义时间对话框
  10449. DialogHelper.showTextInputDialog({
  10450. title: '自定义时间',
  10451. maskColor: Color.Transparent,
  10452. inputType: InputType.Number,
  10453. text: '',
  10454. onChange: (text) => {
  10455. console.error("onChange: " + text);
  10456. },
  10457. onAction: (action, dialogId, content) => {
  10458. if (action == DialogAction.TWO) {
  10459. const customMinutes = Number(content);
  10460. if (customMinutes > 0) {
  10461. this.handleTimeSelect(customMinutes); // 设置自定义时间
  10462. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  10463. }
  10464. }
  10465. }
  10466. });
  10467. } else {
  10468. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  10469. }
  10470. }
  10471. // 添加定时器引用
  10472. private timerId: number = -1;
  10473. // 启动/重置倒计时
  10474. private startCountdown() {
  10475. // 清除旧定时器
  10476. if (this.timerId !== -1) {
  10477. clearInterval(this.timerId);
  10478. }
  10479. // 创建新定时器
  10480. if (this.selectedMinutes > 0) {
  10481. this.timerId = setInterval(() => {
  10482. if (this.remainingSeconds === 15) {
  10483. this.showConfirmationDialog();
  10484. }
  10485. if (this.remainingSeconds > 0) {
  10486. this.remainingSeconds -= 1;
  10487. } else {
  10488. this.stopCountdown();
  10489. this.handleTimeout();
  10490. }
  10491. }, 1000);
  10492. }
  10493. }
  10494. // 15倒计时后再次提示显示确认是否关闭App对话框
  10495. private showConfirmationDialog() {
  10496. DialogHelper.showAlertDialog({
  10497. backgroundColor: $r('app.color.btn_green'),
  10498. title: '确认关闭',
  10499. maskColor: Color.Transparent,
  10500. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  10501. borderStyle: BorderStyle.Dashed,
  10502. primaryButton: '暂不关闭',
  10503. secondaryButton: '确定',
  10504. onAction: (action) => {
  10505. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  10506. this.stopCountdown();
  10507. this.selectedMinutes = 0
  10508. } else if (action == DialogAction.TWO) {
  10509. }
  10510. }
  10511. })
  10512. }
  10513. // 停止倒计时
  10514. private stopCountdown() {
  10515. if (this.timerId !== -1) {
  10516. clearInterval(this.timerId);
  10517. this.timerId = -1;
  10518. }
  10519. }
  10520. // 超时处理
  10521. private handleTimeout() {
  10522. // 执行播放器关闭逻辑
  10523. this.selectedMinutes = 0;
  10524. ToastUtil.showToast(" 定时关闭已完成");
  10525. this.stop(); // 假设存在的播放器实例
  10526. //退出APP
  10527. const mContext = getContext(this) as common.UIAbilityContext
  10528. mContext.terminateSelf();
  10529. AvSessionController.getInstance(true).unregisterSessionListener()
  10530. }
  10531. //倒计时关闭音乐,退出App功能实现结束。
  10532. //播放列表的拖动List 重新排序
  10533. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  10534. //左滑操作 移动文件 重命名 删除等操作
  10535. @Builder
  10536. sonButton(item: VideoItem, index: number, filePath: string) {
  10537. Row() {
  10538. //加入下一首播放
  10539. Button() {
  10540. Image($r('app.media.next_to_play'))
  10541. .fillColor(Color.White)
  10542. .width(20)
  10543. }
  10544. .width(40)
  10545. .height(40)
  10546. .type(ButtonType.Circle)
  10547. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  10548. .backgroundColor(this.themeColor)
  10549. .margin(5)
  10550. .onClick(() => {
  10551. this.addToNextPlay(item);
  10552. })
  10553. Button() {
  10554. Image($r('app.media.close'))
  10555. .fillColor(Color.White)
  10556. .width(20)
  10557. }
  10558. .width(40)
  10559. .height(40)
  10560. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  10561. .type(ButtonType.Circle)
  10562. .backgroundColor(this.themeColor)
  10563. .margin(5)
  10564. .onClick(() => {
  10565. this.songList.splice(Number(index), 1)
  10566. this.sonDataSource.pushArrayData(this.songList)
  10567. })
  10568. Button() {
  10569. Image($r('app.media.share2'))
  10570. .fillColor(Color.White)
  10571. .width(20)
  10572. }
  10573. .width(40)
  10574. .height(40)
  10575. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  10576. .type(ButtonType.Circle)
  10577. .backgroundColor(this.themeColor)
  10578. .margin(5)
  10579. .onClick(() => {
  10580. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  10581. })
  10582. }
  10583. }
  10584. itemMoveSon(index: number, newIndex: number): void {
  10585. if (newIndex < 0 || newIndex >= this.songList.length) {
  10586. return;
  10587. }
  10588. let tmp = this.songList.splice(index, 1);
  10589. this.songList.splice(newIndex, 0, tmp[0]);
  10590. this.sonDataSource.pushArrayData(this.songList)
  10591. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  10592. if(this.modeType==4&&this.playlistTable){
  10593. updateAllSongsSortOrder(this.playlistTable, this.songList,this.currentSongListID)
  10594. }
  10595. }
  10596. @Builder
  10597. PlayList() {
  10598. List({ scroller: this.playListScroller }) {
  10599. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  10600. ListItem() {
  10601. this.MusicItemSon(item, index)
  10602. }
  10603. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  10604. .animation({
  10605. duration: 666,
  10606. curve: 'ease-in-out' // 可选动画曲线
  10607. })
  10608. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 600 }),
  10609. // TransitionEffect.scale({ x: 0, y: 0 })))
  10610. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  10611. //拖动List关键代码开始
  10612. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  10613. .zIndex(this.dragItem === index ? 1 : 0)
  10614. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  10615. .gesture(
  10616. GestureGroup(GestureMode.Sequence,
  10617. LongPressGesture({ repeat: true })
  10618. .onAction((event?: GestureEvent) => {
  10619. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  10620. this.scaleItem = index
  10621. })
  10622. })
  10623. .onActionEnd(() => {
  10624. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  10625. this.scaleItem = -1
  10626. })
  10627. }),
  10628. PanGesture({ fingers: 1, direction: null, distance: 0 })
  10629. .onActionStart(() => {
  10630. this.dragItem = index // 记录当前拖动项索引
  10631. this.dragRefOffset = 0 // 重置偏移基准
  10632. })
  10633. .onActionUpdate((event: GestureEvent) => {
  10634. this.offsetY = event.offsetY - this.dragRefOffset;
  10635. this.neighborItem = -1;
  10636. let indexA = this.songList.indexOf(item);
  10637. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  10638. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  10639. let value: number = 0;
  10640. if (this.offsetY < 0) {
  10641. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  10642. this.neighborItem = indexA - 1;
  10643. this.neighborScale = 1 - value / 20;
  10644. } else if (this.offsetY > 0) {
  10645. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  10646. this.neighborItem = indexA + 1;
  10647. this.neighborScale = 1 - value / 20;
  10648. }
  10649. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  10650. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  10651. this.offsetY -= this.ITEM_INTV;
  10652. this.dragRefOffset += this.ITEM_INTV;
  10653. this.itemMoveSon(indexA, indexA + 1);
  10654. });
  10655. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  10656. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  10657. this.offsetY += this.ITEM_INTV;
  10658. this.dragRefOffset -= this.ITEM_INTV;
  10659. this.itemMoveSon(indexA, indexA - 1);
  10660. });
  10661. }
  10662. })
  10663. .onActionEnd((event: GestureEvent) => {
  10664. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  10665. this.dragItem = -1
  10666. this.neighborItem = -1
  10667. })
  10668. animateTo({
  10669. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  10670. }, () => {
  10671. this.scaleItem = -1
  10672. })
  10673. })
  10674. )
  10675. .onCancel(() => {
  10676. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  10677. this.dragItem = -1
  10678. this.neighborItem = -1
  10679. })
  10680. animateTo({
  10681. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  10682. }, () => {
  10683. this.scaleItem = -1
  10684. })
  10685. })
  10686. ) //拖动List关键代码结束
  10687. .onClick(() => {
  10688. this.doPlay(item, index, true)
  10689. })
  10690. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  10691. }
  10692. .width('100%')
  10693. .height('100%')
  10694. .onReachEnd(() => {
  10695. if(this.modeType === 4 )
  10696. return;
  10697. // 检测是否是流媒体类型(Navidrome/Jellyfin/Emby/AudioStation/Plex),如果是则调用网盘加载更多逻辑
  10698. const isStreamingSong = this.currentSong && (
  10699. isNavidromeType(this.currentSong.type) ||
  10700. isJellyfinType(this.currentSong.type) ||
  10701. isEmbyType(this.currentSong.type) ||
  10702. isAudioStationType(this.currentSong.type) ||
  10703. isPlexType(this.currentSong.type)
  10704. );
  10705. if (isStreamingSong && hasMoreData()) {
  10706. Logger.info('heanup', '播放列表滚动到底部,加载更多流媒体歌曲');
  10707. void this.loadMoreNavidromeSongs();
  10708. } else {
  10709. void this.tryLoadNextPageForPlayback();
  10710. }
  10711. })
  10712. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  10713. // .animation({ duration: 500, curve: Curve.Ease }))
  10714. .cachedCount(10)
  10715. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  10716. .gesture(PinchGesture({ fingers: 2 })
  10717. .onActionEnd((event: GestureEvent) => {
  10718. this.setSonListTwoFingers()
  10719. })
  10720. .onActionUpdate(e => {
  10721. this.scaleValue = this.pinchValue * e.scale
  10722. })
  10723. .onActionStart(e => {
  10724. }))
  10725. .padding({
  10726. bottom: 0
  10727. })
  10728. }
  10729. setSonListTwoFingers() {
  10730. this.pinchValue = this.scaleValue;
  10731. Logger.info('this.pinchValue = ' + this.pinchValue);
  10732. if (this.pinchValue >= 1) {
  10733. this.sonTwoFingerType++
  10734. Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
  10735. if (this.sonTwoFingerType > 3) {
  10736. this.sonTwoFingerType = 1
  10737. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  10738. }
  10739. } else {
  10740. this.sonTwoFingerType--
  10741. Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
  10742. if (this.sonTwoFingerType < 1) {
  10743. this.sonTwoFingerType = 1
  10744. }
  10745. }
  10746. PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
  10747. this.pinchValue = 1;
  10748. this.scaleValue = 1;
  10749. }
  10750. @State sonTwoFingerType:number = 3
  10751. @Builder
  10752. private MusicItemSon(item: VideoItem, index?: number) {
  10753. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10754. Row() {
  10755. Stack() {
  10756. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  10757. .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  10758. .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  10759. .alt($r('app.media.alt'))
  10760. .fillColor(this.themeColor)
  10761. .borderRadius(this.isCoverRectangle?11:'100%')
  10762. .clip(true)
  10763. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  10764. .draggable(false)// 禁止长按手势拖动
  10765. .autoResize(true) // 重采样,可减少内存占用
  10766. .margin({ left: 20 })
  10767. }
  10768. .width('15%')
  10769. Column() {
  10770. Column() {
  10771. Text(this.isShowFileName?item.fileName :item.name)
  10772. .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
  10773. .fontColor(this.curIndex === index ? this.themeColor :
  10774. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  10775. .maxLines(1)
  10776. .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
  10777. Row() {
  10778. Column(){
  10779. Text(item.md5Str?.includes('Lossless')?
  10780. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  10781. .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
  10782. .padding({ top: 3,right:6,left:6,bottom:3 })
  10783. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  10784. $r('app.color.text_color'))
  10785. .fontWeight(500)
  10786. .borderRadius(12)
  10787. .visibility(StrUtil.isEmpty(item.md5Str) ? Visibility.None : Visibility.Visible)
  10788. .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
  10789. .backgroundColor('#FFC107')
  10790. }
  10791. .padding({ top: 8 })
  10792. Text(StrUtil.isEmpty(item.artist) ? item.duration :
  10793. item.artist + ' ' + item?.duration)
  10794. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  10795. .padding({ top: 8 })
  10796. .maxLines(1)
  10797. .fontColor(this.curIndex === index ? this.themeColor :
  10798. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  10799. .margin({ left: StrUtil.isEmpty(item.md5Str)? 12 :this.sonTwoFingerType == 3 ? 5 : 3 })
  10800. Blank()
  10801. Text(item.size)
  10802. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  10803. .padding({ top: 8 })
  10804. .maxLines(1)
  10805. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  10806. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  10807. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  10808. .margin({ left: 10 })
  10809. }
  10810. }
  10811. .height('100%')
  10812. .width('100%')
  10813. .justifyContent(FlexAlign.Center)
  10814. .alignItems(HorizontalAlign.Start)
  10815. }
  10816. .height('100%')
  10817. .width('65%')
  10818. Column() {
  10819. PlayingIndicator({
  10820. isActive: this.videoUrl === item.filePath && !this.isMultiSelect,
  10821. indicatorSize: 18
  10822. })
  10823. }
  10824. .width('20%')
  10825. }
  10826. }
  10827. .backgroundColor(Color.Transparent)
  10828. .width('100%')
  10829. .reuseId('son_item')
  10830. .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
  10831. .shadow(this.scaleItem === index ? {
  10832. radius: 70,
  10833. color: '#15000000',
  10834. offsetX: 0,
  10835. offsetY: 0
  10836. } :
  10837. {
  10838. radius: 0,
  10839. color: '#15000000',
  10840. offsetX: 0,
  10841. offsetY: 0
  10842. })
  10843. .animation({ curve: Curve.Sharp, duration: 300 })
  10844. }
  10845. @Builder
  10846. MusicPlayBuilder() {
  10847. Column() {
  10848. this.IjkMusicPlayerView()
  10849. }
  10850. .transition(TransitionEffect.asymmetric(
  10851. TransitionEffect.opacity(1),
  10852. TransitionEffect.OPACITY
  10853. ))
  10854. .visualEffect(deviceInfo.sdkApiVersion>=20&&this.bgController?
  10855. new hdsEffect.HdsEffectBuilder()
  10856. .shaderEffect({
  10857. effectType: hdsEffect.EffectType.UV_BACKGROUND_FLOW_LIGHT,
  10858. animation: {
  10859. duration: 10000,
  10860. iterations: -1,
  10861. autoPlay: true,
  10862. onFinish: ()=> {
  10863. console.info('Succeeded in finishing');
  10864. }
  10865. },
  10866. controller: this.bgController,
  10867. })
  10868. .buildEffect():null)
  10869. .height('100%')
  10870. .width('100%')
  10871. .onDisAppear(() => {
  10872. this.translateY = 0;
  10873. this.playDragUiOpacity = 1
  10874. })
  10875. .translate({ y: this.translateY })
  10876. .gesture(
  10877. PanGesture(this.panOption)
  10878. .onActionUpdate((event?: GestureEvent) => {
  10879. if (event) {
  10880. // 判断滑动方向
  10881. const offsetY = event.offsetY ?? 0;
  10882. const isSwipeUp = offsetY < 0;
  10883. if (isSwipeUp) {
  10884. // 向上滑动:不应用位移动画,保持 translateY = 0
  10885. this.translateY = 0;
  10886. this.scaleValueImage = 1
  10887. this.scaleValueText = 1
  10888. this.playDragUiOpacity = 1
  10889. } else {
  10890. if(this.isGeKongPlayNext){
  10891. return
  10892. }
  10893. // 向下滑动:应用位移动画
  10894. this.translateY = offsetY;
  10895. // 向下滑动时的缩放效果
  10896. this.getUIContext().animateTo({
  10897. duration: 500,
  10898. curve: Curve.Sharp
  10899. }, () => {
  10900. this.scaleValueImage = Math.min(1, Math.max(0.5, 1 - this.translateY / 880));
  10901. console.info('onecold scaleValueImage:', this.scaleValueImage)
  10902. this.scaleValueText = Math.min(1, Math.max(0.88, 1 - this.translateY / 2000));
  10903. this.playDragUiOpacity = Math.min(1, Math.max(0, 1 - this.translateY / 300));
  10904. })
  10905. }
  10906. }
  10907. })
  10908. .onActionEnd((event?: GestureEvent) => {
  10909. // 判断滑动方向
  10910. const offsetY = event?.offsetY ?? 0;
  10911. const isSwipeUp = offsetY < 0;
  10912. const minDistance = 300; // 最小滑动距离
  10913. const minVelocity = 500; // 最小滑动速度
  10914. const velocity = event?.velocityY ?? 0;
  10915. if (isSwipeUp) {
  10916. // 向上滑动:切换下一首
  10917. const shouldSwitch = this.isPlayPageSwipeNext &&
  10918. (Math.abs(offsetY) > minDistance || Math.abs(velocity) > minVelocity);
  10919. if (shouldSwitch) {
  10920. // 直接切换下一首,无需动画(因为界面没有移动)
  10921. this.playNext().catch(() => {
  10922. Logger.error('heanup MusicPlayBuilder', '向上滑动切换下一首失败');
  10923. });
  10924. }
  10925. } else {
  10926. //这里加个变量,是否开启隔空手势播放下一首
  10927. if(this.isGeKongPlayNext){
  10928. this.playNext()
  10929. return
  10930. }
  10931. // 向下滑动:关闭播放页
  10932. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  10933. if (shouldClose) {
  10934. // 添加关闭动画
  10935. this.getUIContext().animateTo({
  10936. duration: 600,
  10937. curve: Curve.Friction
  10938. }, () => {
  10939. this.isShowPlay = false;
  10940. this.scaleValueImage = 1
  10941. this.scaleValueText = 1
  10942. this.playDragUiOpacity = 1
  10943. this.translateY = 0;
  10944. })
  10945. } else {
  10946. // 回弹动画
  10947. this.getUIContext().animateTo({
  10948. duration: 600,
  10949. curve: Curve.Friction
  10950. }, () => {
  10951. this.scaleValueImage = 1
  10952. this.scaleValueText = 1
  10953. this.playDragUiOpacity = 1
  10954. this.translateY = 0;
  10955. })
  10956. }
  10957. }
  10958. })
  10959. )
  10960. }
  10961. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  10962. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  10963. HeightBreakpoint.HEIGHT_LG;
  10964. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  10965. @State topBarHeight: number = 50
  10966. @State barOpacity: number = 1
  10967. @State barBottomOpacity: number = 1
  10968. private hideDone: boolean = false;
  10969. @State currentYOffset: number = 0;
  10970. @State bottomBarHeight: number = 68;
  10971. private isHiding: boolean = false;
  10972. //是否是Pura X外屏,或者小屏幕
  10973. isPuraWP() {
  10974. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  10975. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  10976. }
  10977. //是否是Pura X外屏,或者小屏幕,手机横屏
  10978. /**
  10979. * 是否是Pura X外屏,或者小屏幕,手机横屏
  10980. * @returns
  10981. */
  10982. isCoverOpacity() {
  10983. if (this.isPuraWP()) {
  10984. return true
  10985. }
  10986. if (this.isPhoneLan()) {
  10987. return true
  10988. }
  10989. if (deviceInfo.marketName.includes('Pura X')
  10990. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  10991. return true
  10992. }
  10993. return false
  10994. }
  10995. //是不是手机横屏
  10996. isPhoneLan() {
  10997. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  10998. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  10999. logHiCarWindow(`isPhoneLan width=${this.windowWidth}`);
  11000. logHiCarWindow(`isPhoneLan height=${this.windowHeight}`);
  11001. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarStatus=${this.isHiCarStatus}`);
  11002. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, curDisplayIsHiCar=${this.curDisplayIsHiCar}`);
  11003. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall=${this.isHiCarSmall()}`);
  11004. if (this.isHiCarKuanBianPing()) {
  11005. return true
  11006. }
  11007. if (this.isHiCar()) {
  11008. return false
  11009. }
  11010. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  11011. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  11012. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  11013. return true
  11014. }
  11015. return false
  11016. }
  11017. //是不是1920x720的hicar的屏幕分辨率
  11018. isHiCarKuanBianPing(){
  11019. // if(!this.isHiCar()){
  11020. // return false
  11021. // }
  11022. const hiCarAspectRatios: HiCarAspectRatio[] = [
  11023. { ratio: 1920 / 720, name: "1920x720" },
  11024. ];
  11025. const currentRatio: number = this.windowWidth / this.windowHeight;
  11026. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  11027. logHiCarWindow(`HiCarKuanBianPing currentRatio=${currentRatio}`)
  11028. for (const hiCarRatio of hiCarAspectRatios) {
  11029. logHiCarWindow(`HiCarKuanBianPing hiCarRatio=${hiCarRatio.ratio}`)
  11030. logHiCarWindow(`HiCarKuanBianPing diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  11031. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  11032. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  11033. //宽扁平的尺寸设置列表展示
  11034. this.twoFingerType ==3
  11035. this.isGridMusic = false
  11036. return true;
  11037. }
  11038. }
  11039. return false;
  11040. }
  11041. //是不是hicar的屏幕分辨率
  11042. isHiCarSmall() {
  11043. if(!this.isHiCar()){
  11044. return false
  11045. }
  11046. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  11047. {
  11048. this.columns = 6
  11049. return false
  11050. }
  11051. const hiCarAspectRatios: HiCarAspectRatio[] = [
  11052. { ratio: 800 / 480, name: "800x480" },
  11053. { ratio: 1280 / 720, name: "1280x720" },
  11054. { ratio: 1920 / 1080, name: "1920x1080" },
  11055. ];
  11056. const currentRatio: number = this.windowWidth / this.windowHeight;
  11057. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  11058. logHiCarWindow(`HiCarSmall currentRatio=${currentRatio}`)
  11059. for (const hiCarRatio of hiCarAspectRatios) {
  11060. logHiCarWindow(`HiCarSmall hiCarRatio=${hiCarRatio.ratio}`)
  11061. logHiCarWindow(`HiCarSmall diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  11062. logHiCarWindow(`HiCarSmall isHiCarStatus=${this.isHiCarStatus}`);
  11063. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  11064. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  11065. //宽扁平的尺寸设置列表展示
  11066. return true;
  11067. }
  11068. }
  11069. return false;
  11070. }
  11071. isHiCar(): boolean {
  11072. return this.curDisplayIsHiCar;
  11073. }
  11074. //是不是正常的手机竖屏
  11075. isPhonePortrait() {
  11076. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  11077. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  11078. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  11079. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  11080. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  11081. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  11082. return true
  11083. }
  11084. return false
  11085. }
  11086. @State showSpeedDialog: boolean = false
  11087. @State longPressSpeed: number = 3 //长按默认倍数
  11088. @Builder
  11089. SpeedDialog() {
  11090. Stack() {
  11091. Column() {
  11092. Text('已切换至' + this.longPressSpeed + '倍速播放')
  11093. .fontColor(Color.White)
  11094. .visibility(Visibility.Hidden)
  11095. }
  11096. .backgroundColor(Color.Black)
  11097. .borderRadius(20)
  11098. .padding({
  11099. top: 10,
  11100. right: 20,
  11101. left: 15,
  11102. bottom: 20
  11103. })
  11104. .opacity(0.6)
  11105. Text('已切换至' + this.longPressSpeed + '倍速播放')
  11106. .fontColor(Color.White)
  11107. }
  11108. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  11109. .zIndex(5)
  11110. .margin({ top: 80 })
  11111. }
  11112. @Builder
  11113. IjkMusicPlayerView() {
  11114. Stack() {
  11115. if(canIUse("SystemCapability.UIDesign.HDSComponent.Core")
  11116. &&deviceInfo.sdkApiVersion>=20&&this.sceneBgController){
  11117. HdsVisualComponent()
  11118. .scene(HdsSceneType.DUAL_EDGE_FLOW_LIGHT_WITH_BACKGROUND_MASK, this.sceneBgController, () => {
  11119. console.info('Succeeded in finishing');
  11120. })
  11121. .width('100%')
  11122. .height('100%')
  11123. .visibility(this.isShowBgLiuGUANG?Visibility.Visible:Visibility.None)
  11124. }
  11125. Column() {
  11126. Column() {
  11127. //播放标题
  11128. Column() {
  11129. this.PlayTitle()
  11130. }
  11131. .opacity(this.playDragUiOpacity)
  11132. .position({ x: 0, y: this.isCoverOpacity() ? 10 : 30 })
  11133. .width('100%')
  11134. .margin({ top: 0 })
  11135. .height(PlayConstants.HEIGHT)
  11136. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  11137. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  11138. if (this.showSpeedDialog) {
  11139. this.SpeedDialog()
  11140. }
  11141. Stack() {
  11142. //手势拖动快进
  11143. Column()
  11144. .width(CommonConstants.FULL_PERCENT)
  11145. .height('100%')
  11146. .gesture(
  11147. GestureGroup(GestureMode.Parallel,
  11148. // 长按屏幕倍数播放
  11149. LongPressGesture({ repeat: true })
  11150. .onAction(() => {
  11151. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  11152. this.showSpeedDialog = true;
  11153. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  11154. }
  11155. })
  11156. .onActionEnd(() => {
  11157. this.showSpeedDialog = false;
  11158. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  11159. }),
  11160. )
  11161. )
  11162. }
  11163. .height('65%')
  11164. Swiper() {
  11165. this.CoverInfo()
  11166. this.PlayerLyrics()
  11167. }
  11168. .onChange((index: number) => {
  11169. this.currentSwiperIndex = index
  11170. if (index === 1) {
  11171. this.syncLyricPositionNow()
  11172. }
  11173. })
  11174. .indicator(false)
  11175. .displayCount(this.getPlayerSwiperDisplayCount())
  11176. .clip(false)
  11177. .loop(false)
  11178. .autoPlay(false)
  11179. // .interval(8000)
  11180. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  11181. .height('100%')
  11182. .hitTestBehavior(HitTestMode.Transparent)
  11183. Image($r('app.media.icon_replay'))
  11184. .objectFit(ImageFit.Auto)
  11185. .width('120px')
  11186. .height('120px')
  11187. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  11188. .border({ width: 0 })
  11189. .visibility(Visibility.None)
  11190. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  11191. .onClick(() => {
  11192. console.info('onecold startPlayOrResumePlay 6744')
  11193. this.startPlayOrResumePlay();
  11194. })
  11195. }
  11196. .width(CommonConstants.FULL_PERCENT)
  11197. .height(CommonConstants.FULL_PERCENT)
  11198. .justifyContent(FlexAlign.End)
  11199. }
  11200. .justifyContent(FlexAlign.End)
  11201. .margin({ bottom: 5 })
  11202. }
  11203. .backgroundImage(!this.isMusicBGCover||StrUtil.isEmpty(this.cover)?null: this.cover)
  11204. .backgroundImageSize(this.isPuraWP()||!this.isMusicBGCover ? { width: '100%' } : { height: '150%', width: '100%' })
  11205. .animation({
  11206. duration: 666,
  11207. curve: 'ease-in-out' // 可选动画曲线
  11208. })
  11209. .backgroundBlurStyle((this.isPuraWP() && this.currentSwiperIndex === 0) ||!this.isMusicBGCover
  11210. ? BlurStyle.NONE :
  11211. BlurStyle.BACKGROUND_ULTRA_THICK)
  11212. .hitTestBehavior(HitTestMode.Transparent)
  11213. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  11214. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  11215. .onClick(() => {
  11216. if(this.isHiCar())
  11217. return
  11218. if(this.is_auto_hide_progress){
  11219. this.is_auto_hide_progress = false
  11220. }
  11221. this.startAutoHide()
  11222. })
  11223. }
  11224. @Consume progressValue: number ;
  11225. @State currentTime: string = "00:00";
  11226. @State totalTime: string = "00:00";
  11227. @State loadingVisible: Visibility = Visibility.None;
  11228. @State replayVisible: Visibility = Visibility.None;
  11229. @State slideEnable: boolean = false;
  11230. @State aspRatio: number = 0.5;
  11231. @State mContext: object | undefined = undefined;
  11232. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  11233. @State mFirst: boolean = true;
  11234. @State mDestroyPage: boolean = false;
  11235. @State playSpeed: number = 1;
  11236. @State oldSeconds: number = 0;
  11237. @State isSeekTo: boolean = false;
  11238. @State isCurrentTime: boolean = false;
  11239. @State videoWidth: string = '100%';
  11240. @State videoHeight: string = '100%';
  11241. @State initAspectRatio: number = 1;
  11242. @State videoAspectRatio: number = this.initAspectRatio;
  11243. @State videoUrl: string = '';
  11244. private last: number = 0;
  11245. @State videoParentAspectRatio: number = this.initAspectRatio;
  11246. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  11247. @Consume CONTROL_PlayStatus: number ;
  11248. @State PROGRESS_MAX_VALUE: number = 100;
  11249. @State updateProgressTimer: number = 0;
  11250. private readonly progressUpdateIntervalMs: number = 120;
  11251. private readonly lyricUpdateMinDeltaMs: number = 24;
  11252. private lastLyricRenderPosition: number = Number.NaN;
  11253. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  11254. @State name: string = '';
  11255. // @State loop: boolean = false;
  11256. @State playType: number = 0; //0:连续循环播放 1:单片重复播放 2:正常播放 3:随机播放 4:连续播放不循环
  11257. @State multiple: string = '1.0X';
  11258. xcomponentController: XComponentController = new XComponentController()
  11259. private panOptionBright: PanGestureOptions =
  11260. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  11261. private panOptionVolume: PanGestureOptions =
  11262. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  11263. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  11264. //手势的音量控制和亮度控制
  11265. private positionX: number = PlayConstants.POSITION_X;
  11266. private positionY: number = PlayConstants.POSITION_Y;
  11267. private windowClass: window.Window = globalThis.windowClass
  11268. @State volume: number = 0.8;
  11269. @State volumeBoostPercent: number = 0
  11270. @State volumeSmall: boolean = false
  11271. @State autoParseMusicName: boolean = true
  11272. @State isShowFileName: boolean = false
  11273. @State isLongNameRoLL: boolean = true//长歌名滚动
  11274. private readonly volumeBoostPreferenceKey: string = 'volumeBoostPercent';
  11275. private readonly volumeBoostMaxPercent: number = 500;
  11276. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  11277. @State bright: number = PlayConstants.BRIGHT;
  11278. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  11279. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  11280. @State screenWidth: number = 0
  11281. @State screenHeight: number = 0
  11282. @State statusBarHeight: number = 0
  11283. @State isYesFull: boolean = false
  11284. private seekValue: number = 0
  11285. @State isVideoLock: boolean = false; // Whether the video playback is locked
  11286. private preloadNextRandomIndex: number = -1; // 预缓存的随机下一首索引
  11287. private playbackUrlRequestSerial: number = 0;
  11288. eventHub = getContext().eventHub;
  11289. private isAppForeground: boolean = true;
  11290. private lastBufferingLogTs: number = 0;
  11291. private readonly bufferingLogIntervalMs: number = 5000;
  11292. //投播组件
  11293. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  11294. // 新的投播控制器(封装了官方示例的逻辑)
  11295. private castControllerWrapper: CastController | undefined = undefined;
  11296. // 保留原始的 avCastController 引用(用于兼容旧代码)
  11297. private castController: avSession.AVCastController | undefined = undefined;
  11298. @State isCastPlaying: boolean = false;
  11299. @State currentTime2: number = 0;
  11300. @State currentStringTime: string = '00:00';
  11301. @State duration: number = 0;
  11302. @State isReady: boolean = false;
  11303. @State durationTime: number = 0;
  11304. @State durationStringTime: string = '00:00';
  11305. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  11306. // @State isPlaying: boolean = false;
  11307. private castSeek: boolean = false;
  11308. private castItem: avSession.AVQueueItem | undefined = undefined;
  11309. private castFile: fs.File | undefined = undefined; // 保持文件描述符引用,避免被垃圾回收
  11310. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  11311. @State rotateAngle2: number = -9
  11312. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  11313. @Consume cover: string | undefined ;
  11314. @State artist: string | undefined = ''
  11315. // 1.初始化controller
  11316. private lyricController: LyricController = new LyricController()
  11317. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  11318. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  11319. private parser = new LyricParser()
  11320. @State randomShakenX: number = 0
  11321. @State randomShakenY: number = 0
  11322. @State lyricTextSize: number = 24
  11323. @State lyricContent: string = ''
  11324. @State isDebug: boolean = false
  11325. @State isHightLightCenter: boolean = true
  11326. private syncWordByWordLyricMode(): void {
  11327. this.lyricController.setEnableWordByWordLyric(this.isEnableWordByWordLyric)
  11328. this.lyricControllerXF.setEnableWordByWordLyric(this.isEnableWordByWordLyric)
  11329. this.lyricControllerSingle.setEnableWordByWordLyric(this.isEnableWordByWordLyric)
  11330. }
  11331. private syncLyricLightTextMode(): void {
  11332. this.lyricController.setLightText(this.isLightText)
  11333. this.lyricControllerXF.setLightText(this.isLightText)
  11334. this.lyricControllerSingle.setLightText(this.isLightText)
  11335. }
  11336. /**
  11337. * 初始化歌词加载与展示逻辑
  11338. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  11339. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  11340. * @param isApi2 是否使用API2获取歌词(可选)
  11341. *
  11342. * 主要流程:
  11343. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  11344. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  11345. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  11346. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  11347. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  11348. * 6. 解析失败或读取失败时,清空歌词显示。
  11349. *
  11350. * 注意事项:
  11351. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  11352. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  11353. * - 歌词内容解析后通过lyricController驱动UI渲染。
  11354. */
  11355. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
  11356. if (StrUtil.isEmpty(lyricPath)) {
  11357. return
  11358. }
  11359. this.syncWordByWordLyricMode()
  11360. this.syncLyricLightTextMode()
  11361. this.initPipLyricSetting()
  11362. this.lyricControllerSingle
  11363. .setTextSize(15)
  11364. .setCacheSize(4)
  11365. .setTextColor("#FFFFFF")
  11366. .setHighlightColor(this.currentHighLightLyricColor)
  11367. .setHighlightScale(1.2)
  11368. .setEmptyHint("")
  11369. .setLineSpace(1)
  11370. .setAlignMode('center')
  11371. .setAnimationDuration(500)
  11372. .setSingleLine(true)
  11373. this.lyricContent = ''
  11374. this.lyricController
  11375. .setTextSize(this.currentLyricSize)
  11376. .setCacheSize(4)
  11377. .setTextColor("#DDDDDD")
  11378. .setHighlightColor("#FFFFFF")
  11379. .setEmptyHint("")
  11380. .setAnimationDuration(1000)
  11381. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  11382. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  11383. this.setBlurDegree(this.blurDegree, false)
  11384. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  11385. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  11386. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  11387. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  11388. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  11389. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  11390. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  11391. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  11392. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  11393. this.lyricController.setTextWeight(this.lyricTextWeight)
  11394. this.showSingleLyric = false
  11395. // 加载已保存的歌词时间偏移
  11396. this.loadLyricTimeOffset()
  11397. this.lyricController.setLyric(null)
  11398. this.lyricControllerSingle.setLyric(null)
  11399. console.log("onecold lyricPath =" + lyricPath)
  11400. // 1. 检查内嵌歌词
  11401. let neiqianLrc = ''
  11402. let lyContent = this.currentSong?.lyricContent
  11403. if(lyContent && StrUtil.isNotEmpty(lyContent)){
  11404. neiqianLrc = lyContent
  11405. }
  11406. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast && !isLocal) {
  11407. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  11408. // Navidrome JSON歌词转换
  11409. if (this.currentSong && isNavidromeType(this.currentSong.type)) {
  11410. const convertedLyric: string | undefined = LyricUtil.convertNavidromeJsonLyricToLrc(neiqianLrc);
  11411. if (convertedLyric) {
  11412. neiqianLrc = convertedLyric;
  11413. console.log("onecold Navidrome歌词转换成功");
  11414. }
  11415. }
  11416. this.setLyricToControllers(neiqianLrc);
  11417. return
  11418. }
  11419. // 2. 远程播放实时探测歌词: 优先探测内嵌歌词,失败后查找同路径同名 .lrc
  11420. if (this.currentSong && shouldResolveRemoteLyricOnPlay(this.currentSong) && !isOnLineAndToast && !isLocal) {
  11421. const remoteLyric: string = await tryResolveRemotePlaybackLyric({
  11422. song: this.currentSong,
  11423. playbackUrl: this.videoUrl,
  11424. manager: RemoteDriveManager.getInstance(),
  11425. detectEncoding: (data: ArrayBuffer): string => this.detect(data)
  11426. });
  11427. if (StrUtil.isNotEmpty(remoteLyric)) {
  11428. this.currentSong.lyricContent = remoteLyric;
  11429. this.setLyricToControllers(remoteLyric);
  11430. void this.persistRemoteMetadataToDb(this.currentSong);
  11431. return;
  11432. }
  11433. }
  11434. // 3. 尝试从服务器获取歌词 (Navidrome/Jellyfin/Emby/AudioStation/Plex)
  11435. if (this.currentSong && (isJellyfinType(this.currentSong.type)||isNavidromeType(this.currentSong.type)
  11436. || isEmbyType(this.currentSong.type) || isAudioStationType(this.currentSong.type)
  11437. || isPlexType(this.currentSong.type))) {
  11438. const manager = RemoteDriveManager.getInstance();
  11439. const getAccount = (accountId: string) => manager.getWebDavAccountById(accountId);
  11440. // 将currentSong转换为SongData接口
  11441. const songData: SongData = {
  11442. webdav_account_id: this.currentSong.webdav_account_id,
  11443. artist: this.currentSong.artist,
  11444. name: this.currentSong.name,
  11445. webdav_id: this.currentSong.webdav_id,
  11446. lyricIndex: this.currentSong.lyricIndex,
  11447. type: this.currentSong.type
  11448. };
  11449. let serverLyric = '';
  11450. if (!serverLyric && isNavidromeType(songData.type)) {
  11451. serverLyric = await lyricService.fetchNavidromeLyric(songData, getAccount,this.currentSong.id);
  11452. }
  11453. if (!serverLyric && isJellyfinType(songData.type)) {
  11454. serverLyric = await lyricService.fetchJellyfinLyric(songData, getAccount);
  11455. }
  11456. if (!serverLyric && isEmbyType(songData.type)) {
  11457. serverLyric = await lyricService.fetchEmbyLyric(songData, getAccount);
  11458. }
  11459. if (!serverLyric && isAudioStationType(songData.type)) {
  11460. serverLyric = await lyricService.fetchAudioStationLyric(songData, getAccount);
  11461. }
  11462. if (!serverLyric && isPlexType(songData.type)) {
  11463. serverLyric = await lyricService.fetchPlexLyric(songData, getAccount);
  11464. }
  11465. if (serverLyric) {
  11466. this.setLyricToControllers(serverLyric, lyricPath);
  11467. return;
  11468. }
  11469. }
  11470. // 4. 尝试在线歌词API
  11471. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath))
  11472. && !Utility.isVideoByExtension(this.videoUrl))) {
  11473. this.fetchOnlineLyric(lyricPath, isOnLineAndToast || false, isApi2);
  11474. return;
  11475. }
  11476. // 5. 从本地文件读取歌词
  11477. await this.loadLyricFromFile(lyricPath, isLocal || false);
  11478. }
  11479. /**
  11480. * 从本地文件加载歌词
  11481. */
  11482. private async loadLyricFromFile(lyricPath: string, isLocal: boolean): Promise<void> {
  11483. try {
  11484. let realLyricPath = lyricPath;
  11485. // 读取文件内容
  11486. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  11487. const stat = await fileIo.stat(file.fd);
  11488. const arrayBuffer = new ArrayBuffer(stat.size);
  11489. fs.read(file.fd, arrayBuffer)
  11490. .then((readLen: number) => {
  11491. console.info("read file data succeed");
  11492. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  11493. if (buf.length === 0) {
  11494. throw new Error("Buffer is empty after reading the file");
  11495. }
  11496. try {
  11497. // 检测文件编码
  11498. let detectedEncoding = this.detect(arrayBuffer);
  11499. console.info("onecoldT Detected encoding: " + detectedEncoding);
  11500. // 使用检测到的编码解码,解决中文乱码问题
  11501. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  11502. console.info("onecoldT Detected textDecoder: " + textDecoder);
  11503. let fileContent = textDecoder.decode(buf);
  11504. console.info(`onecoldT The content of file1: ${fileContent}`);
  11505. console.info(`onecold The content of file2: ${fileContent}`);
  11506. this.lyricContent = fileContent;
  11507. if(isLocal){
  11508. // 编辑标签选择本地歌词需要赋值给this.lyricConStr
  11509. this.lyricConStr = fileContent;
  11510. }
  11511. this.setLyricToControllers(fileContent);
  11512. console.info(`The content of file: ${fileContent}`);
  11513. } catch (chardetError) {
  11514. console.error("chardet.detect failed with error: " + chardetError.message);
  11515. this.clearLyricControllers();
  11516. }
  11517. })
  11518. .catch((err: BusinessError) => {
  11519. this.clearLyricControllers();
  11520. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  11521. })
  11522. .catch((err: Error) => {
  11523. this.clearLyricControllers();
  11524. console.error("read file 2 data failed with error message: " + err.message);
  11525. })
  11526. .finally(() => {
  11527. fs.closeSync(file);
  11528. });
  11529. } catch (error) {
  11530. this.clearLyricControllers();
  11531. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  11532. }
  11533. }
  11534. detect(data: ArrayBuffer): string {
  11535. //创建检测对象
  11536. let detector: UniversalDetector = new UniversalDetector();
  11537. // 限制检测数据大小,避免内存溢出
  11538. // 通常只需要检测文件前16KB就足够判断编码格式
  11539. const MAX_DETECT_SIZE = 16 * 1024; // 16KB
  11540. const detectSize = Math.min(data.byteLength, MAX_DETECT_SIZE);
  11541. // 传入检测数据并实时判断编码格式
  11542. detector.handleData(data, 0, detectSize);
  11543. // 标记检测数据 读取结束
  11544. detector.dataEnd();
  11545. // 获取检测结果
  11546. let detected: string = detector.getDetectedCharset();
  11547. // 释放资源
  11548. detector.reset();
  11549. Logger.info(TAG, "heanup detect encoding: " + detected + ", data size: " + data.byteLength + ", detect size: " + detectSize);
  11550. return detected;
  11551. }
  11552. /**
  11553. * 设置歌词到所有控制器
  11554. * @param lyricText 歌词文本
  11555. * @param savePath 可选,如果提供则保存到本地文件
  11556. */
  11557. private setLyricToControllers(lyricText: string, savePath?: string): void {
  11558. if (StrUtil.isEmpty(lyricText)) {
  11559. this.clearLyricControllers();
  11560. return;
  11561. }
  11562. this.lyricContent = lyricText;
  11563. const lines: string[] = lyricText.split('\n').map((line: string) => line.trim());
  11564. const lyric: Lyric = this.parser.parse(lines);
  11565. this.lyricController.setLyric(lyric);
  11566. this.lyricControllerXF.setLyric(lyric);
  11567. this.lyricControllerSingle.setLyric(lyric);
  11568. this.showSingleLyric = true;
  11569. // 如果提供了保存路径,保存歌词到本地
  11570. if (savePath) {
  11571. this.saveDataToFile(lyricText, savePath);
  11572. }
  11573. }
  11574. /**
  11575. * 清空所有歌词控制器
  11576. */
  11577. private clearLyricControllers(): void {
  11578. this.lyricController.setLyric(null);
  11579. this.lyricControllerXF.setLyric(null);
  11580. this.lyricControllerSingle.setLyric(null);
  11581. }
  11582. private extractLyricCopyLines(lyricText: string): string[] {
  11583. if (StrUtil.isEmpty(lyricText)) {
  11584. return [];
  11585. }
  11586. const normalizedLyric = LyricUtil.convertLyricToSimpleLrc(lyricText);
  11587. const source = StrUtil.isNotEmpty(normalizedLyric) ? normalizedLyric : lyricText;
  11588. const lines = source.split('\n');
  11589. const result: string[] = [];
  11590. const metaTagPattern = /^\[(ti|ar|al|by|offset|hash|sign|qq|total|tool|re|ve|length|au):?.*]$/i;
  11591. for (let i = 0; i < lines.length; i++) {
  11592. const line = lines[i].trim();
  11593. if (!line || metaTagPattern.test(line)) {
  11594. continue;
  11595. }
  11596. const pureLine = line
  11597. .replace(/\[\d{1,2}:\d{2}(?:\.\d{1,3})?]/g, '')
  11598. .replace(/<\d{1,2}:\d{2}(?:\.\d{1,3})?>/g, '')
  11599. .trim();
  11600. if (pureLine.length > 0) {
  11601. result.push(pureLine);
  11602. }
  11603. }
  11604. return result;
  11605. }
  11606. private openLyricCopySheet(): void {
  11607. const lines = this.extractLyricCopyLines(this.lyricContent);
  11608. if (ArrayUtil.isEmpty(lines)) {
  11609. ToastUtil.showToast('暂无可复制歌词');
  11610. return;
  11611. }
  11612. this.lyricCopyLines = lines;
  11613. this.lyricSelectedIndexes = [];
  11614. this.isShowLyricCopySheet = true;
  11615. }
  11616. private toggleLyricLineSelection(index: number): void {
  11617. const selectedIndex = this.lyricSelectedIndexes.indexOf(index);
  11618. if (selectedIndex >= 0) {
  11619. const nextSelectedIndexes = [...this.lyricSelectedIndexes];
  11620. nextSelectedIndexes.splice(selectedIndex, 1);
  11621. this.lyricSelectedIndexes = nextSelectedIndexes;
  11622. return;
  11623. }
  11624. this.lyricSelectedIndexes = [...this.lyricSelectedIndexes, index];
  11625. }
  11626. private toggleLyricSelectAll(): void {
  11627. if (this.lyricSelectedIndexes.length === this.lyricCopyLines.length) {
  11628. this.lyricSelectedIndexes = [];
  11629. return;
  11630. }
  11631. this.lyricSelectedIndexes = this.lyricCopyLines.map((_: string, index: number) => index);
  11632. }
  11633. private copySelectedLyricLines(): void {
  11634. const selectedLines = this.getSelectedLyricLines();
  11635. if (ArrayUtil.isEmpty(selectedLines)) {
  11636. ToastUtil.showToast('暂无可复制歌词');
  11637. return;
  11638. }
  11639. Utility.copyText(selectedLines.join('\n'));
  11640. ToastUtil.showToast(`已复制${selectedLines.length}行歌词`);
  11641. }
  11642. private getSelectedLyricLines(): string[] {
  11643. if (ArrayUtil.isEmpty(this.lyricSelectedIndexes)) {
  11644. return [];
  11645. }
  11646. const selectedIndexes = [...this.lyricSelectedIndexes].sort((a: number, b: number) => a - b);
  11647. const selectedLines: string[] = [];
  11648. for (let i = 0; i < selectedIndexes.length; i++) {
  11649. const index = selectedIndexes[i];
  11650. if (index >= 0 && index < this.lyricCopyLines.length) {
  11651. selectedLines.push(this.lyricCopyLines[index]);
  11652. }
  11653. }
  11654. return selectedLines;
  11655. }
  11656. private shareSelectedLyricLines(): void {
  11657. const selectedLines = this.getSelectedLyricLines();
  11658. if (ArrayUtil.isEmpty(selectedLines)) {
  11659. ToastUtil.showToast('暂无可分享歌词');
  11660. return;
  11661. }
  11662. const shareTitle = `${this.currentSong?.name ?? '歌词'}歌词`;
  11663. Utility.doShareText(selectedLines.join('\n'), this.context, shareTitle, '分享歌词');
  11664. }
  11665. /**
  11666. * 从在线API获取歌词
  11667. */
  11668. private fetchOnlineLyric(lyricPath: string, isOnLineAndToast: boolean, isApi2?: boolean): void {
  11669. if (!this.currentSong) {
  11670. this.clearLyricControllers();
  11671. if (isOnLineAndToast) {
  11672. ToastUtil.showShort('未获取到歌词!');
  11673. }
  11674. return;
  11675. }
  11676. let artist = this.currentSong.artist || '';
  11677. if (isApi2 === undefined) {
  11678. isApi2 = false;
  11679. }
  11680. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  11681. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  11682. this.setLyricToControllers(res, lyricPath);
  11683. } else {
  11684. this.clearLyricControllers();
  11685. if (isOnLineAndToast) {
  11686. ToastUtil.showShort('未获取到歌词!');
  11687. }
  11688. }
  11689. });
  11690. }
  11691. //初始化悬浮歌词的自定义设置
  11692. initPipLyricSetting() {
  11693. this.lyricControllerXF
  11694. .setTextSize(this.currentLyricSize)
  11695. .setCacheSize(4)
  11696. .setTextColor("#DDDDDD")
  11697. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  11698. .setEmptyHint("")
  11699. .setAnimationDuration(1000)
  11700. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  11701. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  11702. this.setBlurDegree(this.blurDegreePip, true)
  11703. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  11704. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  11705. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  11706. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  11707. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  11708. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  11709. this.lyricControllerXF.setHightLightCenter(true)
  11710. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  11711. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  11712. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  11713. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  11714. if (this.pipBgIndex === 0) {
  11715. if (this.cover) {
  11716. this.pipBg = this.cover
  11717. } else {
  11718. this.pipBg = this.imageColor
  11719. }
  11720. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  11721. }
  11722. }
  11723. //根据item返回歌词内容
  11724. async getLyricContent(item: VideoItem): Promise<string> {
  11725. let neiqianLrc = ''
  11726. let lyContent = item?.lyricContent
  11727. if(lyContent&&StrUtil.isNotEmpty(lyContent)){
  11728. neiqianLrc = lyContent
  11729. return neiqianLrc
  11730. }
  11731. try {
  11732. //取数据库里面的歌词lyContent
  11733. const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
  11734. if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
  11735. console.log("onecold Lyrics:", lyricContent);
  11736. neiqianLrc = lyricContent
  11737. return neiqianLrc
  11738. }
  11739. } catch (error) {
  11740. console.error("Error fetching lyrics:", error);
  11741. }
  11742. try {
  11743. let filePath = item.filePath;
  11744. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  11745. let realLyricPath = lyricPath;
  11746. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  11747. const stat = await fileIo.stat(file.fd);
  11748. const arrayBuffer = new ArrayBuffer(stat.size);
  11749. const readLen = await fs.read(file.fd, arrayBuffer);
  11750. console.info("read file data succeed");
  11751. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  11752. if (buf.length === 0) {
  11753. throw new Error("Buffer is empty after reading the file");
  11754. }
  11755. // let detectedEncoding = chardet.detect(buf);
  11756. let detectedEncoding = this.detect(arrayBuffer)
  11757. console.info("Detected encoding: " + detectedEncoding);
  11758. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  11759. let fileContent = textDecoder.decode(buf);
  11760. console.info(`onecold The content of file1: ${fileContent}`);
  11761. fs.closeSync(file);
  11762. return fileContent;
  11763. } catch (error) {
  11764. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  11765. return '';
  11766. }
  11767. }
  11768. async saveDataToFile(content: string, filePath: string) {
  11769. if (StrUtil.isEmpty(filePath)) {
  11770. return
  11771. }
  11772. try {
  11773. let lyricContent = ''
  11774. lyricContent = content
  11775. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  11776. // 清空文件内容
  11777. await fileIo.truncate(file.fd, 0);
  11778. await fileIo.write(file.fd, lyricContent);
  11779. await fileIo.close(file);
  11780. console.log('onecold lyric file Data saved successfully.');
  11781. } catch (error) {
  11782. console.error('onecold lyric file Failed to save data:', error);
  11783. }
  11784. }
  11785. // 定义开始旋转的方法
  11786. // 使用动画系统优化旋转性能,避免 setInterval 频繁更新导致卡顿
  11787. @State timer: number = 0
  11788. @State rotateAngle: number = 0
  11789. @State isRotationRunning: boolean = false // 旋转动画是否正在运行
  11790. @StorageProp('isPageVisible') @Watch('onPageVisibilityChange') isPageVisible: boolean = true // 页面可见性标志
  11791. // 页面可见性变化回调
  11792. onPageVisibilityChange() {
  11793. // 当页面可见性改变时,重新启动/停止旋转动画
  11794. this.animationRoFun()
  11795. }
  11796. //封面旋转动画
  11797. animationRoFun() {
  11798. if (this.isPlaying && !this.isCoverRectangle && this.isPageVisible) {
  11799. // 启动旋转动画
  11800. if (!this.isRotationRunning) {
  11801. this.isRotationRunning = true
  11802. this.startContinuousRotation()
  11803. }
  11804. this.startRotation()
  11805. } else {
  11806. // 停止旋转动画
  11807. this.isRotationRunning = false
  11808. clearInterval(this.timer)
  11809. this.stopRotation()
  11810. }
  11811. }
  11812. // 使用持续的动画进行旋转,避免频繁状态更新
  11813. private startContinuousRotation() {
  11814. clearInterval(this.timer)
  11815. // 改为每 1000ms 更新 36 度(10秒一圈),减少更新频率
  11816. // 不使用 % 360 取模,让角度持续累加,避免反转
  11817. this.timer = setInterval(() => {
  11818. if (this.isRotationRunning) {
  11819. this.rotateAngle = this.rotateAngle + 36
  11820. }
  11821. }, 1000)
  11822. }
  11823. // 定义开始旋转的方法
  11824. startRotation() {
  11825. if (this.isPlaying) {
  11826. animateTo({
  11827. duration: 777,
  11828. iterations: 1,
  11829. curve: Curve.Linear
  11830. }, () => {
  11831. this.rotateAngle2 = -9
  11832. })
  11833. }
  11834. }
  11835. // 回调,暂停和播放按钮回调,下一首和上一首
  11836. playChange() {
  11837. // if(this.isCoverRectangle){
  11838. // return
  11839. // }
  11840. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  11841. this.setIsPlaying(true)
  11842. this.animationState = AnimationStatus.Running
  11843. } else {
  11844. this.setIsPlaying(false)
  11845. this.animationState = AnimationStatus.Paused
  11846. }
  11847. AppStorage.setOrCreate('animationState', this.animationState);
  11848. }
  11849. // 定义停止旋转的方法
  11850. stopRotation() {
  11851. if (this.isCoverRectangle) {
  11852. this.rotateAngle = 0
  11853. } else {
  11854. //唱针以左上角为点选择逆时针40度
  11855. animateTo({
  11856. duration: 1000,
  11857. curve: Curve.Linear,
  11858. iterations: 1,
  11859. }, () => {
  11860. this.rotateAngle2 = -45;
  11861. });
  11862. }
  11863. }
  11864. @Builder
  11865. private LyricsTopItem() {
  11866. Row() {
  11867. Stack({ alignContent: Alignment.Center }) {
  11868. Image( StrUtil.isNotEmpty(this.cover)?
  11869. this.cover:$r('app.media.alt'))
  11870. .height(58)
  11871. .width(58)
  11872. .clip(true)
  11873. .sourceSize({width:38, height:38})
  11874. .alt($r('app.media.alt'))
  11875. .borderRadius(8)
  11876. .clickEffect({ level: ClickEffectLevel.HEAVY })
  11877. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  11878. .shadow({
  11879. radius: 22,
  11880. type: ShadowType.BLUR,
  11881. color: 'on_primary'
  11882. })
  11883. }
  11884. .width(62)
  11885. .height('100%')
  11886. Column() {
  11887. Column() {
  11888. Text(this.name)
  11889. .fontSize(16)
  11890. .maxLines(1)
  11891. .fontWeight(FontWeight.Bolder)
  11892. .fontColor(Color.White)
  11893. .textOverflow({ overflow: TextOverflow.Ellipsis })
  11894. .margin({ left: 10 })
  11895. Row() {
  11896. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  11897. .fontSize(13)
  11898. .fontWeight(FontWeight.Bolder)
  11899. .padding({ top: 8 })
  11900. .fontColor(Color.White)
  11901. .margin({ left: 10 })
  11902. Blank()
  11903. }
  11904. }
  11905. .height('100%')
  11906. .width('100%')
  11907. .justifyContent(FlexAlign.Center)
  11908. .alignItems(HorizontalAlign.Start)
  11909. }
  11910. .height('100%')
  11911. .layoutWeight(1)
  11912. .margin({ right: 8 })
  11913. Column() {
  11914. PointLightDefaultButton({
  11915. isSysBol:false,
  11916. pointColor:Color.White,
  11917. imageResource:$r('app.media.lyric'),
  11918. isPx: false,
  11919. builderHeight: 23,
  11920. builderWidth: 23,
  11921. })
  11922. .onClick(() => {
  11923. this.isLyricSetting = !this.isLyricSetting;
  11924. })
  11925. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  11926. height: '99%',
  11927. dragBar: true,
  11928. preferType: SheetType.CENTER,
  11929. showClose: true,
  11930. blurStyle: BlurStyle.Thin,
  11931. backgroundColor: Color.Transparent,
  11932. title: { title: $r('app.string.lyric_setting') }
  11933. })
  11934. }
  11935. .width(44)
  11936. .height('100%')
  11937. .justifyContent(FlexAlign.Center)
  11938. .alignItems(HorizontalAlign.End)
  11939. }
  11940. .width(this.currentLyricAlignModePip === 1?'98%':'90%%')
  11941. .padding({ left: 28, right: 28 })
  11942. .height(58)
  11943. .alignItems(VerticalAlign.Center)
  11944. }
  11945. //歌词显示
  11946. @Builder
  11947. PlayerLyrics() {
  11948. Column() {
  11949. Column() {
  11950. this.LyricsTopItem()
  11951. }
  11952. .height(this.isPuraWP() ? 15 : 58)
  11953. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  11954. Visibility.None : Visibility.Visible)
  11955. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  11956. .width("100%")
  11957. Column() {
  11958. LyricView2({
  11959. controller: this.lyricController,
  11960. enableSeek: true,
  11961. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  11962. seekLineColor: "#80ffffff", // 滑动定位线颜色
  11963. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  11964. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  11965. if (!this.isPlaying) {
  11966. console.info('onecold startPlayOrResumePlay 7527')
  11967. this.startPlayOrResumePlay()
  11968. }
  11969. else {
  11970. this.isSeekTo = true;
  11971. this.mDestroyPage = false;
  11972. // 只有播放网盘歌曲时才显示转圈圈
  11973. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  11974. this.showLoadIng();
  11975. }
  11976. this.seekTo(position + "");
  11977. }
  11978. return true
  11979. }
  11980. })
  11981. .width("100%")
  11982. .layoutWeight(1)
  11983. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  11984. .gesture(LongPressGesture()
  11985. .onAction(() => {
  11986. this.openLyricCopySheet();
  11987. }))
  11988. .bindSheet($$this.isShowLyricCopySheet, this.LyricCopySheetBuilder(), {
  11989. height: '99%',
  11990. dragBar: true,
  11991. showClose: true,
  11992. preferType: SheetType.CENTER,
  11993. blurStyle: BlurStyle.Thin,
  11994. title: { title: '歌词' }
  11995. })
  11996. if (this.isPhoneLan()) {
  11997. Column() {
  11998. if (this.isShowSpectrum) {
  11999. this.InlineSpectrumView()
  12000. }
  12001. this.playProgressView()
  12002. }
  12003. .margin({ bottom: 32, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  12004. }
  12005. }
  12006. .position({
  12007. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  12008. (this.isPuraWP() ? 58 : 99)
  12009. })
  12010. .justifyContent(FlexAlign.Center)
  12011. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  12012. }
  12013. }
  12014. @Builder
  12015. LyricCopySheetBuilder() {
  12016. LyricCopySheet({
  12017. lyricCopyLines: this.lyricCopyLines,
  12018. lyricSelectedIndexes: this.lyricSelectedIndexes,
  12019. isDarkMode: this.isDarkMode,
  12020. themeColor: this.themeColor,
  12021. bottomSafeHeight: this.bottomSafeHeight,
  12022. onToggleLyricLine: (index: number) => {
  12023. this.toggleLyricLineSelection(index);
  12024. },
  12025. onToggleSelectAll: () => {
  12026. this.toggleLyricSelectAll();
  12027. },
  12028. onCopySelectedLines: () => {
  12029. this.copySelectedLyricLines();
  12030. },
  12031. onShareSelectedLines: () => {
  12032. this.shareSelectedLyricLines();
  12033. }
  12034. })
  12035. }
  12036. @Builder
  12037. SingleLyricView() {
  12038. Column() {
  12039. Column() {
  12040. LyricView2({
  12041. controller: this.lyricControllerSingle,
  12042. enableSeek: false,
  12043. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  12044. seekLineColor: "#80ffffff", // 滑动定位线颜色
  12045. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  12046. })
  12047. .gesture(LongPressGesture()
  12048. .onAction(() => {
  12049. this.openLyricCopySheet();
  12050. }))
  12051. }
  12052. .height(82)
  12053. .margin({ bottom: 20 })
  12054. }
  12055. .opacity(this.playDragUiOpacity)
  12056. }
  12057. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  12058. @Builder
  12059. BottomControl() {
  12060. Column() {
  12061. if (this.isShowSpectrum) {
  12062. this.InlineSpectrumView()
  12063. }
  12064. this.TopPlayProgressView()
  12065. //播放 暂停,下一首,上一首
  12066. this.playCenterView()
  12067. if(!this.curDisplayIsHiCar){
  12068. //播放进度条
  12069. this.BottomView()
  12070. }
  12071. }
  12072. .justifyContent(FlexAlign.Center)
  12073. .alignItems(HorizontalAlign.Center)
  12074. .opacity(this.playDragUiOpacity)
  12075. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  12076. }
  12077. @Builder
  12078. playMenuBuilder(){
  12079. Image($r('app.media.menu'))
  12080. .width(24)
  12081. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12082. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  12083. height: '99%',
  12084. preferType:SheetType.CENTER,
  12085. dragBar: true,
  12086. showClose: true,
  12087. blurStyle: BlurStyle.Thin,
  12088. title: { title: $r('app.string.more') },
  12089. backgroundColor: Color.Transparent,
  12090. })
  12091. }
  12092. //播放控制上一首 下一首 暂停和播放
  12093. @Builder
  12094. playCenterView(){
  12095. Row() {
  12096. PointLightButton({
  12097. builder: () => {
  12098. this.playMenuBuilder()
  12099. },
  12100. isPx: false,
  12101. builderHeight: 26,
  12102. builderWidth: 26,
  12103. })
  12104. .onClick(async () =>{
  12105. this.isShowMoreView = !this.isShowMoreView;
  12106. })
  12107. PointLightButton({
  12108. builder: () => {
  12109. this.playPreviousBuilder()
  12110. },
  12111. isPx: false,
  12112. builderHeight: 26,
  12113. builderWidth: 26,
  12114. })
  12115. .onClick(async () =>{
  12116. await this.playPrevious()
  12117. })
  12118. PointLightButton({
  12119. builder: () => {
  12120. this.PlayOrPauseButton()
  12121. },
  12122. isPx: false,
  12123. builderHeight: this.isPhoneLan()?38:41,
  12124. builderWidth: this.isPhoneLan()?38:41,
  12125. })
  12126. .onClick(() =>{
  12127. this.playOrPause()
  12128. })
  12129. PointLightButton({
  12130. builder: () => {
  12131. this.playNextBuilder()
  12132. },
  12133. isPx: false,
  12134. builderHeight: 26,
  12135. builderWidth: 26,
  12136. })
  12137. .onClick(async () =>{
  12138. await this.playNext()
  12139. })
  12140. this.playModeButton()
  12141. }
  12142. .width('95%')
  12143. .margin({ bottom:this.isCoverOpacity()?0:15 })
  12144. .justifyContent(FlexAlign.SpaceEvenly)
  12145. }
  12146. @Builder
  12147. playPreviousBuilder(){
  12148. Image($r('app.media.ic_previous'))
  12149. .width(32)
  12150. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12151. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12152. }
  12153. @Builder
  12154. playNextBuilder(){
  12155. Image($r('app.media.ic_next'))
  12156. .width(32)
  12157. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12158. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12159. }
  12160. @Builder
  12161. PlayOrPauseButton(){
  12162. Stack() {
  12163. Column() {
  12164. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  12165. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  12166. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  12167. .width(this.isPhoneLan()?38:40)
  12168. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12169. .fillColor(Color.White)
  12170. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12171. }
  12172. // 加载进度圈
  12173. if (this.isPlayerLoading) {
  12174. Progress({value:0,total:100,type:ProgressType.Ring })
  12175. .width(this.isPhoneLan()?40:43)
  12176. .height(this.isPhoneLan()?40:43)
  12177. .color(Color.White)
  12178. .style({ strokeWidth: 5, status: ProgressStatus.LOADING })
  12179. }
  12180. }
  12181. .width(this.isPhoneLan()?38:41)
  12182. .height(this.isPhoneLan()?38:41)
  12183. }
  12184. @Builder
  12185. TopPlayProgressView(){
  12186. Column() {
  12187. Row(){
  12188. Stack(){
  12189. SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
  12190. .fontColor([Color.White])
  12191. .fontSize(21)
  12192. .effectStrategy(1)
  12193. Text(this.fastForwardSeconds)
  12194. .fontColor(Color.White)
  12195. .fontSize(10)
  12196. .fontWeight(FontWeight.Bold)
  12197. }
  12198. .padding({left:12,bottom:6})
  12199. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  12200. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  12201. .onClick(()=>{
  12202. this.backForward()
  12203. })
  12204. Slider({
  12205. value: this.progressValue,
  12206. min: 0,
  12207. max: this.PROGRESS_MAX_VALUE,
  12208. step: 1,
  12209. style: SliderStyle.InSet
  12210. })
  12211. .height(20)
  12212. .blockColor('rgba(255,255,255,1)')
  12213. .trackColor('rgba(255,255,255,0.3)')
  12214. .selectedColor(Color.White)
  12215. .trackThickness(4)
  12216. .showSteps(false)
  12217. .showTips(true)
  12218. .layoutWeight(1)
  12219. .enabled(this.slideEnable)
  12220. .onChange((value: number, mode: SliderChangeMode) => {
  12221. if (mode !== 2) {
  12222. return
  12223. }
  12224. if(this.isSeekTo)
  12225. return
  12226. this.isSeekTo = true;
  12227. this.mDestroyPage = false;
  12228. // 只有播放网盘歌曲时才显示转圈圈
  12229. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  12230. this.showLoadIng();
  12231. }
  12232. let seekValue = value * (this.getActiveDuration() / 100);
  12233. this.seekTo(seekValue + "", "top-progress-slider");
  12234. })
  12235. Stack(){
  12236. SymbolGlyph($r('sys.symbol.arrow_clockwise'))
  12237. .fontColor([Color.White])
  12238. .fontSize(21)
  12239. .effectStrategy(1)
  12240. Text(this.fastForwardSeconds)
  12241. .fontColor(Color.White)
  12242. .fontSize(10)
  12243. .fontWeight(FontWeight.Bold)
  12244. }
  12245. .padding({right:10,bottom:6})
  12246. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  12247. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  12248. .onClick(()=>{
  12249. this.fastForward()
  12250. })
  12251. }
  12252. .justifyContent(FlexAlign.Center)
  12253. .padding({left:20,right:20})
  12254. .width(this.isLandscape?'88%':'95%')
  12255. Row() {
  12256. Text(this.currentTime)
  12257. .fontSize(10)
  12258. .fontColor(Color.White)
  12259. .margin({left:25})
  12260. Blank()
  12261. Text(this.totalTime)
  12262. .fontSize(10)
  12263. .fontColor(Color.White)
  12264. .margin({right:25})
  12265. }
  12266. .width(this.isLandscape?'85%':'90%')
  12267. .height(10)
  12268. }
  12269. .width('100%')
  12270. .alignItems(HorizontalAlign.Center)
  12271. }
  12272. @Builder
  12273. playModeButton(){
  12274. PointLightButton({
  12275. builder: () => {
  12276. this.playModeBuilder()
  12277. },
  12278. isPx: false,
  12279. builderHeight: 26,
  12280. builderWidth: 26,
  12281. })
  12282. .onClick(async () =>{
  12283. this.setLoopMode()
  12284. })
  12285. }
  12286. @Builder
  12287. playModeBuilder(){
  12288. Column() {
  12289. if (this.playType === 0) {
  12290. Image($r('app.media.loop'))
  12291. .width(24)
  12292. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12293. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12294. } else if (this.playType === 1) {
  12295. Image($r('app.media.single'))
  12296. .width(24)
  12297. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12298. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12299. } else if (this.playType === 2) {
  12300. Image($r('app.media.normal_play'))
  12301. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12302. .width(24)
  12303. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12304. } else if (this.playType === 3) {
  12305. Image($r('app.media.random'))
  12306. .width(24)
  12307. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12308. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12309. } else if (this.playType === 4) {
  12310. Image($r('app.media.noloop'))
  12311. .width(24)
  12312. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12313. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12314. }
  12315. }
  12316. }
  12317. //播放进度条
  12318. @Builder
  12319. BottomView(){
  12320. Row() {
  12321. PointLightDefaultButton({
  12322. isSysBol:true,
  12323. pointColor:Color.White,
  12324. imageResource:$r('sys.symbol.rectangle_portrait_rotate'),
  12325. isPx: false,
  12326. builderHeight: 22,
  12327. builderWidth: 22,
  12328. })
  12329. .onClick(async () =>{
  12330. if (this.isLandscape) {
  12331. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  12332. } else {
  12333. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  12334. }
  12335. })
  12336. if(this.currentSong){
  12337. PointLightDefaultButton({
  12338. isSysBol:true,
  12339. pointColor:Color.White,
  12340. imageResource:$r('sys.symbol.rename'),
  12341. isPx: false,
  12342. builderHeight: 22,
  12343. builderWidth: 22,
  12344. })
  12345. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  12346. height: '99%',
  12347. dragBar: true,
  12348. showClose: true,
  12349. preferType: SheetType.BOTTOM,
  12350. title: { title: '编辑标签' }
  12351. })
  12352. .onClick(async () => {
  12353. this.initEditFields(this.currentSong)
  12354. this.tempLyricContent = this.lyricContent
  12355. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  12356. this.lyricConStr = this.tempLyricContent
  12357. }
  12358. this.isShowEdit = !this.isShowEdit;
  12359. })
  12360. }
  12361. PointLightDefaultButton({
  12362. isSysBol:true,
  12363. pointColor:Color.White,
  12364. imageResource:$r('sys.symbol.slider_vertical_3'),
  12365. isPx: false,
  12366. builderHeight: 22,
  12367. builderWidth: 22,
  12368. })
  12369. .onClick(async () => {
  12370. this.isEqualizerSheet = !this.isEqualizerSheet;
  12371. })
  12372. PointLightDefaultButton({
  12373. isSysBol:true,
  12374. pointColor:Color.White,
  12375. imageResource:Utility.getIsFav(this.favList,this.currentSong)?
  12376. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'),
  12377. isPx: false,
  12378. builderHeight: 22,
  12379. builderWidth: 22,
  12380. })
  12381. .onClick(async () => {
  12382. if(this.currentSong){
  12383. this.doFav(this.currentSong)
  12384. }
  12385. })
  12386. this.playListBuilder()
  12387. }
  12388. .width(this.isLandscape?'88%':'95%')
  12389. .justifyContent(FlexAlign.SpaceAround)
  12390. .visibility(this.showSimple?Visibility.None:Visibility.Visible)
  12391. .height(30)
  12392. .animation({
  12393. duration: 666,
  12394. curve: 'ease-in-out' // 可选动画曲线
  12395. })
  12396. }
  12397. @Builder
  12398. fullButton(){
  12399. Column() {
  12400. Image($r('app.media.full_4'))
  12401. .width(25)
  12402. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  12403. .aspectRatio(CommonConstants.ASPECT_RATIO)
  12404. }
  12405. }
  12406. @Builder
  12407. playListBuilder(){
  12408. PointLightDefaultButton({
  12409. isSysBol:true,
  12410. pointColor:Color.White,
  12411. imageResource:$r('sys.symbol.music_note_list'),
  12412. isPx: false,
  12413. builderHeight: 26,
  12414. builderWidth: 26,
  12415. })
  12416. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  12417. height: '95%',
  12418. dragBar: true,
  12419. showClose: true,
  12420. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  12421. blurStyle: BlurStyle.Thin,
  12422. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  12423. title: {
  12424. title:this.getPlayListDisplayCount()==0?Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  12425. :Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  12426. + `(${this.getPlayListDisplayCount()}首)`
  12427. }
  12428. })
  12429. .onClick(() => {
  12430. this.isShowSheetView = !this.isShowSheetView;
  12431. if(this.isPlayListBgGrass){
  12432. this.isFrontWhite = true
  12433. }else{
  12434. this.isFrontWhite = false
  12435. }
  12436. this.scrollIndex()
  12437. // 只有在播放本地音乐时才自动加载完整列表
  12438. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_LOCAL) {
  12439. void this.hydrateFullMediaPlayListIfNeeded();
  12440. }
  12441. })
  12442. }
  12443. //旧版本播放进度条(现在是手机横屏的播放条)
  12444. @Builder
  12445. playProgressView() {
  12446. Row() {
  12447. Column(){
  12448. PointLightDefaultButton({
  12449. isSysBol:true,
  12450. pointColor:Color.White,
  12451. imageResource:$r('sys.symbol.rectangle_portrait_rotate'),
  12452. isPx: false,
  12453. builderHeight: 26,
  12454. builderWidth: 26,
  12455. })
  12456. .onClick(async () =>{
  12457. if (this.isLandscape) {
  12458. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  12459. } else {
  12460. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  12461. }
  12462. })
  12463. }
  12464. .margin({ right: 10,bottom:6})
  12465. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  12466. .animation({
  12467. duration: 666,
  12468. curve: 'ease-in-out' // 可选动画曲线
  12469. })
  12470. Text(this.currentTime)
  12471. .fontSize($r('app.float.slider_font_size'))
  12472. .fontColor(Color.White)
  12473. .margin(3)
  12474. Slider({
  12475. value: this.progressValue,
  12476. min: 0,
  12477. max: this.PROGRESS_MAX_VALUE,
  12478. step: 1,
  12479. style: SliderStyle.InSet
  12480. })
  12481. .width('600px')
  12482. .blockColor('rgba(255,255,255,1)')
  12483. .trackColor('rgba(255,255,255,0.3)')
  12484. .selectedColor(Color.White)
  12485. .trackThickness(5)
  12486. .layoutWeight(1)
  12487. .margin({top:4, left: PlayConstants.PROGRESS_MARGIN_LEFT })
  12488. .showSteps(false)
  12489. .showTips(true)
  12490. .enabled(this.slideEnable)
  12491. .onChange((value: number, mode: SliderChangeMode) => {
  12492. if (mode !== 2) {
  12493. return
  12494. }
  12495. this.isSeekTo = true;
  12496. this.mDestroyPage = false;
  12497. // 只有播放网盘歌曲时才显示转圈圈
  12498. console.info("onecold this.currentSong.type:"+this.currentSong?.type)
  12499. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  12500. this.showLoadIng();
  12501. }
  12502. let seekValue = value * (this.getActiveDuration() / 100);
  12503. this.seekTo(seekValue + "", "landscape-progress-slider");
  12504. })
  12505. Text(this.totalTime)
  12506. .fontSize($r('app.float.slider_font_size'))
  12507. .fontColor(Color.White)
  12508. .margin(3)
  12509. //播放列表
  12510. Column(){
  12511. this.playListBuilder()
  12512. }
  12513. .margin({ left: 10,bottom:6})
  12514. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  12515. .animation({
  12516. duration: 666,
  12517. curve: 'ease-in-out' // 可选动画曲线
  12518. })
  12519. }
  12520. //x5的竖屏模式需要99%
  12521. .width(this.isPhonePortrait() ? '93.4%'
  12522. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  12523. .height(this.isPhoneLan() ? 25 : 33)
  12524. .alignItems(VerticalAlign.Bottom)
  12525. .animation({
  12526. duration: 666,
  12527. curve: 'ease-in-out' // 可选动画曲线
  12528. })
  12529. }
  12530. isBigScreen() {
  12531. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  12532. return true
  12533. }
  12534. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  12535. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  12536. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  12537. return false
  12538. } else {
  12539. return true
  12540. }
  12541. return false
  12542. }
  12543. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  12544. // 添加控制缩放的状态变量
  12545. @State scaleValueImage: number = 1
  12546. @State scaleValueText: number = 1
  12547. @State playDragUiOpacity: number = 1
  12548. @Builder
  12549. private CoverScaleGuideOverlay() {
  12550. Stack() {
  12551. Column({ space: 10 }) {
  12552. SymbolGlyph($r('sys.symbol.arrow_up_left_and_arrow_down_right'))
  12553. .fontSize(34)
  12554. .fontColor([Color.White])
  12555. Text('双指缩放封面')
  12556. .fontSize(16)
  12557. .fontWeight(FontWeight.Bold)
  12558. .fontColor(Color.White)
  12559. Text('在封面区域双指捏合,可调整封面大小')
  12560. .fontSize(12)
  12561. .fontColor(Color.White)
  12562. .opacity(0.88)
  12563. .textAlign(TextAlign.Center)
  12564. }
  12565. .padding({ left: 18, right: 18, top: 16, bottom: 16 })
  12566. .backgroundColor('#A6000000')
  12567. .borderRadius(18)
  12568. .width(this.isPhoneLan() ? 230 : 240)
  12569. }
  12570. .width('100%')
  12571. .height(this.isPhoneLan() ? 260 : 360)
  12572. .align(Alignment.Center)
  12573. .zIndex(10)
  12574. .visibility(this.isShowCoverScaleGuide ? Visibility.Visible : Visibility.None)
  12575. .onClick(() => {
  12576. this.dismissCoverScaleGuide()
  12577. })
  12578. }
  12579. @Builder
  12580. CoverInfo() {
  12581. Column() {
  12582. Stack() {
  12583. Column() {
  12584. //方形封面布局
  12585. if (this.isCoverRectangle) {
  12586. this.RectangleCoverView()
  12587. } else {
  12588. //圆形封面布局
  12589. this.CicleCoverView()
  12590. }
  12591. this.musicNameInfo(false)
  12592. if (this.isPhoneLan()) {
  12593. Text(this.name+"--"+this.artist)
  12594. .fontSize(18)
  12595. .fontWeight(FontWeight.Bold)
  12596. .margin({ top: 13 })
  12597. .textOverflow({ overflow: TextOverflow.Ellipsis })
  12598. .maxLines(1)
  12599. .width('99%')
  12600. .textAlign(TextAlign.Center)
  12601. .fontColor(Color.White)
  12602. }
  12603. }
  12604. .width('100%')
  12605. Column({ space: 8 }) {
  12606. Text(this.name)
  12607. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  12608. .fontWeight(FontWeight.Bold)
  12609. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  12610. .maxLines(1)
  12611. .width('85%')
  12612. .textAlign(TextAlign.Center)
  12613. .fontColor(Color.White)
  12614. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  12615. Text(this.artist)
  12616. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  12617. .fontColor(Color.White)
  12618. .fontWeight(FontWeight.Bold)
  12619. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  12620. }
  12621. .justifyContent(FlexAlign.Start)
  12622. .zIndex(1)
  12623. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  12624. this.CoverScaleGuideOverlay()
  12625. }
  12626. .margin({
  12627. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  12628. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  12629. top: this.isCoverOpacity() ? 0 : 20
  12630. })
  12631. if (this.isShowSingleLineLyric&&this.isPhonePortrait()) {
  12632. this.SingleLyricView()
  12633. }
  12634. if (this.isPhoneLan()) {
  12635. Column() {
  12636. this.playCenterView()
  12637. }
  12638. .position({ left: 28, bottom: 35 })
  12639. } else {
  12640. this.BottomControl()
  12641. }
  12642. }
  12643. .width(CommonConstants.FULL_PERCENT)
  12644. .clip(true)
  12645. }
  12646. //方形封面布局
  12647. @Builder
  12648. RectangleCoverView(){
  12649. Stack({alignContent:Alignment.Center}){
  12650. Image( StrUtil.isNotEmpty(this.cover)?
  12651. this.cover:$r('app.media.alt'))
  12652. .height(this.getRectangleCoverHeight())
  12653. .width(this.getRectangleCoverWidth())
  12654. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  12655. .alt($r('app.media.alt'))
  12656. .margin({ right: 8, left: 8, top: 5 })
  12657. .aspectRatio(1)
  12658. .geometryTransition('cover') // 绑定标识符
  12659. .opacity(this.opacityValueImage)
  12660. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  12661. .bindContextMenu(this.MenuImageBuilder(this.cover), ResponseType.LongPress,
  12662. {
  12663. preview: MenuPreviewMode.IMAGE,
  12664. previewAnimationOptions: { scale: [0.8, 1.0] },
  12665. })
  12666. .bindContextMenu(this.MenuImageBuilder(this.cover), ResponseType.RightClick,
  12667. {
  12668. preview: MenuPreviewMode.IMAGE,
  12669. previewAnimationOptions: { scale: [0.8, 1.0] },
  12670. })
  12671. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  12672. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  12673. .clip(true)
  12674. .rotate({
  12675. x: 0,
  12676. y: 0,
  12677. z: 1,
  12678. angle: this.rotateAngle
  12679. })
  12680. .animation({
  12681. duration: 1000, // 与 setInterval 同步
  12682. curve: Curve.Linear,
  12683. iterations: 1
  12684. })
  12685. .shadow({
  12686. radius: 22,
  12687. type: ShadowType.BLUR,
  12688. color: 'on_primary'
  12689. })
  12690. .onClick(() => {
  12691. this.isMusicBGCover = !this.isMusicBGCover
  12692. })
  12693. .gesture(PinchGesture({ fingers: 2 })
  12694. .onActionUpdate((event: GestureEvent) => {
  12695. this.updateRectangleCoverScaleByPinch(event.scale)
  12696. })
  12697. .onActionEnd(() => {
  12698. this.rectangleCoverPinchValue = this.rectangleCoverScale
  12699. PreferencesUtil.put(SettingPage.RECTANGLE_COVER_SCALE, this.rectangleCoverScale)
  12700. }))
  12701. }
  12702. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  12703. // 设置左下角为缩放中心点
  12704. centerX: '0%',
  12705. centerY: '50%' })
  12706. }
  12707. private getRectangleCoverWidth(): string | number {
  12708. if (this.isHiCar() || this.isCoverOpacity()) {
  12709. return 'auto'
  12710. }
  12711. const baseWidth = this.isBigScreen() ? 72 : this.isCoverTopBig ? 100 : 88
  12712. return `${Math.min(100, Math.max(48, baseWidth * this.rectangleCoverScale))}%`
  12713. }
  12714. private getRectangleCoverHeight(): string | number {
  12715. if (this.isHiCar()) {
  12716. return px2vp(this.windowHeight) * 0.4 * this.rectangleCoverScale
  12717. }
  12718. if (this.isCoverOpacity()) {
  12719. return px2vp(this.windowHeight) * 0.54 * this.rectangleCoverScale
  12720. }
  12721. return 'auto'
  12722. }
  12723. private updateCoverScaleByPinch(scale: number): void {
  12724. this.rectangleCoverScale = Math.min(1.4, Math.max(0.7, this.rectangleCoverPinchValue * scale))
  12725. }
  12726. private updateRectangleCoverScaleByPinch(scale: number): void {
  12727. const dampedScale = 1 + (scale - 1) * 0.45
  12728. this.rectangleCoverScale = Math.min(1.4, Math.max(0.7, this.rectangleCoverPinchValue * dampedScale))
  12729. }
  12730. private persistCoverScaleAfterPinch(): void {
  12731. this.rectangleCoverPinchValue = this.rectangleCoverScale
  12732. PreferencesUtil.put(SettingPage.RECTANGLE_COVER_SCALE, this.rectangleCoverScale)
  12733. }
  12734. @Builder
  12735. CicleCoverView() {
  12736. //圆形封面布局
  12737. Stack({alignContent:Alignment.Center}) {
  12738. Image($r('app.media.ic_music_disc'))
  12739. .width(245)
  12740. .height(245)
  12741. .margin({ right: 20, left: 20 ,top:this.isLandscape?0:50 })
  12742. .aspectRatio(1)
  12743. .opacity(this.isCoverOpacity() ? 0 : 1)
  12744. .visibility(this.isCoverOpacity() ? Visibility.None : Visibility.Visible)
  12745. .borderRadius('100%')
  12746. .align(Alignment.Center)
  12747. .clip(true)
  12748. .rotate({
  12749. angle: this.rotateAngle,
  12750. centerX: "50%",
  12751. centerY: "50%",
  12752. })
  12753. .animation({
  12754. duration: 1000, // 改为 1000ms 与 setInterval 同步
  12755. curve: Curve.Linear,
  12756. iterations: 1 // 只执行一次,下一次更新会触发新的动画
  12757. })
  12758. .shadow({
  12759. radius: 22,
  12760. type: ShadowType.BLUR,
  12761. color: 'on_primary'
  12762. })
  12763. Image( StrUtil.isNotEmpty(this.cover)?
  12764. this.cover:$r('app.media.alt'))
  12765. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
  12766. (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 168))
  12767. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  12768. .alt($r('app.media.alt'))
  12769. .margin({ right: 20, left: 20,
  12770. top:this.isCoverRectangle||this.isLandscape?0:50})
  12771. .aspectRatio(1)
  12772. .opacity(this.opacityValueImage)
  12773. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  12774. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  12775. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  12776. .align(Alignment.Center)//
  12777. .clip(true)
  12778. .shadow({
  12779. radius: 22,
  12780. type: ShadowType.BLUR,
  12781. color: 'on_primary'
  12782. })
  12783. .rotate({
  12784. x: 0,
  12785. y: 0,
  12786. z: 1,
  12787. angle: this.rotateAngle
  12788. })
  12789. .animation({
  12790. duration: 1000, // 与 setInterval 同步
  12791. curve: Curve.Linear,
  12792. iterations: 1
  12793. })
  12794. .onClick(() => {
  12795. this.isMusicBGCover = !this.isMusicBGCover
  12796. })
  12797. // 唱针以左上角为点选择逆时针40度
  12798. Image($r('app.media.ic_music_cover_hand'))
  12799. .height(130)
  12800. .margin({ bottom: 200, top: 0 })
  12801. // .position({ x: this.windowWidth/2, y: 0 })
  12802. .align(Alignment.Top)
  12803. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  12804. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  12805. .visibility(this.isHiCar()||this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  12806. }
  12807. .scale({ x: this.scaleValueImage * this.rectangleCoverScale, y: this.scaleValueImage * this.rectangleCoverScale,
  12808. centerX: '50%',
  12809. centerY: '50%' })
  12810. .priorityGesture(PinchGesture({ fingers: 2 })
  12811. .onActionStart(() => {
  12812. this.rectangleCoverPinchValue = this.rectangleCoverScale
  12813. })
  12814. .onActionUpdate((event: GestureEvent) => {
  12815. this.updateCoverScaleByPinch(event.scale)
  12816. })
  12817. .onActionEnd(() => {
  12818. this.persistCoverScaleAfterPinch()
  12819. }))
  12820. }
  12821. @Builder
  12822. MenuImageBuilder(cover: string|undefined) {
  12823. Menu(){
  12824. MenuItem({
  12825. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.picture_2')),
  12826. content: '查看封面'
  12827. })
  12828. .onClick(async() => {
  12829. if (StrUtil.isEmpty(cover)) {
  12830. ToastUtil.showToast('当前没有可用封面')
  12831. return;
  12832. }
  12833. this.getUIContext().getRouter().pushUrl({
  12834. url: 'pages/WallpaperPreviewPage',
  12835. params: {
  12836. imageUri: cover
  12837. }
  12838. })
  12839. })
  12840. MenuItem({
  12841. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.picture')),
  12842. content: '更换封面'
  12843. })
  12844. .onClick(async() => {
  12845. await this.replaceCurrentSongCoverByAlbum();
  12846. })
  12847. }
  12848. }
  12849. @Builder
  12850. private musicNameInfo(isHidden: boolean) {
  12851. Row(){
  12852. Column({ space: 8 }) {
  12853. Text(this.name)
  12854. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 20)
  12855. .fontWeight(FontWeight.Bold)
  12856. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  12857. .maxLines(1)
  12858. .width('99%')
  12859. .textAlign(TextAlign.Start)
  12860. .fontColor(Color.White)
  12861. Text(this.artist + ' ' + this.currentSong?.album)
  12862. .fontSize(this.isCoverOpacity() ? 12 : 15)
  12863. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  12864. .fontColor(Color.White)
  12865. .textAlign(TextAlign.Start)
  12866. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  12867. .width('99%')
  12868. .maxLines(1)
  12869. }
  12870. .zIndex(1)
  12871. .layoutWeight(1)
  12872. .margin({ left: 15 })
  12873. Blank()
  12874. Row(){
  12875. PointLightDefaultButton({
  12876. isSysBol:true,
  12877. pointColor:Color.White,
  12878. imageResource:this.showSimple?
  12879. $r('sys.symbol.sun_max'):$r('sys.symbol.moon'),
  12880. isPx: false,
  12881. builderHeight: 26,
  12882. builderWidth: 26,
  12883. })
  12884. .onClick(async () => {
  12885. this.showSimple = !this.showSimple
  12886. PreferencesUtil.put('showSimple', this.showSimple)
  12887. })
  12888. }
  12889. .margin({ left: 8,right:8 })
  12890. }
  12891. .width(this.isLandscape?'83%':'90%')
  12892. .scale({ x: this.scaleValueText, y: this.scaleValueText }) // 添加缩放效果
  12893. .opacity(this.playDragUiOpacity)
  12894. .margin({ top:this.isCoverRectangle?10: 0 })
  12895. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  12896. }
  12897. @Builder
  12898. private PlayTitle() {
  12899. Row() {
  12900. Row() {
  12901. Image($r('app.media.ic_back_down'))
  12902. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  12903. .hitTestBehavior(HitTestMode.Transparent)
  12904. }
  12905. .width('100%')
  12906. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  12907. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  12908. .onClick(() => {
  12909. this.setShowPlayFalse()
  12910. })
  12911. Column() {
  12912. AVCastPicker({
  12913. normalColor: Color.White,
  12914. onStateChange: this.onStateVastChange
  12915. })
  12916. .width(24)
  12917. .height(24)
  12918. }
  12919. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  12920. }
  12921. .width(PlayConstants.ROW_WIDTH)
  12922. }
  12923. @Builder
  12924. lyricSettingSheet(isPip: boolean) {
  12925. Scroll() {
  12926. this.lyricSetting(isPip)
  12927. }
  12928. .width('100%')
  12929. .height('100%')
  12930. }
  12931. @Builder
  12932. lyricSetting(isPip: boolean) {
  12933. Column() {
  12934. // 时间调节模块
  12935. if (!isPip) {
  12936. this.BuildTimeControls()
  12937. }
  12938. // 字号控制模块
  12939. this.BuildFontControls(isPip)
  12940. }
  12941. }
  12942. // 歌词时间偏移状态
  12943. @State timeOffset: number = 0.0
  12944. @State currentLyricColor: string = '#FFFFFF'
  12945. @State currentLyricColorPip: string = '#FFFFFF'
  12946. @State currentHighLightLyricColor: string = '#FF4081'
  12947. @State currentHighLightLyricColorPip: string = '#FF4081'
  12948. // 歌词字号状态
  12949. @State currentLyricSize: number = 20
  12950. @State currentLyricSizePip: number = 20
  12951. // 高亮歌词放大倍数
  12952. @State currentHightLyricSize: number = 1.2
  12953. @State currentHightLyricSizePip: number = 1.2
  12954. @State currentLyricLineSpace: number = 10
  12955. @State currentLyricLineSpacePip: number = 10
  12956. @State currentLyricAlignMode: number = 1
  12957. @State currentLyricAlignModePip: number = 1
  12958. @State blurDegree: number = 2
  12959. @State blurDegreePip: number = 2
  12960. @State isShowSelectColor: boolean = false
  12961. @State isShowHLSelectColor: boolean = false
  12962. @State isShowPipBgSelectColor: boolean = false
  12963. @State pipLyWidth: number = 330
  12964. @State pipLyHeight: number = 120
  12965. // 构建颜色选择器
  12966. @Builder
  12967. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  12968. Row({ space: 10 }) {
  12969. HSBColorPicker({
  12970. color: '#FFFFFF',
  12971. radius: 8,
  12972. layout: HSBColorPickerLayout.COLUMN,
  12973. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  12974. '#fa7105'],
  12975. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  12976. this.changeLyricColor(value, isPip, isBGPip)
  12977. })
  12978. .height(250)
  12979. .layoutWeight(1)
  12980. .padding(25)
  12981. }
  12982. .width('66%')
  12983. }
  12984. @State isOpenPip: boolean = false
  12985. @State pipBgIndex: number = 0
  12986. // 构建字号控制器
  12987. @Builder
  12988. BuildFontControls(isPip: boolean) {
  12989. Column() {
  12990. if (isPip) {
  12991. Column() {
  12992. Row() {
  12993. Text('悬浮歌词')
  12994. .margin({ left: 18 })
  12995. .fontSize(15)
  12996. .fontColor(Color.White)
  12997. .fontWeight(480)
  12998. .layoutWeight(1)
  12999. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  13000. .selectedColor(this.themeColor)
  13001. .switchPointColor(Color.White)
  13002. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13003. .margin({ right: 18 })
  13004. .onChange((checked: boolean) => {
  13005. this.isOpenPip = checked;
  13006. if (this.isOpenPip) {
  13007. this.startPip()
  13008. } else {
  13009. this.stopPip()
  13010. }
  13011. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  13012. })
  13013. .width(50)
  13014. .height(30);
  13015. }
  13016. .height(55)
  13017. }
  13018. .backgroundColor(Color.Transparent)
  13019. .borderRadius(15)
  13020. .margin({
  13021. left: 30,
  13022. right: 30,
  13023. top: 0,
  13024. bottom: 20
  13025. })
  13026. .padding(0)
  13027. .border({
  13028. color: Color.White,
  13029. width: 1.8
  13030. })
  13031. }else{
  13032. Row() {
  13033. Row() {
  13034. Text(`迷你歌词:`)
  13035. .fontSize(14)
  13036. .fontColor(Color.White)
  13037. .width(88)
  13038. Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
  13039. .selectedColor(this.themeColor)
  13040. .switchPointColor(Color.White)
  13041. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13042. .onChange((checked: boolean) => {
  13043. this.isShowSingleLineLyric = checked;
  13044. PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
  13045. })
  13046. .width(50)
  13047. .height(30)
  13048. .alignSelf(ItemAlign.Start)
  13049. .margin({ left: 12 })
  13050. Blank()
  13051. }
  13052. .layoutWeight(1)
  13053. Row() {
  13054. Text(`逐字歌词:`)
  13055. .fontSize(14)
  13056. .fontColor(Color.White)
  13057. .width(88)
  13058. Toggle({ type: ToggleType.Switch, isOn: this.isEnableWordByWordLyric })
  13059. .selectedColor(this.themeColor)
  13060. .switchPointColor(Color.White)
  13061. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13062. .onChange((checked: boolean) => {
  13063. this.isEnableWordByWordLyric = checked;
  13064. PreferencesUtil.putSync(SettingPage.IS_ENABLE_WORD_BY_WORD_LYRIC, this.isEnableWordByWordLyric)
  13065. this.syncWordByWordLyricMode()
  13066. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  13067. })
  13068. .width(50)
  13069. .height(30)
  13070. .alignSelf(ItemAlign.Start)
  13071. .margin({ left: 12 })
  13072. Blank()
  13073. }
  13074. .layoutWeight(1)
  13075. }
  13076. .width('100%')
  13077. .margin({
  13078. left: 20,
  13079. right: 15,
  13080. top: 10,
  13081. bottom: 10
  13082. })
  13083. }
  13084. if (!isPip) {
  13085. Row() {
  13086. Row() {
  13087. Text(`歌词发光:`)
  13088. .fontSize(14)
  13089. .fontColor(Color.White)
  13090. .width(88)
  13091. Toggle({ type: ToggleType.Switch, isOn: this.isLightText })
  13092. .selectedColor(this.themeColor)
  13093. .switchPointColor(Color.White)
  13094. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13095. .onChange((checked: boolean) => {
  13096. this.isLightText = checked;
  13097. PreferencesUtil.putSync(SettingPage.IS_LIGHT_TEXT, this.isLightText)
  13098. this.syncLyricLightTextMode()
  13099. })
  13100. .width(50)
  13101. .height(30)
  13102. .alignSelf(ItemAlign.Start)
  13103. .margin({ left: 12 })
  13104. Blank()
  13105. }
  13106. .layoutWeight(1)
  13107. Row() {
  13108. Text(`高亮居中:`)
  13109. .fontSize(14)
  13110. .fontColor(Color.White)
  13111. .width(88)
  13112. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  13113. .selectedColor(this.themeColor)
  13114. .switchPointColor(Color.White)
  13115. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13116. .onChange((checked: boolean) => {
  13117. this.isHightLightCenter = checked;
  13118. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  13119. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  13120. })
  13121. .width(50)
  13122. .height(30)
  13123. .alignSelf(ItemAlign.Start)
  13124. .margin({ left: 12 })
  13125. Blank()
  13126. }
  13127. .layoutWeight(1)
  13128. }
  13129. .width('100%')
  13130. .margin({
  13131. left: 20,
  13132. right: 15,
  13133. top: 10,
  13134. bottom: 10
  13135. })
  13136. }
  13137. Row() {
  13138. Text(`歌词居中:`)
  13139. .fontSize(14)
  13140. .fontColor(Color.White)
  13141. Row() {
  13142. ForEach(['居中', '居左'], (size: string, index: number) => {
  13143. Button(size)
  13144. .width(60)
  13145. .height(28)
  13146. .fontSize(12)
  13147. .fontColor('#FFFFFF')
  13148. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  13149. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  13150. .border({
  13151. color: (!isPip && this.currentLyricAlignMode === index) ||
  13152. (isPip && this.currentLyricAlignModePip === index) ?
  13153. '#007DFF' : '#DDDDDD',
  13154. width: 1.8
  13155. })
  13156. .onClick(() => {
  13157. this.setLyricAlignMode(index, isPip)
  13158. })
  13159. .margin({ left: 10, right: 8 })
  13160. })
  13161. }
  13162. .layoutWeight(1)
  13163. Blank()
  13164. }
  13165. .width('100%')
  13166. .margin({
  13167. top: 10,
  13168. bottom: 10,
  13169. right: 15,
  13170. left: 20
  13171. })
  13172. if (isPip) {
  13173. Row() {
  13174. Text(`悬浮背景:`)
  13175. .fontSize(14)
  13176. .fontColor(Color.White)
  13177. Select([
  13178. { value: CommonConstants.PIP_LYRIC_BG[0] },
  13179. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  13180. .font({ size: 13, weight: FontWeight.Medium })
  13181. .fontColor(Color.White)
  13182. .margin({ left: 10 })
  13183. .selected(this.pipBgIndex)
  13184. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  13185. .onSelect(async (_index: number, text?: string | undefined) => {
  13186. this.pipBgIndex = _index
  13187. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  13188. if (this.pipBgIndex === 0) {
  13189. if (this.cover) {
  13190. this.pipBg = this.cover
  13191. } else {
  13192. this.pipBg = this.imageColor
  13193. }
  13194. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  13195. } else {
  13196. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  13197. }
  13198. })
  13199. Column() {
  13200. }
  13201. .backgroundColor(this.pipBg)
  13202. .margin({ left: 10, right: 10 })
  13203. .borderRadius(20)
  13204. .height(28)
  13205. .width(28)
  13206. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13207. Row() {
  13208. SymbolGlyph($r('sys.symbol.paintbrush'))
  13209. .fontColor([Color.White])
  13210. .effectStrategy(1)
  13211. Text(`选择颜色`)
  13212. .fontSize(13)
  13213. .margin({ left: 10 })
  13214. .fontColor(Color.White)
  13215. }
  13216. }
  13217. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  13218. .backgroundColor(Color.Transparent)
  13219. .border({
  13220. color: '#FFFFFF',
  13221. radius: 20,
  13222. width: 1.8
  13223. })
  13224. .height(36)
  13225. .width(110)
  13226. .onClick(() => {
  13227. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  13228. })
  13229. .bindPopup(this.isShowPipBgSelectColor, {
  13230. builder: this.SelectColor(false, isPip, true),
  13231. placement: Placement.Top,
  13232. mask: { color: '#33000000' },
  13233. enableArrow: false, //是否显示箭头
  13234. showInSubWindow: false,
  13235. onStateChange: (e) => {
  13236. if (!e.isVisible) {
  13237. this.isShowPipBgSelectColor = false
  13238. }
  13239. }
  13240. })
  13241. }
  13242. .width('100%')
  13243. .margin({ bottom: 5, right: 15, left: 20 })
  13244. }
  13245. Row() {
  13246. Text(`歌词颜色:`)
  13247. .fontSize(14)
  13248. .fontColor(Color.White)
  13249. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  13250. .fontSize(15)
  13251. .fontColor(Color.White)
  13252. .margin({ left: 6, right: 6 })
  13253. Column() {
  13254. }
  13255. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  13256. .margin({ right: 12 })
  13257. .borderRadius(20)
  13258. .height(28)
  13259. .width(28)
  13260. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13261. Row() {
  13262. SymbolGlyph($r('sys.symbol.paintbrush'))
  13263. .fontColor([Color.White])
  13264. .effectStrategy(1)
  13265. Text(`选择颜色`)
  13266. .fontSize(13)
  13267. .margin({ left: 10 })
  13268. .fontColor(Color.White)
  13269. }
  13270. }
  13271. .backgroundColor(Color.Transparent)
  13272. .border({
  13273. color: '#FFFFFF',
  13274. radius: 20,
  13275. width: 1.8
  13276. })
  13277. .height(36)
  13278. .width(110)
  13279. .onClick(() => {
  13280. this.isShowSelectColor = !this.isShowSelectColor
  13281. })
  13282. .bindPopup(this.isShowSelectColor, {
  13283. builder: this.SelectColor(false, isPip),
  13284. placement: Placement.Top,
  13285. mask: { color: '#33000000' },
  13286. enableArrow: false, //是否显示箭头
  13287. showInSubWindow: false,
  13288. onStateChange: (e) => {
  13289. if (!e.isVisible) {
  13290. this.isShowSelectColor = false
  13291. }
  13292. }
  13293. })
  13294. }
  13295. .width('100%')
  13296. .margin({
  13297. top: 10,
  13298. bottom: 10,
  13299. right: 15,
  13300. left: 20
  13301. })
  13302. Row() {
  13303. Text(`高亮颜色:`)
  13304. .fontSize(14)
  13305. .fontColor(Color.White)
  13306. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  13307. .fontSize(15)
  13308. .fontColor(Color.White)
  13309. .margin({ left: 6, right: 6 })
  13310. Column() {
  13311. }
  13312. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  13313. .margin({ right: 12 })
  13314. .borderRadius(20)
  13315. .height(28)
  13316. .width(28)
  13317. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13318. Row() {
  13319. SymbolGlyph($r('sys.symbol.paintbrush'))
  13320. .fontColor([Color.White])
  13321. .effectStrategy(1)
  13322. Text(`选择颜色`)
  13323. .fontSize(13)
  13324. .margin({ left: 10 })
  13325. .fontColor(Color.White)
  13326. }
  13327. }
  13328. .backgroundColor(Color.Transparent)
  13329. .border({
  13330. color: '#FFFFFF',
  13331. radius: 20,
  13332. width: 1.8
  13333. })
  13334. .height(36)
  13335. .width(110)
  13336. .onClick(() => {
  13337. this.isShowHLSelectColor = !this.isShowHLSelectColor
  13338. })
  13339. .bindPopup(this.isShowHLSelectColor, {
  13340. builder: this.SelectColor(true, isPip),
  13341. placement: Placement.Top,
  13342. mask: { color: '#33000000' },
  13343. enableArrow: false, //是否显示箭头
  13344. showInSubWindow: false,
  13345. onStateChange: (e) => {
  13346. if (!e.isVisible) {
  13347. this.isShowHLSelectColor = false
  13348. }
  13349. }
  13350. })
  13351. }
  13352. .width('100%')
  13353. .margin({
  13354. top: 10,
  13355. bottom: 10,
  13356. right: 15,
  13357. left: 20
  13358. })
  13359. if (isPip) {
  13360. Row() {
  13361. Text(`显示宽度:`)
  13362. .fontSize(14)
  13363. .fontColor(Color.White)
  13364. Slider({
  13365. value: this.pipLyWidth,
  13366. min: 10,
  13367. max: 800,
  13368. step: 1,
  13369. style: SliderStyle.OutSet
  13370. })
  13371. .blockColor(this.themeColor)
  13372. .trackColor($r('app.color.speed_text_color'))
  13373. .selectedColor(Color.White)
  13374. .trackThickness(6)
  13375. .onChange((value: number) => {
  13376. this.pipLyWidth = value
  13377. if (this.pipController) {
  13378. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  13379. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  13380. }
  13381. })
  13382. .layoutWeight(1)
  13383. }
  13384. .justifyContent(FlexAlign.Start)
  13385. .margin({
  13386. left: 20,
  13387. right: 15,
  13388. top: 5,
  13389. bottom: 5
  13390. })
  13391. Row() {
  13392. Text(`显示高度:`)
  13393. .fontSize(14)
  13394. .fontColor(Color.White)
  13395. Slider({
  13396. value: this.pipLyHeight,
  13397. min: 10,
  13398. max: 1000,
  13399. step: 1,
  13400. style: SliderStyle.OutSet
  13401. })
  13402. .blockColor(this.themeColor)
  13403. .trackColor($r('app.color.speed_text_color'))
  13404. .selectedColor(Color.White)
  13405. .trackThickness(6)
  13406. .onChange((value: number) => {
  13407. this.pipLyHeight = value
  13408. if (this.pipController) {
  13409. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  13410. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  13411. }
  13412. })
  13413. .layoutWeight(1)
  13414. }
  13415. .justifyContent(FlexAlign.Start)
  13416. .margin({
  13417. left: 20,
  13418. right: 15,
  13419. top: 5,
  13420. bottom: 5
  13421. })
  13422. }
  13423. Row() {
  13424. Text(`歌词字号:`)
  13425. .fontSize(14)
  13426. .fontColor(Color.White)
  13427. Slider({
  13428. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  13429. min: 12,
  13430. max: 30,
  13431. step: 0.1,
  13432. style: SliderStyle.OutSet
  13433. })
  13434. .blockColor(this.themeColor)
  13435. .trackColor($r('app.color.speed_text_color'))
  13436. .selectedColor(Color.White)
  13437. .trackThickness(6)
  13438. .onChange((value: number) => {
  13439. this.setLyricTextSize(value, isPip)
  13440. })
  13441. .layoutWeight(1)
  13442. .margin({ right: 3 })
  13443. Text(this.getLyricSizeDisplayValue(isPip))
  13444. .fontSize(13)
  13445. .fontColor(Color.White)
  13446. .textAlign(TextAlign.Start)
  13447. }
  13448. .width('100%')
  13449. .margin({
  13450. left: 20,
  13451. right: 15,
  13452. top: 5,
  13453. bottom: 5
  13454. })
  13455. Row() {
  13456. Text(`高亮倍数:`)
  13457. .fontSize(14)
  13458. .fontColor(Color.White)
  13459. Slider({
  13460. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  13461. min: 1,
  13462. max: 2,
  13463. step: 0.1,
  13464. style: SliderStyle.OutSet
  13465. })
  13466. .blockColor(this.themeColor)
  13467. .trackColor($r('app.color.speed_text_color'))
  13468. .selectedColor(Color.White)
  13469. .trackThickness(6)
  13470. .onChange((value: number) => {
  13471. this.setHighLyricTextSize(value, isPip)
  13472. })
  13473. .layoutWeight(1)
  13474. .margin({ right: 3 })
  13475. Text(this.getHighLyricSizeDisplayValue(isPip))
  13476. .fontSize(13)
  13477. .fontColor(Color.White)
  13478. .textAlign(TextAlign.Start)
  13479. }
  13480. .width('100%')
  13481. .margin({
  13482. left: 20,
  13483. right: 15,
  13484. top: 5,
  13485. bottom: 5
  13486. })
  13487. Row() {
  13488. Text(`歌词间隙:`)
  13489. .fontSize(14)
  13490. .fontColor(Color.White)
  13491. Slider({
  13492. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  13493. min: 0,
  13494. max: 100,
  13495. step: 1,
  13496. style: SliderStyle.OutSet
  13497. })
  13498. .blockColor(this.themeColor)
  13499. .trackColor($r('app.color.speed_text_color'))
  13500. .selectedColor(Color.White)
  13501. .trackThickness(6)
  13502. .onChange((value: number) => {
  13503. this.setLyricLineSpace(value, isPip)
  13504. })
  13505. .layoutWeight(1)
  13506. .margin({ right: 3 })
  13507. Text(this.getLyricLineSpaceDisplayValue(isPip))
  13508. .fontSize(13)
  13509. .fontColor(Color.White)
  13510. .textAlign(TextAlign.Start)
  13511. }
  13512. .width('100%')
  13513. .margin({
  13514. left: 20,
  13515. right: 15,
  13516. top: 5,
  13517. bottom: 5
  13518. })
  13519. //取值间隔为100,默认为400,取值越大,字体越粗
  13520. Row() {
  13521. Text(`歌词字重:`)
  13522. .fontSize(14)
  13523. .fontColor(Color.White)
  13524. Slider({
  13525. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  13526. min: 100,
  13527. max: 900,
  13528. step: 100,
  13529. style: SliderStyle.OutSet
  13530. })
  13531. .blockColor(this.themeColor)
  13532. .trackColor($r('app.color.speed_text_color'))
  13533. .selectedColor(Color.White)
  13534. .trackThickness(6)
  13535. .onChange((value: number) => {
  13536. if (isPip) {
  13537. this.lyricTextWeightPip = value
  13538. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  13539. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  13540. } else {
  13541. this.lyricTextWeight = value
  13542. this.lyricController.setTextWeight(this.lyricTextWeight)
  13543. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  13544. }
  13545. })
  13546. .layoutWeight(1)
  13547. .margin({ right: 3 })
  13548. Text(this.getLyricTextWeightDisplayValue(isPip))
  13549. .fontSize(13)
  13550. .fontColor(Color.White)
  13551. .textAlign(TextAlign.Start)
  13552. }
  13553. .width('100%')
  13554. .margin({
  13555. left: 20,
  13556. right: 15,
  13557. top: 5,
  13558. bottom: 5
  13559. })
  13560. Row() {
  13561. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  13562. this.pushLyricButton($r('app.media.share2'), 2, '分享歌词')
  13563. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  13564. // this.pushLyricButton($r('app.media.white_search'), 1, '繁体转简体')
  13565. }
  13566. .justifyContent(FlexAlign.Center)
  13567. .margin({ top: 3, bottom: 10 })
  13568. }
  13569. .width('88%')
  13570. }
  13571. private getLyricSizeDisplayValue(isPip: boolean): string {
  13572. const lyricSize = isPip ? this.currentLyricSizePip : this.currentLyricSize;
  13573. return lyricSize.toFixed(1);
  13574. }
  13575. private getHighLyricSizeDisplayValue(isPip: boolean): string {
  13576. const highLyricSize = isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize;
  13577. return highLyricSize.toFixed(1);
  13578. }
  13579. private getLyricLineSpaceDisplayValue(isPip: boolean): string {
  13580. const lyricLineSpace = isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace;
  13581. return Math.round(lyricLineSpace).toString();
  13582. }
  13583. private getLyricTextWeightDisplayValue(isPip: boolean): string {
  13584. const lyricTextWeightValue = isPip ? this.lyricTextWeightPip : this.lyricTextWeight;
  13585. return Math.round(lyricTextWeightValue).toString();
  13586. }
  13587. private setBlurDegree(index: number, isPip: boolean) {
  13588. if (isPip) {
  13589. this.blurDegreePip = index
  13590. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  13591. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  13592. } else {
  13593. this.blurDegree = index
  13594. this.lyricController.setBlurDegree(this.blurDegree)
  13595. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  13596. }
  13597. }
  13598. private setLyricAlignMode(index: number, isPip: boolean) {
  13599. if (isPip) {
  13600. this.currentLyricAlignModePip = index
  13601. if (this.currentLyricAlignModePip === 1) {
  13602. this.lyricControllerXF.setAlignMode("left")
  13603. } else {
  13604. this.lyricControllerXF.setAlignMode("center")
  13605. }
  13606. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  13607. } else {
  13608. this.currentLyricAlignMode = index
  13609. if (this.currentLyricAlignMode === 1) {
  13610. this.lyricController.setAlignMode("left")
  13611. } else {
  13612. this.lyricController.setAlignMode("center")
  13613. }
  13614. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  13615. }
  13616. }
  13617. private setLyricTextSize(index: number, isPip: boolean) {
  13618. if (isPip) {
  13619. this.currentLyricSizePip = index
  13620. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  13621. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  13622. } else {
  13623. this.currentLyricSize = index
  13624. this.lyricController.setTextSize(this.currentLyricSize)
  13625. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  13626. }
  13627. }
  13628. private setHighLyricTextSize(scale: number, isPip: boolean) {
  13629. if (isPip) {
  13630. this.currentHightLyricSizePip = scale
  13631. this.lyricControllerXF
  13632. .setHighlightScale(this.currentHightLyricSizePip)
  13633. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  13634. } else {
  13635. this.currentHightLyricSize = scale
  13636. this.lyricController
  13637. .setHighlightScale(this.currentHightLyricSize)
  13638. PreferencesUtil.putSync('HighLyricTextSize', scale)
  13639. }
  13640. }
  13641. private setLyricLineSpace(index: number, isPip: boolean) {
  13642. if (isPip) {
  13643. this.currentLyricLineSpacePip = index
  13644. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  13645. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  13646. } else {
  13647. this.currentLyricLineSpace = index
  13648. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  13649. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  13650. }
  13651. }
  13652. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  13653. LogUtil.info('onecold isBG = ' + isBG)
  13654. if (isBG) { //如果是设置悬浮背景
  13655. this.pipBg = color
  13656. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  13657. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  13658. return
  13659. }
  13660. if (isPip) {
  13661. this.currentLyricColorPip = color
  13662. this.lyricControllerXF
  13663. .setTextColor(this.currentLyricColorPip)
  13664. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  13665. } else {
  13666. this.currentLyricColor = color
  13667. this.lyricController
  13668. .setTextColor(this.currentLyricColor)
  13669. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  13670. }
  13671. }
  13672. private changeLyricHightLightColor(color: string, isPip: boolean) {
  13673. if (isPip) {
  13674. this.currentHighLightLyricColorPip = color
  13675. this.lyricControllerXF
  13676. .setHighlightColor(this.currentHighLightLyricColorPip)
  13677. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  13678. } else {
  13679. this.currentHighLightLyricColor = color
  13680. this.lyricController
  13681. .setHighlightColor(this.currentHighLightLyricColor)
  13682. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  13683. }
  13684. }
  13685. // 构建时间控制器
  13686. @Builder
  13687. BuildTimeControls() {
  13688. Column() {
  13689. // 时间显示
  13690. Text(this.getTimeText())
  13691. .fontSize(18)
  13692. .fontColor(Color.White)
  13693. .margin({ bottom: 10 })
  13694. Row() {
  13695. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  13696. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  13697. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  13698. }
  13699. .justifyContent(FlexAlign.Center)
  13700. }
  13701. .margin({ top: 12, bottom: 8 })
  13702. }
  13703. // 精度按钮组件
  13704. @Builder
  13705. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  13706. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13707. Column() {
  13708. Image(icon)
  13709. .width(28)
  13710. .margin({ bottom: 5 })
  13711. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  13712. Text(label)
  13713. .fontSize(12)
  13714. .fontColor('#FFFFFF')
  13715. }
  13716. }
  13717. .backgroundColor(Color.Transparent)
  13718. .enabled(!this.isButtonDisabled(step))
  13719. .onClick(() => this.handlePrecisionAdjust(step))
  13720. .padding(5)
  13721. .width(66)
  13722. .height(66)
  13723. .margin({ left: 18, right: 18 })
  13724. .border({
  13725. color: '#FFFFFF',
  13726. width: 1.8
  13727. })
  13728. }
  13729. private handlePrecisionAdjust(step: number) {
  13730. if (step === 0) {
  13731. this.timeOffset = 0
  13732. this.saveLyricTimeOffset()
  13733. return
  13734. }
  13735. // 精度处理:保留1位小数
  13736. const newOffset = Number((this.timeOffset + step).toFixed(5))
  13737. // 边界保护(±15.0秒)
  13738. if (newOffset < -30.0 || newOffset > 30.0) {
  13739. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  13740. return
  13741. }
  13742. // 状态更新
  13743. this.timeOffset = newOffset
  13744. // 保存歌词时间偏移
  13745. this.saveLyricTimeOffset()
  13746. }
  13747. // 按钮禁用逻辑
  13748. private isButtonDisabled(step: number): boolean {
  13749. const futureOffset = this.timeOffset + step
  13750. return (futureOffset < -30.0) || (futureOffset > 30.0)
  13751. }
  13752. // 时间显示文本升级
  13753. private getTimeText(): string {
  13754. const absValue = Math.abs(this.timeOffset)
  13755. return this.timeOffset === 0
  13756. ? '歌词时间已重置'
  13757. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  13758. }
  13759. /**
  13760. * 获取当前歌曲的唯一标识key
  13761. * 使用歌曲的filePath作为唯一标识
  13762. */
  13763. private getLyricOffsetKey(): string {
  13764. if (this.currentSong && StrUtil.isNotEmpty(this.currentSong.filePath)) {
  13765. // 使用MD5对filePath进行加密,作为存储key
  13766. return 'lyric_offset_' + MD5.digestSync(this.currentSong.filePath)
  13767. }
  13768. return ''
  13769. }
  13770. /**
  13771. * 保存当前歌曲的歌词时间偏移
  13772. */
  13773. private saveLyricTimeOffset(): void {
  13774. try {
  13775. const key = this.getLyricOffsetKey()
  13776. if (StrUtil.isEmpty(key)) {
  13777. console.warn('heanup saveLyricTimeOffset: key is empty')
  13778. return
  13779. }
  13780. PreferencesUtil.putSync(key, this.timeOffset)
  13781. console.info('heanup saveLyricTimeOffset: key=' + key + ', offset=' + this.timeOffset)
  13782. } catch (e) {
  13783. console.error('heanup saveLyricTimeOffset error: ' + JSON.stringify(e))
  13784. }
  13785. }
  13786. /**
  13787. * 加载当前歌曲的歌词时间偏移
  13788. */
  13789. private loadLyricTimeOffset(): void {
  13790. try {
  13791. const key = this.getLyricOffsetKey()
  13792. if (StrUtil.isEmpty(key)) {
  13793. console.warn('heanup loadLyricTimeOffset: key is empty')
  13794. return
  13795. }
  13796. const savedOffset = PreferencesUtil.getNumberSync(key, 0)
  13797. if (savedOffset !== 0) {
  13798. this.timeOffset = savedOffset
  13799. console.info('heanup loadLyricTimeOffset: key=' + key + ', offset=' + savedOffset)
  13800. }else{
  13801. this.timeOffset = 0
  13802. }
  13803. } catch (e) {
  13804. console.error('heanup loadLyricTimeOffset error: ' + JSON.stringify(e))
  13805. }
  13806. }
  13807. // 导入 本地歌词 搜索歌词
  13808. @Builder
  13809. pushLyricButton(icon: Resource, step: number, label: string) {
  13810. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13811. Row() {
  13812. Image(icon)
  13813. .width(14)
  13814. .margin({ left: 13 })
  13815. Text(label)
  13816. .fontSize(12)
  13817. .margin({ left: 6 })
  13818. .fontColor('#FFFFFF')
  13819. }
  13820. }
  13821. .onClick(() => {
  13822. switch (step) {
  13823. case 0:
  13824. this.callFilePickerSelectFileForLyric()
  13825. break;
  13826. case 1:
  13827. //判断有没有设置api
  13828. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  13829. this.isLyricSetting = false
  13830. this.showTipsDialog()
  13831. return
  13832. }
  13833. if (StrUtil.isNotEmpty(this.videoUrl)) {
  13834. ToastUtil.showToast('正在获取')
  13835. this.isLyricSetting = false
  13836. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  13837. this.initLyric(lyricPath, true);
  13838. }
  13839. break;
  13840. case 2:
  13841. this.isLyricSetting = false
  13842. this.openLyricCopySheet()
  13843. break;
  13844. }
  13845. })
  13846. .padding(5)
  13847. .layoutWeight(1)
  13848. .backgroundColor(Color.Transparent)
  13849. .height(40)
  13850. .margin({ left: 4, right: 4 })
  13851. .border({
  13852. color: '#FFFFFF',
  13853. radius: 20,
  13854. width: 1.8
  13855. })
  13856. }
  13857. showVipDialog() {
  13858. DialogHelper.showCustomContentDialog({
  13859. dialogId: 'vip',
  13860. title: "友情提示",
  13861. autoCancel: false, //点击遮障层时,不关闭弹窗
  13862. backCancel: true, //点击返回键,不关闭弹窗
  13863. contentBuilder: () => {
  13864. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  13865. },
  13866. buttons: [],
  13867. })
  13868. }
  13869. //去赞助的自定义内容
  13870. @Builder
  13871. customVipBuilder(content: string) {
  13872. Column() {
  13873. Text(content)
  13874. .fontColor(Color.Gray)
  13875. .fontSize(16)
  13876. .alignSelf(ItemAlign.Start)
  13877. .margin({ bottom: 15 })
  13878. .fontSize(16)
  13879. Row() {
  13880. Button('取消')
  13881. .fontColor(Color.White)
  13882. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  13883. .height(50)
  13884. .layoutWeight(1)
  13885. .stateEffect(true)
  13886. .margin({ right: 6 })
  13887. .onClick(() => {
  13888. DialogHelper.closeDialog('vip'); //关闭弹框
  13889. })
  13890. Button('开通')
  13891. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  13892. .layoutWeight(1)
  13893. .height(50)
  13894. .backgroundColor(this.themeColor)
  13895. .stateEffect(true)
  13896. .margin({ left: 6 })
  13897. .onClick(() => {
  13898. DialogHelper.closeDialog('vip'); //关闭弹框
  13899. this.isShowPlay = false
  13900. this.mType = 1 //跳转到用户中心
  13901. // router.pushUrl({
  13902. // url: 'pages/VipPage'
  13903. // }, router.RouterMode.Single);
  13904. })
  13905. }
  13906. }
  13907. .width("100%")
  13908. .padding(10)
  13909. }
  13910. showTipsDialog() {
  13911. DialogHelper.showCustomContentDialog({
  13912. dialogId: 'tips',
  13913. title: "友情提示",
  13914. autoCancel: false, //点击遮障层时,不关闭弹窗
  13915. backCancel: true, //点击返回键,不关闭弹窗
  13916. contentBuilder: () => {
  13917. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  13918. },
  13919. buttons: [],
  13920. })
  13921. }
  13922. @Builder
  13923. customTipsBuilder(content: string) {
  13924. Column() {
  13925. Text(content)
  13926. .fontColor(Color.Gray)
  13927. .fontSize(16)
  13928. .alignSelf(ItemAlign.Start)
  13929. .margin({ bottom: 15 })
  13930. .fontSize(16)
  13931. Row() {
  13932. Button('取消')
  13933. .fontColor(Color.White)
  13934. .backgroundColor(this.themeColor)
  13935. .height(50)
  13936. .layoutWeight(1)
  13937. .stateEffect(true)
  13938. .margin({ right: 6 })
  13939. .onClick(() => {
  13940. DialogHelper.closeDialog('tips'); //关闭弹框
  13941. })
  13942. Button('跳转')
  13943. .fontColor(Color.White)//
  13944. .layoutWeight(1)
  13945. .height(50)
  13946. .backgroundColor(this.themeColor)
  13947. .stateEffect(true)
  13948. .margin({ left: 6 })
  13949. .onClick(() => {
  13950. DialogHelper.closeDialog('tips'); //关闭弹框
  13951. this.isShowEdit = false
  13952. this.longItemFilePath = ''
  13953. // if(this.isGridMusic&&!this.isShowPlay){
  13954. // this.longItemFilePath== ''
  13955. // }else{
  13956. // this.isShowEdit = false
  13957. // }
  13958. this.isShowMoreView = false;
  13959. this.isShowPlay = false
  13960. this.mType = 4
  13961. // router.pushUrl({
  13962. // url: 'pages/SettingPage'
  13963. // }, router.RouterMode.Single);
  13964. })
  13965. }
  13966. }
  13967. .width("100%")
  13968. .padding(10)
  13969. }
  13970. @Builder
  13971. PlayMoreSheet() {
  13972. Column() {
  13973. this.MoreList()
  13974. }
  13975. .width('100%')
  13976. .height('100%')
  13977. }
  13978. @Builder
  13979. MoreList() {
  13980. Scroll() {
  13981. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  13982. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  13983. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13984. Row() {
  13985. if (more.id === 3&&this.currentSong) {
  13986. Image(more.image)
  13987. .width(24)
  13988. .height(24)
  13989. .margin({ left: 10, right: 10 })
  13990. Text(more.title)
  13991. .fontSize(16)
  13992. .fontColor(Color.White)
  13993. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  13994. height: '99%',
  13995. dragBar: true,
  13996. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  13997. showClose: true,
  13998. blurStyle: BlurStyle.Thin,
  13999. backgroundColor: Color.Transparent,
  14000. title: { title: '歌曲信息' }
  14001. })
  14002. } else if (more.id === 15 && this.currentSong) { //编辑标签
  14003. Image(more.image)
  14004. .width(24)
  14005. .height(24)
  14006. .margin({ left: 10, right: 10 })
  14007. Text(more.title)
  14008. .fontSize(16)
  14009. .fontColor(Color.White)
  14010. } else if (more.id === 5) { //定时关闭
  14011. Image(more.image)
  14012. .width(24)
  14013. .height(24)
  14014. .margin({ left: 10, right: 10 })
  14015. Text(more.title)
  14016. .fontSize(16)
  14017. .fontColor(Color.White)
  14018. .onClick(() => {
  14019. this.doMore(more.id)
  14020. })
  14021. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  14022. height: this.isCoverOpacity() ? '95%' : '95%',
  14023. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  14024. dragBar: true,
  14025. showClose: true,
  14026. title: { title: $r('app.string.time_close') }
  14027. })
  14028. } else if (more.id === 2) { //歌词设置
  14029. Image(more.image)
  14030. .width(24)
  14031. .height(24)
  14032. .margin({ left: 10, right: 10 })
  14033. Text(more.title)
  14034. .fontSize(16)
  14035. .fontColor(Color.White)
  14036. } else if (more.id === 16) { //悬浮歌词设置
  14037. Image(more.image)
  14038. .width(24)
  14039. .height(24)
  14040. .margin({ left: 10, right: 10 })
  14041. Text(more.title)
  14042. .fontSize(16)
  14043. .fontColor(Color.White)
  14044. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  14045. height: '99%',
  14046. dragBar: true,
  14047. preferType: SheetType.CENTER,
  14048. showClose: true,
  14049. blurStyle: BlurStyle.Thin,
  14050. backgroundColor: Color.Transparent,
  14051. title: { title: '悬浮歌词' }
  14052. })
  14053. } else if (more.id === 11) {
  14054. Image(more.image)
  14055. .width(24)
  14056. .height(24)
  14057. .margin({ left: 10, right: 10 })
  14058. Text(more.title)
  14059. .fontSize(16)
  14060. .fontColor(Color.White)
  14061. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  14062. height: this.isCoverOpacity() ? '95%' : '60%',
  14063. dragBar: true,
  14064. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  14065. showClose: true,
  14066. blurStyle: BlurStyle.Thin,
  14067. backgroundColor: Color.Transparent,
  14068. title: { title: '跳过头尾' }
  14069. })
  14070. } else if (more.id === 12) { //投播
  14071. AVCastPicker({
  14072. customPicker: (): void => this.TPImageBuilder(more),
  14073. onStateChange: (state) => {
  14074. if (state == AVCastPickerState.STATE_APPEARING) {
  14075. console.log(' The picker starts showing.');
  14076. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  14077. console.log(' The picker finishes presenting.');
  14078. }
  14079. },
  14080. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  14081. sessionType: 'video'
  14082. })
  14083. .id('AVCastPicker')
  14084. } else {
  14085. if(more.id >= 22){
  14086. SymbolGlyph(more.image)
  14087. .fontSize(24)
  14088. .fontColor([Color.White])
  14089. .alignSelf(ItemAlign.Center)
  14090. .margin({ left: 10, right: 10,bottom:5})
  14091. // .padding({bottom:4})
  14092. .onClick(() => {
  14093. this.doMore(more.id)
  14094. })
  14095. }else{
  14096. Image(more.image)
  14097. .width(24)
  14098. .height(24)
  14099. .fillColor(Color.White)
  14100. .margin({ left: 10, right: 10 })
  14101. .onClick(() => {
  14102. this.doMore(more.id)
  14103. })
  14104. }
  14105. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  14106. .fontSize(16)
  14107. .margin({top:more.id >= 22?3:0})
  14108. .fontColor(Color.White)
  14109. .onClick(() => {
  14110. this.doMore(more.id)
  14111. })
  14112. Select([//倍速
  14113. { value: '0.25x' },
  14114. { value: '0.5x' },
  14115. { value: '0.75x' },
  14116. { value: '1x' },
  14117. { value: '1.25x' },
  14118. { value: '1.5x' },
  14119. { value: '1.75x' },
  14120. { value: '2x' },
  14121. { value: '3x' }])
  14122. .font({ size: 16, weight: FontWeight.Medium })
  14123. .fontColor($r('sys.color.white'))
  14124. .margin({ left: 25 })
  14125. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  14126. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  14127. .value(Utility.optimizedFormat(this.playSpeed))
  14128. .onSelect(async (_index: number, text?: string | undefined) => {
  14129. let speed = parseFloat(text?.replace('x', '') || '1');
  14130. if (!CommonConstants.video_speed_list.includes(speed)) {
  14131. speed = 1;
  14132. }
  14133. this.playSpeed = speed
  14134. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  14135. })
  14136. Slider({
  14137. value: this.volume,
  14138. min: 0,
  14139. max: 1,
  14140. step: 0.1,
  14141. style: SliderStyle.OutSet
  14142. })
  14143. .margin({ left: 18, right: 8 })
  14144. .blockColor(this.themeColor)
  14145. .trackColor($r('app.color.speed_text_color'))
  14146. .selectedColor(Color.White)
  14147. .trackThickness(9)
  14148. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  14149. .onChange((value: number) => {
  14150. this.volume = value;
  14151. this.applyCurrentVolume();
  14152. PreferencesUtil.putSync('DefalutVolume',this.volume)
  14153. })
  14154. .layoutWeight(1)
  14155. Slider({
  14156. value: this.volumeBoostPercent,
  14157. min: 0,
  14158. max: this.volumeBoostMaxPercent,
  14159. step: 1,
  14160. style: SliderStyle.OutSet
  14161. })
  14162. .margin({ left: 18, right: 8 })
  14163. .blockColor(this.themeColor)
  14164. .trackColor($r('app.color.speed_text_color'))
  14165. .selectedColor(Color.White)
  14166. .trackThickness(9)
  14167. .visibility(more.id === 28 ? Visibility.Visible : Visibility.None)
  14168. .onChange((value: number) => {
  14169. this.volumeBoostPercent = Math.round(value);
  14170. this.applyCurrentVolume();
  14171. PreferencesUtil.putSync(this.volumeBoostPreferenceKey, this.volumeBoostPercent);
  14172. })
  14173. .layoutWeight(1)
  14174. Text(`${Math.round(this.volumeBoostPercent)}%`)
  14175. .fontSize(13)
  14176. .fontColor(Color.White)
  14177. .margin({ left: 8, right: 8 })
  14178. .visibility(more.id === 28 ? Visibility.Visible : Visibility.None)
  14179. Text(`${Math.round(this.volume*100)}%`)
  14180. .fontSize(13)
  14181. .fontColor(Color.White)
  14182. .margin({ left: 8, right: 8 })
  14183. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  14184. Blank()
  14185. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  14186. .selectedColor(this.themeColor)
  14187. .switchPointColor(Color.White)
  14188. .margin({ right: 15 })
  14189. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14190. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  14191. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14192. if (more.id == 6) {
  14193. this.isMusicMemoryPlay = checked;
  14194. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  14195. if (this.isMusicMemoryPlay) {
  14196. ToastUtil.showToast('记忆播放已开启')
  14197. } else {
  14198. ToastUtil.showToast('记忆播放已关闭')
  14199. }
  14200. }
  14201. })
  14202. .width(48)
  14203. .height(24);
  14204. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  14205. .selectedColor(this.themeColor)
  14206. .switchPointColor(Color.White)
  14207. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14208. .margin({ right: 15 })
  14209. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  14210. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14211. if (more.id == 7) {
  14212. this.isMusicBGCover = checked;
  14213. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  14214. if (this.isMusicBGCover) {
  14215. ToastUtil.showToast('播放背景随音乐封面已开启')
  14216. } else {
  14217. ToastUtil.showToast('播放背景随音乐封面已关闭')
  14218. }
  14219. }
  14220. })
  14221. .width(48)
  14222. .height(24);
  14223. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  14224. .selectedColor(this.themeColor)
  14225. .switchPointColor(Color.White)
  14226. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14227. .margin({ right: 15 })
  14228. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  14229. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14230. if (more.id == 8) {
  14231. this.isSavePlayMode = checked;
  14232. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  14233. if (this.isSavePlayMode) {
  14234. ToastUtil.showToast('保存播放模式已开启')
  14235. } else {
  14236. ToastUtil.showToast('保存播放模式已关闭')
  14237. }
  14238. }
  14239. })
  14240. .width(48)
  14241. .height(24);
  14242. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  14243. .selectedColor(this.themeColor)
  14244. .switchPointColor(Color.White)
  14245. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14246. .margin({ right: 15 })
  14247. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  14248. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14249. if (more.id == 13) {
  14250. this.isCoverRectangle = checked;
  14251. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  14252. if (this.isCoverRectangle) {
  14253. ToastUtil.showToast('封面方形已开启,双指缩放封面可以调整封面大小')
  14254. this.animationRoFun()
  14255. } else {
  14256. ToastUtil.showToast('封面圆形已开启,双指缩放封面可以调整封面大小')
  14257. this.animationRoFun()
  14258. }
  14259. }
  14260. })
  14261. .width(48)
  14262. .height(24);
  14263. Toggle({ type: ToggleType.Switch, isOn: this.isShowSpectrum })
  14264. .selectedColor(this.themeColor)
  14265. .switchPointColor(Color.White)
  14266. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14267. .margin({ right: 15 })
  14268. .visibility(more.id == 25 ? Visibility.Visible : Visibility.None)
  14269. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14270. if (more.id == 25) {
  14271. this.isShowSpectrum = checked;
  14272. PreferencesUtil.put("isShowSpectrum", this.isShowSpectrum)
  14273. }
  14274. })
  14275. .width(48)
  14276. .height(24);
  14277. // 频谱特效类型选择器
  14278. Select([
  14279. { value: '柱状' },
  14280. { value: '波形' },
  14281. { value: '水波纹' },
  14282. { value: '圆形' },
  14283. { value: '粒子' },
  14284. { value: '脉冲' },
  14285. { value: '镜像柱' },
  14286. { value: '影子柱' },
  14287. { value: '轨道线' },
  14288. { value: '点阵' },
  14289. { value: '星爆' },
  14290. { value: '心电图' },
  14291. { value: '特效' }
  14292. ])
  14293. .font({ size: 14, weight: FontWeight.Medium })
  14294. .fontColor(Color.White)
  14295. .margin({ left: 25 })
  14296. .margin({top:more.id >= 22?3:0})
  14297. .visibility(more.id === 26 ? Visibility.Visible : Visibility.None)
  14298. .selected(this.spectrumModeIndex)
  14299. .value(['柱状', '波形', '水波纹', '圆形', '粒子', '脉冲', '镜像柱', '影子柱', '轨道线', '点阵', '星爆', '心电图', '特效'][this.spectrumModeIndex])
  14300. .onSelect((index: number, _text?: string) => {
  14301. this.spectrumModeIndex = index;
  14302. // 使用同步方法保存,确保立即生效
  14303. PreferencesUtil.putSync('spectrumModeIndex', this.spectrumModeIndex);
  14304. AppStorage.setOrCreate<number>('spectrumMode', this.spectrumModeIndex);
  14305. const modeNames = ['柱状', '波形', '水波纹', '圆形', '粒子', '脉冲', '镜像柱', '影子柱', '轨道线', '点阵', '星爆', '心电图', '特效'];
  14306. Logger.info('heanup-LocalMusic', '频谱特效已切换为: ' + modeNames[index]);
  14307. });
  14308. Toggle({ type: ToggleType.Switch, isOn: this.showSimple })
  14309. .selectedColor(this.themeColor)
  14310. .switchPointColor(Color.White)
  14311. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14312. .margin({ right: 15 })
  14313. .visibility(more.id == 22 ? Visibility.Visible : Visibility.None)
  14314. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14315. if (more.id == 22) {
  14316. this.showSimple = checked;
  14317. PreferencesUtil.put('showSimple', this.showSimple)
  14318. }
  14319. })
  14320. .width(48)
  14321. .height(24);
  14322. Toggle({ type: ToggleType.Switch, isOn: this.enablePointLight })
  14323. .selectedColor(this.themeColor)
  14324. .switchPointColor(Color.White)
  14325. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14326. .margin({ right: 15 })
  14327. .visibility(more.id == 23 ? Visibility.Visible : Visibility.None)
  14328. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14329. if (more.id == 23) {
  14330. this.enablePointLight = checked;
  14331. PreferencesUtil.put('enablePointLight', this.enablePointLight)
  14332. AppStorage.setOrCreate('EnablePointLight', this.enablePointLight);
  14333. }
  14334. })
  14335. .width(48)
  14336. .height(24);
  14337. Toggle({ type: ToggleType.Switch, isOn: this.isGeKongPlayNext })
  14338. .selectedColor(this.themeColor)
  14339. .switchPointColor(Color.White)
  14340. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14341. .margin({ right: 15 })
  14342. .visibility(more.id == 27 ? Visibility.Visible : Visibility.None)
  14343. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  14344. if (more.id == 27) {
  14345. this.isGeKongPlayNext = checked;
  14346. PreferencesUtil.put('isGeKongPlayNext', this.isGeKongPlayNext)
  14347. }
  14348. })
  14349. .width(48)
  14350. .height(24);
  14351. Toggle({ type: ToggleType.Switch, isOn: this.isShowBgLiuGUANG })
  14352. .selectedColor(this.themeColor)
  14353. .switchPointColor(Color.White)
  14354. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  14355. .margin({ right: 15 })
  14356. .visibility(more.id == 21 ? Visibility.Visible : Visibility.None)
  14357. .onChange((checked: boolean) => { // 是否开启背景流光效果
  14358. if (more.id == 21) {
  14359. this.isShowBgLiuGUANG = checked;
  14360. PreferencesUtil.putSync('isShowBgLiuGUANG',this.isShowBgLiuGUANG)
  14361. }
  14362. })
  14363. .width(48)
  14364. .height(24);
  14365. }
  14366. }
  14367. .width('100%')
  14368. .height(45)
  14369. .padding(15)
  14370. .backgroundColor(Color.Transparent)
  14371. .borderRadius(12)
  14372. .margin({ bottom: 6 })
  14373. }
  14374. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  14375. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  14376. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  14377. .backgroundColor(Color.Transparent)
  14378. .onClick(() => {
  14379. this.doMore(more.id)
  14380. })
  14381. });
  14382. }
  14383. .width('100%')
  14384. .padding(16)
  14385. }.margin({ bottom: 18 })
  14386. }
  14387. @Builder
  14388. TPImageBuilder(more: MoreItem): void {
  14389. Row() {
  14390. Image($r('app.media.tuoping'))
  14391. .width(22)
  14392. .height(22)
  14393. .margin({ left: 10, right: 10 })
  14394. Text(more.title)
  14395. .fontSize(16)
  14396. .fontColor(Color.White)
  14397. }
  14398. .width('100%')
  14399. .layoutWeight(1)
  14400. .alignItems(VerticalAlign.Center)
  14401. .justifyContent(FlexAlign.Start)
  14402. }
  14403. private moreItems: MoreItem[] = [
  14404. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  14405. { id: 30, image: $r('sys.symbol.lyrics_square'), title: '歌词' },
  14406. { id: 24, image: $r('sys.symbol.slider_vertical_3'), title: '均衡器' },
  14407. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  14408. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  14409. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  14410. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  14411. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  14412. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  14413. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  14414. { id:20,image: $r("app.media.a_b"), title: 'AB循环' },
  14415. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  14416. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  14417. { id: 4, image: $r('app.media.share2'), title: '分享' },
  14418. { id: 9, image: $r('app.media.volume_white'), title: '音量减弱' },
  14419. { id: 28, image: $r('sys.symbol.speaker_wave_3'), title: '音量增强' },
  14420. { id: 25, image: $r('sys.symbol.ranking'), title: '音乐频谱' },
  14421. { id: 26, image: $r('sys.symbol.eight_diagram'), title: '频谱类型' },
  14422. { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  14423. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  14424. { id : 22, image: $r('sys.symbol.satellite_map'), title: '沉浸式' },
  14425. { id : 23, image: $r('sys.symbol.lightbulb'), title: '点光源效果' },
  14426. { id : 21, image: $r('app.media.kp_music'), title: '背景双边流光' },
  14427. { id : 27, image: $r('sys.symbol.hand'), title: '隔空手势切歌' },
  14428. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  14429. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  14430. ];
  14431. @State isShowBgLiuGUANG: boolean = false;
  14432. @State isShowMoreView: boolean = false;
  14433. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  14434. @State isShowTimeCloseMore: boolean = false
  14435. @State isShowDetailMore: boolean = false
  14436. @State isMusicBGCover: boolean = true
  14437. @State isSavePlayMode: boolean = true
  14438. @State isLyricSetting: boolean = false
  14439. @State isJumpSetting: boolean = false
  14440. @State isShowEdit: boolean = false
  14441. @State showPipLyric: boolean = false
  14442. @State isShowSpectrum: boolean = false//是否显示频谱
  14443. @State spectrumModeIndex: number = 0 //选中的频谱特效索引
  14444. private getSafeBoostPercent(): number {
  14445. const rawBoostPercent = Math.max(0, Math.min(this.volumeBoostPercent, this.volumeBoostMaxPercent));
  14446. if (rawBoostPercent <= 150) {
  14447. return rawBoostPercent;
  14448. }
  14449. if (rawBoostPercent <= 300) {
  14450. return 150 + (rawBoostPercent - 150) * 0.45;
  14451. }
  14452. return 217.5 + (rawBoostPercent - 300) * 0.15;
  14453. }
  14454. private getVolumeBoostFactor(): number {
  14455. return 1 + this.getSafeBoostPercent() / 100;
  14456. }
  14457. private getCurrentOutputVolume(): number {
  14458. const baseVolume = Math.max(0, Math.min(this.volume, 1));
  14459. const boostedVolume = baseVolume * this.getVolumeBoostFactor();
  14460. const maxOutputVolume = this.getVolumeBoostFactor();
  14461. return Math.max(0, Math.min(boostedVolume, maxOutputVolume));
  14462. }
  14463. private applyCurrentVolume(forceDsfSafeVolume: boolean = false): void {
  14464. if (!this.mIjkMediaPlayer) {
  14465. return;
  14466. }
  14467. if (forceDsfSafeVolume && this.volumeSmall && this.videoUrl.toLowerCase().endsWith('.dsf')) {
  14468. this.mIjkMediaPlayer.setVolume('1', '1');
  14469. return;
  14470. }
  14471. const outputVolume = this.getCurrentOutputVolume();
  14472. this.mIjkMediaPlayer.setVolume(outputVolume.toString(), outputVolume.toString());
  14473. }
  14474. async setRingTone() {
  14475. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  14476. return
  14477. }
  14478. // 确定后的逻辑
  14479. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  14480. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  14481. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  14482. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  14483. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  14484. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  14485. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  14486. , this.videoUrl, this.name).then(res => {
  14487. LogUtil.info('onecold setFlag :' + res);
  14488. });
  14489. }
  14490. doMore(moreId: number) {
  14491. switch (moreId) {
  14492. case 30: //歌词
  14493. this.isLyricSetting = !this.isLyricSetting;
  14494. this.isShowMoreView = false
  14495. break;
  14496. case 3: //详情
  14497. this.isShowDetailMore = !this.isShowDetailMore;
  14498. break;
  14499. case 4: //分享
  14500. if (this.currentSong !== undefined) {
  14501. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  14502. }
  14503. this.isShowMoreView = false
  14504. break;
  14505. case 5: //定时关闭
  14506. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  14507. break;
  14508. case 10: //设为铃声
  14509. this.setRingTone()
  14510. this.isShowMoreView = false
  14511. break;
  14512. case 11: //跳过头尾
  14513. this.isJumpSetting = !this.isJumpSetting;
  14514. break;
  14515. case 13: //倍速
  14516. break;
  14517. case 14: //搜索封面
  14518. if (this.currentSong !== undefined) {
  14519. this.doSearchCover(this.currentSong)
  14520. }
  14521. this.isShowMoreView = false
  14522. break;
  14523. case 15: //编辑标签
  14524. this.initEditFields(this.currentSong)
  14525. this.tempLyricContent = this.lyricContent
  14526. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  14527. this.lyricConStr = this.tempLyricContent
  14528. }
  14529. this.isShowEdit = !this.isShowEdit;
  14530. break;
  14531. case 16: //悬浮歌词
  14532. this.showPipLyric = !this.showPipLyric;
  14533. break;
  14534. case 17: //横屏模式
  14535. if (this.isLandscape) {
  14536. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  14537. } else {
  14538. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  14539. }
  14540. this.isShowMoreView = false
  14541. break;
  14542. case 20://AB循环
  14543. this.isABSheet = !this.isABSheet
  14544. break;
  14545. case 24://均衡器
  14546. this.isEqualizerSheet = !this.isEqualizerSheet
  14547. break;
  14548. }
  14549. }
  14550. //AB循环
  14551. @State isOpenAB:boolean = false
  14552. @State jumpATime:number = 0
  14553. @State jumpBTime:number = 0
  14554. @State isABSheet:boolean = false
  14555. @State isEqualizerSheet: boolean = false
  14556. @State eqApplying: boolean = false
  14557. @State eqAppliedAt: number = 0
  14558. @State eqCurrentPresetName: string = '正常'
  14559. @State eqCurrentEnabled: boolean = false
  14560. @Builder
  14561. ABLoopSheet() {
  14562. ABLoopComptent({
  14563. jumpATime:this.jumpATime,
  14564. jumpBTime:this.jumpBTime,
  14565. onClickAItem: async ()=>{
  14566. if(this.mIjkMediaPlayer){
  14567. this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
  14568. }
  14569. },
  14570. onClickBItem: async ()=>{
  14571. if(this.mIjkMediaPlayer){
  14572. this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
  14573. if(this.jumpBTime<=this.jumpATime){
  14574. ToastUtil.showToast('设置B点时间不能小于A点时间')
  14575. this.jumpBTime = 0
  14576. }
  14577. }
  14578. },
  14579. onCancleButtonClick: async ()=>{
  14580. this.isOpenAB = false
  14581. this.isABSheet = false
  14582. },
  14583. onStartButtonClick: async ()=>{
  14584. if(this.jumpBTime<=this.jumpATime||this.stringForTime(this.jumpATime)==this.stringForTime(this.jumpBTime)){
  14585. ToastUtil.showToast('设置B点时间不能小于或等于A点时间')
  14586. return
  14587. }
  14588. this.isABSheet = false
  14589. this.startABLoop()
  14590. },
  14591. })
  14592. }
  14593. private syncEqualizerUi(): void {
  14594. const equalizerManager = EqualizerManager.getInstance();
  14595. this.eqCurrentEnabled = equalizerManager.enabled;
  14596. this.eqCurrentPresetName = equalizerManager.getPresetDisplayName(equalizerManager.currentPresetId);
  14597. if (this.CONTROL_PlayStatus === PlayStatus.INIT) {
  14598. this.eqAppliedAt = 0;
  14599. }
  14600. }
  14601. private markEqualizerApplied(): void {
  14602. const equalizerManager = EqualizerManager.getInstance();
  14603. this.eqCurrentEnabled = equalizerManager.enabled;
  14604. this.eqCurrentPresetName = equalizerManager.getPresetDisplayName(equalizerManager.currentPresetId);
  14605. this.eqAppliedAt = Date.now();
  14606. this.eqApplying = false;
  14607. }
  14608. private applyEqualizerToCurrentPlayback(): void {
  14609. if (this.eqApplying) {
  14610. return;
  14611. }
  14612. if (this.castControllerWrapper && this.isCastPlaying) {
  14613. ToastUtil.showToast('投播模式暂不支持实时均衡器');
  14614. return;
  14615. }
  14616. if (!this.currentSong || !this.mIjkMediaPlayer) {
  14617. ToastUtil.showToast('暂无可应用的播放');
  14618. return;
  14619. }
  14620. this.eqApplying = true;
  14621. try {
  14622. const equalizerManager = EqualizerManager.getInstance();
  14623. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  14624. this.markEqualizerApplied();
  14625. ToastUtil.showToast('均衡器已实时生效');
  14626. } catch (error) {
  14627. this.eqApplying = false;
  14628. Logger.warn(TAG, `heanup 应用均衡器失败: ${(error as Error).message}`);
  14629. }
  14630. }
  14631. @Builder
  14632. private EqualizerApplyStatusBar(): void {
  14633. Row() {
  14634. Column() {
  14635. Text(`均衡器:${this.eqCurrentEnabled ? '开' : '关'} · ${this.eqCurrentPresetName}`)
  14636. .fontSize(12)
  14637. .fontColor($r('app.color.text_color'))
  14638. Text(this.eqAppliedAt > 0 ? '当前播放:已生效' : '当前播放:未应用')
  14639. .fontSize(10)
  14640. .fontColor(this.eqAppliedAt > 0 ? this.themeColor : Color.Gray)
  14641. }
  14642. .alignItems(HorizontalAlign.Start)
  14643. Blank()
  14644. Button('重新应用')
  14645. .fontSize(12)
  14646. .fontColor(Color.White)
  14647. .backgroundColor('#666666')
  14648. .height(28)
  14649. .padding({ left: 14, right: 14 })
  14650. .borderRadius(14)
  14651. .enabled(!this.eqApplying && this.CONTROL_PlayStatus !== PlayStatus.INIT)
  14652. .onClick(() => {
  14653. this.applyEqualizerToCurrentPlayback();
  14654. })
  14655. }
  14656. .width('100%')
  14657. .padding({ left: 12, right: 12, top: 8, bottom: 8 })
  14658. .backgroundColor($r('app.color.settings_background_main'))
  14659. .borderRadius(12)
  14660. }
  14661. @Builder
  14662. EqualizerSheet() {
  14663. Column() {
  14664. Column() {
  14665. EqualizerViewWithCallback({
  14666. onEqualizerChanged: () => {
  14667. this.syncEqualizerUi();
  14668. if (this.mIjkMediaPlayer) {
  14669. const equalizerManager = EqualizerManager.getInstance();
  14670. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  14671. this.markEqualizerApplied();
  14672. }
  14673. }
  14674. })
  14675. }
  14676. .margin({ top: 8 })
  14677. Column() {
  14678. this.EqualizerApplyStatusBar()
  14679. }
  14680. .margin({ top: 8 })
  14681. }
  14682. .padding({ left: 12, right: 12, bottom: 20 })
  14683. .width('100%')
  14684. }
  14685. //开始AB循环
  14686. startABLoop(){
  14687. if(this.mIjkMediaPlayer){
  14688. this.seekTo(this.jumpATime+'')
  14689. this.isOpenAB = true
  14690. }
  14691. }
  14692. /**
  14693. * 切换横竖屏
  14694. *
  14695. */
  14696. setOrientation(orientation: number) {
  14697. this.windowClass.setPreferredOrientation(orientation).then(() => {
  14698. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  14699. }).catch((err: BusinessError) => {
  14700. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  14701. });
  14702. }
  14703. /**
  14704. * 画中画功能(悬浮歌词功能)
  14705. *
  14706. */
  14707. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  14708. pipController?: PiPWindow.PiPController;
  14709. navigationId: string = '';
  14710. @State curState: string = '';
  14711. @State curError: ResourceStr = '';
  14712. @State pipBg: string = '#E8E8E8'
  14713. @State buttonAction: string = '';
  14714. //开启画中画功能
  14715. async startPip() {
  14716. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  14717. if (!this.pipController) {
  14718. await this.createPipController();
  14719. }
  14720. if (!this.pipController) {
  14721. Logger.info(`[${TAG}] pipController create error`);
  14722. return;
  14723. }
  14724. await this.pipController.startPiP();
  14725. }
  14726. async stopPip() {
  14727. if (!this.pipController) {
  14728. Logger.info(`[${TAG}] pipController is not exist`);
  14729. return;
  14730. }
  14731. this.isOpenPip = false
  14732. await this.pipController.stopPiP();
  14733. }
  14734. async createPipController() {
  14735. this.pipController = await PiPWindow.create({
  14736. context: getContext(this),
  14737. componentController: this.xcomponentController,
  14738. navigationId: this.navigationId,
  14739. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  14740. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  14741. customUIController: this.nodeController,
  14742. });
  14743. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  14744. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  14745. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  14746. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  14747. this.onStateChange(state, reason);
  14748. });
  14749. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  14750. this.onActionEvent(event, status);
  14751. });
  14752. }
  14753. destroyPipController() {
  14754. if (!this.pipController) {
  14755. return;
  14756. }
  14757. this.pipController.off('stateChange');
  14758. this.pipController.off('controlPanelActionEvent');
  14759. this.pipController = undefined;
  14760. }
  14761. onStateChange(state: PiPWindow.PiPState, reason: string) {
  14762. switch (state) {
  14763. case PiPWindow.PiPState.ABOUT_TO_START:
  14764. this.curState = 'ABOUT_TO_START';
  14765. this.curError = $r('app.string.current_error_hint');
  14766. break;
  14767. case PiPWindow.PiPState.STARTED:
  14768. this.curState = 'STARTED';
  14769. this.curError = $r('app.string.current_error_hint');
  14770. break;
  14771. case PiPWindow.PiPState.ABOUT_TO_STOP:
  14772. this.curState = 'ABOUT_TO_STOP';
  14773. this.curError = $r('app.string.current_error_hint');
  14774. break;
  14775. case PiPWindow.PiPState.STOPPED:
  14776. this.curState = 'STOPPED';
  14777. this.curError = $r('app.string.current_error_hint');
  14778. this.stopPip()
  14779. this.destroyPipController()
  14780. break;
  14781. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  14782. this.curState = 'ABOUT_TO_RESTORE';
  14783. this.curError = $r('app.string.current_error_hint');
  14784. break;
  14785. case PiPWindow.PiPState.ERROR:
  14786. this.curState = 'ERROR';
  14787. this.curError = reason;
  14788. break;
  14789. default:
  14790. break;
  14791. }
  14792. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  14793. }
  14794. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  14795. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  14796. switch (event) {
  14797. case 'playbackStateChanged':
  14798. if (status === 0) {
  14799. this.pause();
  14800. } else {
  14801. console.info('onecold startPlayOrResumePlay 9869')
  14802. this.startPlayOrResumePlay();
  14803. }
  14804. break;
  14805. case 'nextVideo':
  14806. // 切换到下一个视频
  14807. this.playNext().catch(() => {
  14808. Logger.error('heanup onActionEvent playNext', `播放下一首失败`);
  14809. });
  14810. break;
  14811. case 'previousVideo':
  14812. // 切换到上一个视频
  14813. this.playPrevious().catch(() => {
  14814. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败`);
  14815. });
  14816. break;
  14817. case 'previousVideo':
  14818. // 切换到上一个视频
  14819. this.playPrevious().catch(() => {
  14820. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败:`);
  14821. });
  14822. break;
  14823. default:
  14824. }
  14825. this.buttonAction = event + `-status:${status}`;
  14826. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  14827. }
  14828. /**
  14829. * 画中画功能(悬浮歌词功能)结束
  14830. *
  14831. */
  14832. async doSearchCover(item: VideoItem,title?:string,artist?:string): Promise<string> {
  14833. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  14834. this.isShowMoreView = false;
  14835. this.showTipsDialog();
  14836. return ''; // Return empty string when no API is configured
  14837. }
  14838. if (!item) {
  14839. return ''; // Return empty string if item is undefined
  14840. }
  14841. const titleS = title||item?.name || '';
  14842. const artistS = artist||item?.artist || ''; // Use empty string if artist is missing
  14843. return this.searchCover(item, titleS, artistS, true); // Await is not needed here as we return the promise directly
  14844. }
  14845. /**
  14846. *api搜索封面
  14847. *item,根据title和artist
  14848. */
  14849. searchCover(item: VideoItem, title: string, artist: string, markAsCustomCover: boolean = false): Promise<string> {
  14850. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  14851. LogUtil.debug("onecold res =" + res);
  14852. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  14853. if (item.filePath == this.currentSong?.filePath) {
  14854. if (this.currentSong) {
  14855. mergeCoverWithPriority(this.currentSong, res, markAsCustomCover ? 1 : 0);
  14856. this.cover = this.currentSong.pixelMapPath || res;
  14857. }
  14858. }
  14859. if (isRemoteCloudType(item.type)) {
  14860. mergeCoverWithPriority(item, res, markAsCustomCover ? 1 : 0);
  14861. this.syncRemoteManagerSong(item);
  14862. try {
  14863. await this.persistRemoteMetadataToDb(item);
  14864. this.emitRemoteMetadataUpdated(item);
  14865. } catch (error) {
  14866. Logger.error(TAG, `searchCover 持久化网盘封面失败: ${(error as Error).message}`);
  14867. }
  14868. } else {
  14869. // Update pixel map path but always return res regardless of success
  14870. if (markAsCustomCover) {
  14871. item.isCustomCover = 1;
  14872. this.table.updateCustomCoverPath(item.filePath, res, (success: boolean, error?: string) => {
  14873. if (success) {
  14874. this.doUpdateData();
  14875. console.log("onecold 更新音乐封面成功,数据库已同步");
  14876. } else {
  14877. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  14878. }
  14879. });
  14880. } else {
  14881. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  14882. if (success) {
  14883. this.doUpdateData();
  14884. console.log("onecold 更新音乐封面成功,数据库已同步");
  14885. } else {
  14886. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  14887. }
  14888. });
  14889. }
  14890. }
  14891. LogUtil.debug("onecold this.cover =" + this.cover);
  14892. }
  14893. return res; // Always return res regardless of updatePixelMapPath result
  14894. });
  14895. }
  14896. @State jumpTopTime: number = 0
  14897. @State jumpEndTime: number = 0
  14898. @State isOpenJump: boolean = false
  14899. @Builder
  14900. JumpTopEndSheet() {
  14901. Scroll() {
  14902. Column() {
  14903. Column() {
  14904. Text('仅对本播放列表有效')
  14905. .fontSize(16)
  14906. .fontColor($r('app.color.text_color'))
  14907. // 跳过头尾
  14908. Column() {
  14909. Row() {
  14910. Text('跳过片头:')
  14911. .fontSize(16)
  14912. .fontColor($r('app.color.text_color'))
  14913. Text(this.jumpTopTime + 's')
  14914. .fontSize(16)
  14915. .fontColor($r('app.color.text_color'))
  14916. }
  14917. .margin({ bottom: 5 })
  14918. Row() {
  14919. Slider({
  14920. value: this.jumpTopTime,
  14921. min: 0,
  14922. max: 120,
  14923. step: 1,
  14924. style: SliderStyle.OutSet
  14925. })
  14926. .blockColor(this.themeColor)
  14927. .trackColor($r('app.color.speed_text_color'))
  14928. .selectedColor(Color.White)
  14929. .trackThickness(8)
  14930. .onChange((value: number) => {
  14931. this.jumpTopTime = value;
  14932. })
  14933. .width('85%')
  14934. }
  14935. .alignItems(VerticalAlign.Top)
  14936. }
  14937. .margin({ top: 10, bottom: 10 })
  14938. // 跳过头尾
  14939. Column() {
  14940. Row() {
  14941. Text('跳过片尾:')
  14942. .fontSize(16)
  14943. .fontColor($r('app.color.text_color'))
  14944. Text(this.jumpEndTime + 's')
  14945. .fontSize(16)
  14946. .fontColor($r('app.color.text_color'))
  14947. }
  14948. .margin({ bottom: 5 })
  14949. Row() {
  14950. Slider({
  14951. value: this.jumpEndTime,
  14952. min: 0,
  14953. max: 120,
  14954. step: 1,
  14955. style: SliderStyle.OutSet
  14956. })
  14957. .blockColor(this.themeColor)
  14958. .trackColor($r('app.color.speed_text_color'))
  14959. .selectedColor(Color.White)
  14960. .trackThickness(8)
  14961. .onChange((value: number) => {
  14962. this.jumpEndTime = value;
  14963. })
  14964. .width('85%')
  14965. }
  14966. .alignItems(VerticalAlign.Top)
  14967. }
  14968. .margin({ top: 10, bottom: 10 })
  14969. Row() {
  14970. Button('保存设置')
  14971. .fontColor(Color.White)
  14972. .layoutWeight(1)
  14973. .height(40)
  14974. .width(80)
  14975. .backgroundColor(this.themeColor)
  14976. .stateEffect(true)
  14977. .margin({ left: 0, bottom: 20 })
  14978. .onClick(async () => {
  14979. if (!Utility.isNoble()) {
  14980. this.isJumpSetting = false
  14981. this.isShowMoreView = false
  14982. this.showVipDialog()
  14983. return
  14984. }
  14985. if (this.currentSong === undefined) {
  14986. return
  14987. }
  14988. if (this.modeType === 0) {
  14989. let parentPath = FileUtil.getParentPath(this.videoUrl)
  14990. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  14991. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  14992. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  14993. } else if (this.modeType === 1) { //媒体库
  14994. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  14995. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  14996. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  14997. } else if (this.modeType === 2) { //艺术家
  14998. if (this.currentSong?.artist) {
  14999. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  15000. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  15001. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  15002. }
  15003. } else if (this.modeType === 3) { //专辑
  15004. if (this.currentSong?.album) {
  15005. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  15006. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  15007. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  15008. }
  15009. }
  15010. ToastUtil.showShort("保存成功")
  15011. this.isJumpSetting = false
  15012. })
  15013. }
  15014. .margin({
  15015. left: 38,
  15016. right: 38,
  15017. top: 10,
  15018. bottom: 10
  15019. })
  15020. .width(120)
  15021. .height(50)
  15022. }
  15023. }
  15024. }
  15025. .width('100%')
  15026. .height('100%')
  15027. }
  15028. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  15029. private onStateVastChange(state: AVCastPickerState) {
  15030. if (state == AVCastPickerState.STATE_APPEARING) {
  15031. console.log('The picker starts showing.');
  15032. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  15033. console.log('The picker finishes presenting.');
  15034. }
  15035. }
  15036. private showSelectLyric() {
  15037. DialogHelper.showActionSheetDialog({
  15038. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  15039. // sheets: ["本地歌词", "搜索歌词"],
  15040. sheets: [
  15041. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  15042. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  15043. ],
  15044. maskColor: Color.Transparent,
  15045. backgroundColor: $r('app.color.bg_card'),
  15046. transition: AnimationHelper.transitionInDown(666),
  15047. onAction: (index) => {
  15048. switch (index) {
  15049. case 0:
  15050. this.callFilePickerSelectFileForLyric()
  15051. break;
  15052. case 1:
  15053. if (StrUtil.isNotEmpty(this.videoUrl)) {
  15054. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  15055. this.initLyric(lyricPath);
  15056. }
  15057. break;
  15058. }
  15059. }
  15060. })
  15061. }
  15062. // 拉起picker选择文件管理器
  15063. async callFilePickerSelectFileForLyric(): Promise<void> {
  15064. try {
  15065. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  15066. DocumentSelectOptions.maxSelectNumber = 1
  15067. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  15068. let documentPicker = new picker.DocumentViewPicker();
  15069. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  15070. Logger.info(TAG,
  15071. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  15072. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  15073. this.saveVideoDatasLyric(DocumentSelectResult)
  15074. }
  15075. }).catch((err: BusinessError) => {
  15076. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  15077. });
  15078. } catch (err) {
  15079. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  15080. }
  15081. }
  15082. async saveVideoDatasLyric(uris: string[]) {
  15083. if (ArrayUtil.isEmpty(uris)) {
  15084. return
  15085. }
  15086. let newUris: string[] = [];
  15087. for (let i = 0; i < uris.length; i++) {
  15088. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  15089. Logger.info(TAG, 'filePath uri: ' + filePath);
  15090. newUris.push(filePath)
  15091. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  15092. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  15093. fileIo.copyFileSync(file.fd, file2.fd)
  15094. fileIo.closeSync(file);
  15095. fileIo.closeSync(file2);
  15096. this.initLyric(filePath,false,false,true)
  15097. }
  15098. }
  15099. private initDelayPlay(context: object) {
  15100. this.mContext = context;
  15101. }
  15102. startPipLyric() {
  15103. if (this.pipController) {
  15104. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  15105. PiPWindow.PiPControlStatus.PLAY);
  15106. }
  15107. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  15108. if (this.isOpenPip) {
  15109. this.startPip()
  15110. } else {
  15111. this.stopPip()
  15112. }
  15113. }
  15114. //startOffset 从cue分轨时间开始播
  15115. private startPlayOrResumePlay(startOffset?:number) {
  15116. let finalStartOffset = startOffset
  15117. if ((finalStartOffset === undefined || finalStartOffset === null) && this.currentSong && isCueSplitItem(this.currentSong)) {
  15118. finalStartOffset = 0
  15119. }
  15120. //新版本ijkplayer可以直接播放dsf歌,不需要转格式了。所以注释掉代码
  15121. //针对dsf文件高采样率,统一转wav播放
  15122. // const sampleRate = this.currentSong?.sampleRate||0
  15123. // if(this.videoUrl.toLowerCase().endsWith('.dsf')&&sampleRate>=441000){
  15124. // console.info('onecold 采样率 ='+sampleRate)
  15125. // let newDsfPath = this.context.filesDir + '/'+FileUtil.getFileName(this.videoUrl)+'.wav'
  15126. // console.info('onecold newDsfPath ='+newDsfPath)
  15127. // if(!FileUtil.accessSync(newDsfPath)){
  15128. // const task = new taskpool.Task(convertDsfToWav,this.videoUrl,newDsfPath);
  15129. // taskpool.execute(task, taskpool.Priority.HIGH).then((data)=>{
  15130. // this.videoUrl = newDsfPath
  15131. // this.startPlay(startOffset)
  15132. // }).catch((e:object)=>{
  15133. // console.info("task1 catch e: " + e);
  15134. // })
  15135. // }else{
  15136. // this.videoUrl = newDsfPath
  15137. // this.startPlay(startOffset)
  15138. // }
  15139. //
  15140. // }else{
  15141. // this.startPlay(startOffset)
  15142. // }
  15143. this.startPlay(finalStartOffset)
  15144. // 仅当前播放的是网盘歌曲时,才提前缓存下一首
  15145. // 排除用户拖动进度条的情况
  15146. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !this.isSeekTo) {
  15147. void this.preloadNextSongInternal();
  15148. }
  15149. }
  15150. startPlay(startOffset?:number) {
  15151. this.startPipLyric()
  15152. this.mDestroyPage = false;
  15153. this.animationState = AnimationStatus.Running
  15154. LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  15155. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  15156. this.stopProgressTask();
  15157. this.startProgressTask();
  15158. this.clearInitialSeekGuardTimer();
  15159. this.activePlaybackMemoryKey = this.getPlaybackMemoryKey();
  15160. this.remoteRestoreSeekToken++;
  15161. const shouldMemoryPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)
  15162. || (this.isMemoryLastPlay && this.isFirstStartPlay);
  15163. this.pendingMemorySeekPosition = shouldMemoryPlay ? PreferencesUtil.getNumberSync(this.getPlaybackMemoryKey(), 0) : 0;
  15164. const isRemoteStreamSong = this.currentSong && isRemoteCloudType(this.currentSong.type) &&
  15165. this.videoUrl.includes('://');
  15166. this.waitInitialSeekBeforeStart = !!isRemoteStreamSong && this.pendingMemorySeekPosition > 0;
  15167. // 网盘歌曲起播阶段统一显示加载圈,prepared/首帧后再收起
  15168. this.isPlayerLoading = !!isRemoteStreamSong;
  15169. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  15170. Logger.info(
  15171. TAG,
  15172. `[remote-play] startPlay type=${this.currentSong.type}, memory=${this.pendingMemorySeekPosition}, ` +
  15173. `waitInitial=${this.waitInitialSeekBeforeStart}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  15174. );
  15175. }
  15176. this.play(this.videoUrl.toString(),startOffset);
  15177. }
  15178. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  15179. this.mIjkMediaPlayer.start();
  15180. this.setProgress()
  15181. this.CONTROL_PlayStatus = PlayStatus.PLAY
  15182. }
  15183. this.setIsPlaying(true)
  15184. this.updateSessionPlayState(true)
  15185. this.watchStatus();
  15186. this.updateLastPlayTimeStr(this.videoUrl)
  15187. }
  15188. updateLastPlayTimeStr(filePath: string) {
  15189. // 检查是否为网络音频(WebDAV),如果是则不更新本地数据库
  15190. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  15191. Logger.info(`heanup 检测到网络音频播放,跳过数据库更新: ${filePath}`)
  15192. return;
  15193. }
  15194. const targetFilePath = this.currentSong?.filePath || filePath;
  15195. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  15196. this.table.updateLastPlayedStrByFilePath(targetFilePath, lastPlayTime, (success: boolean, error?: string) => {
  15197. if (success) {
  15198. this.getHistoryList(false)
  15199. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  15200. } else {
  15201. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  15202. }
  15203. });
  15204. }
  15205. private completionNum(num: number): string | number {
  15206. if (num < 10) {
  15207. return '0' + num;
  15208. } else {
  15209. return num;
  15210. }
  15211. }
  15212. private parseDurationToMs(duration?: string): number {
  15213. if (!duration) {
  15214. return 0;
  15215. }
  15216. const parts = duration.split(':').map((item) => Number(item));
  15217. if (parts.some((item) => Number.isNaN(item))) {
  15218. return 0;
  15219. }
  15220. if (parts.length === 2) {
  15221. return Math.floor((parts[0] * 60 + parts[1]) * 1000);
  15222. }
  15223. if (parts.length === 3) {
  15224. return Math.floor((parts[0] * 3600 + parts[1] * 60 + parts[2]) * 1000);
  15225. }
  15226. return 0;
  15227. }
  15228. private sanitizePlaybackUrl(url?: string): string {
  15229. if (!url) {
  15230. return '';
  15231. }
  15232. let sanitized = url.replace(/(access_token=)[^&]+/ig, '$1***');
  15233. sanitized = sanitized.replace(/(refresh_token=)[^&]+/ig, '$1***');
  15234. sanitized = sanitized.replace(/(Authorization=)[^&]+/ig, '$1***');
  15235. if (sanitized.length > 220) {
  15236. return `${sanitized.substring(0, 220)}...`;
  15237. }
  15238. return sanitized;
  15239. }
  15240. private async resolvePlaybackUrlForCurrentSong(source: string): Promise<string | null> {
  15241. const song = this.currentSong;
  15242. if (!song) {
  15243. Logger.warn(TAG, `[play-url] skip source=${source}, currentSong is null`);
  15244. return null;
  15245. }
  15246. const expectedFilePath = song.filePath || '';
  15247. const requestSerial = ++this.playbackUrlRequestSerial;
  15248. Logger.info(
  15249. TAG,
  15250. `[play-url] begin serial=${requestSerial}, source=${source}, song=${song.name}, path=${expectedFilePath}`
  15251. );
  15252. const resolvedUrl = await setVideoUrlForSong(song, {
  15253. context: this.context,
  15254. autoParseMusicName: this.autoParseMusicName
  15255. });
  15256. const currentFilePath = this.currentSong?.filePath || '';
  15257. if (requestSerial !== this.playbackUrlRequestSerial || currentFilePath !== expectedFilePath) {
  15258. Logger.warn(
  15259. TAG,
  15260. `[play-url] stale serial=${requestSerial}, source=${source}, expected=${expectedFilePath}, ` +
  15261. `current=${currentFilePath}, drop=${this.sanitizePlaybackUrl(resolvedUrl)}`
  15262. );
  15263. return null;
  15264. }
  15265. Logger.info(
  15266. TAG,
  15267. `[play-url] apply serial=${requestSerial}, source=${source}, song=${song.name}, ` +
  15268. `url=${this.sanitizePlaybackUrl(resolvedUrl)}`
  15269. );
  15270. return resolvedUrl;
  15271. }
  15272. private beginSeekTrace(source: string, requestMs: number): void {
  15273. this.lastSeekSource = source;
  15274. this.lastSeekRequestMs = requestMs;
  15275. this.seekTraceUntilTs = Date.now() + this.seekTraceLogWindowMs;
  15276. this.lastSeekTraceLogTs = 0;
  15277. }
  15278. private isSeekTraceActive(): boolean {
  15279. return this.seekTraceUntilTs > 0 && Date.now() <= this.seekTraceUntilTs;
  15280. }
  15281. private logSeekTrace(stage: string, position?: number, playerDuration?: number, force: boolean = false): void {
  15282. if (!force && !this.isSeekTraceActive()) {
  15283. return;
  15284. }
  15285. const now = Date.now();
  15286. if (!force && now - this.lastSeekTraceLogTs < this.seekTraceLogIntervalMs) {
  15287. return;
  15288. }
  15289. this.lastSeekTraceLogTs = now;
  15290. const currentPosition = typeof position === 'number' ? position : this.mIjkMediaPlayer.getCurrentPosition();
  15291. const resolvedPlayerDuration = typeof playerDuration === 'number' ? playerDuration : this.mIjkMediaPlayer.getDuration();
  15292. Logger.info(
  15293. TAG,
  15294. `[seek-trace] stage=${stage}, source=${this.lastSeekSource || 'unknown'}, req=${this.lastSeekRequestMs}, ` +
  15295. `current=${currentPosition}, playerDuration=${resolvedPlayerDuration}, uiDuration=${this.duration}, ` +
  15296. `activeDuration=${this.getActiveDuration()}, isPlaying=${this.mIjkMediaPlayer.isPlaying()}, ` +
  15297. `isSeekTo=${this.isSeekTo}, waitInitial=${this.waitInitialSeekBeforeStart}, ` +
  15298. `songType=${this.currentSong?.type ?? -1}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  15299. );
  15300. }
  15301. private stringForTime(timeMs: number): string {
  15302. let totalSeconds: number | string = (timeMs / 1000);
  15303. let newSeconds: number | string = totalSeconds % 60;
  15304. let minutes: number | string = (totalSeconds / 60) % 60;
  15305. let hours: number | string = totalSeconds / 3600;
  15306. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  15307. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  15308. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  15309. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  15310. if (this.isCurrentTime) {
  15311. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  15312. this.oldSeconds = newSeconds
  15313. } else {
  15314. newSeconds = this.oldSeconds
  15315. }
  15316. }
  15317. newSeconds = this.completionNum(newSeconds);
  15318. if (hours > 0) {
  15319. return hours + ":" + minutes + ":" + newSeconds;
  15320. } else {
  15321. return minutes + ":" + newSeconds;
  15322. }
  15323. }
  15324. private getPlayerSwiperDisplayCount(): number {
  15325. return new BreakpointType<number>({
  15326. sm: 1,
  15327. md: 2,
  15328. lg: 2,
  15329. xl: 2,
  15330. xxl: 2
  15331. }).getValue(this.currentBreakpoint) ?? 1
  15332. }
  15333. private shouldUpdateMainLyricPanel(): boolean {
  15334. return this.getPlayerSwiperDisplayCount() > 1 || this.currentSwiperIndex === 1
  15335. }
  15336. private getActivePlaybackPositionMs(): number {
  15337. if (this.castControllerWrapper && this.isCastPlaying) {
  15338. return this.currentTime2 * 1000
  15339. }
  15340. return this.mIjkMediaPlayer.getCurrentPosition()
  15341. }
  15342. private syncLyricPositionNow(): void {
  15343. const position = this.getActivePlaybackPositionMs()
  15344. if (position < 0) {
  15345. return
  15346. }
  15347. this.updateLyricPosition(position + this.timeOffset * 1000)
  15348. }
  15349. private updateLyricPosition(lyricPosition: number): void {
  15350. if (!this.isAppForeground || !this.isPageVisible) {
  15351. return;
  15352. }
  15353. const shouldUpdateMainLyric = this.shouldUpdateMainLyricPanel()
  15354. const shouldUpdatePipLyric = this.showPipLyric
  15355. const shouldUpdateSingleLineLyric = this.isShowSingleLineLyric
  15356. if (!shouldUpdateMainLyric && !shouldUpdatePipLyric && !shouldUpdateSingleLineLyric) {
  15357. return
  15358. }
  15359. if (!Number.isNaN(this.lastLyricRenderPosition) &&
  15360. Math.abs(lyricPosition - this.lastLyricRenderPosition) < this.lyricUpdateMinDeltaMs) {
  15361. return;
  15362. }
  15363. this.lastLyricRenderPosition = lyricPosition;
  15364. if (shouldUpdateMainLyric) {
  15365. this.lyricController.updatePosition(lyricPosition);
  15366. }
  15367. if (shouldUpdatePipLyric) {
  15368. this.lyricControllerXF.updatePosition(lyricPosition);
  15369. }
  15370. if (shouldUpdateSingleLineLyric) {
  15371. this.lyricControllerSingle.updatePosition(lyricPosition);
  15372. }
  15373. }
  15374. private setProgress() {
  15375. if (this.castControllerWrapper && this.isCastPlaying) {
  15376. return;
  15377. }
  15378. const shouldRefreshUi = this.isAppForeground && this.isPageVisible;
  15379. const rawPosition = this.mIjkMediaPlayer.getCurrentPosition();
  15380. const rawDuration = this.mIjkMediaPlayer.getDuration();
  15381. const cueTrackItem = this.currentSong && isCueSplitItem(this.currentSong) ? this.currentSong : undefined;
  15382. const cueTrackStartOffset = cueTrackItem ? getCueTrackStartOffset(cueTrackItem) : 0;
  15383. const cueTrackEndOffset = cueTrackItem ? getCueTrackEndOffset(cueTrackItem) : 0;
  15384. const cueTrackDuration = cueTrackItem ? getCueTrackDuration(cueTrackItem) : 0;
  15385. let position = rawPosition;
  15386. let duration = rawDuration;
  15387. if (cueTrackItem) {
  15388. position = Math.max(0, rawPosition - cueTrackStartOffset);
  15389. if (cueTrackDuration > 0) {
  15390. duration = cueTrackDuration;
  15391. } else if (cueTrackEndOffset > cueTrackStartOffset) {
  15392. duration = cueTrackEndOffset - cueTrackStartOffset;
  15393. } else if (rawDuration > cueTrackStartOffset) {
  15394. duration = rawDuration - cueTrackStartOffset;
  15395. }
  15396. if (duration > 0 && position > duration) {
  15397. position = duration;
  15398. }
  15399. }
  15400. if (duration <= 0 && this.duration > 0) {
  15401. duration = this.duration;
  15402. }
  15403. let pos = 0;
  15404. if (duration > 0) {
  15405. this.slideEnable = true;
  15406. let curPercent = position / duration;
  15407. pos = curPercent * 100;
  15408. if (shouldRefreshUi) {
  15409. if (pos > this.PROGRESS_MAX_VALUE) {
  15410. this.progressValue = this.PROGRESS_MAX_VALUE
  15411. } else {
  15412. this.progressValue = pos;
  15413. }
  15414. }
  15415. }
  15416. this.logSeekTrace('progress-tick', position, duration);
  15417. // LogUtils.getInstance()
  15418. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  15419. if (shouldRefreshUi) {
  15420. this.totalTime = this.stringForTime(duration);
  15421. }
  15422. if (position > duration) {
  15423. position = duration;
  15424. }
  15425. if (shouldRefreshUi) {
  15426. const lyricPosition = (cueTrackItem ? rawPosition : position) + this.timeOffset * 1000;
  15427. this.isCurrentTime = true;
  15428. this.updateLyricPosition(lyricPosition);
  15429. // 蓝牙歌词更新逻辑
  15430. if (this.bluetoothLyricEnabled && this.isBluetoothConnected && this.lyricContent && this.currentSong) {
  15431. const currentLyricLine = LyricUtil.getCurrentLyricLine(this.lyricContent, lyricPosition);
  15432. // 仅在歌词行变化时更新,避免频繁调用
  15433. if (currentLyricLine !== this.lastBluetoothLyricLine) {
  15434. this.lastBluetoothLyricLine = currentLyricLine;
  15435. this.avSessionController.updateBluetoothLyric(
  15436. currentLyricLine,
  15437. this.currentSong.name || '',
  15438. this.currentSong.artist || '',
  15439. this.bluetoothLyricMode
  15440. );
  15441. }
  15442. }
  15443. this.currentTime = this.stringForTime(position);
  15444. this.isCurrentTime = false
  15445. }
  15446. if (this.mIjkMediaPlayer.isPlaying()) {
  15447. const isCueTrackCompleted = cueTrackItem &&
  15448. cueTrackEndOffset > cueTrackStartOffset &&
  15449. rawPosition >= cueTrackEndOffset;
  15450. //如果是开启AB循环
  15451. if(this.isOpenAB){
  15452. if(position >=this.jumpBTime){
  15453. this.seekTo(this.jumpATime+'')
  15454. return
  15455. }
  15456. }
  15457. // 判断是否播放到结束时间
  15458. if ((this.isOpenJump && duration > this.jumpEndTime * 1000 &&
  15459. position >= duration - this.jumpEndTime * 1000) || isCueTrackCompleted) {
  15460. if(this.playType == 1){//跳过尾部如果是单曲循环就选择单曲循环
  15461. this.CONTROL_PlayStatus = PlayStatus.INIT
  15462. this.startPlayOrResumePlay();
  15463. }else if (this.playType == 2) { //2:正常播放,单片播完
  15464. this.showRePlay();
  15465. this.currentTime = this.stringForTime(duration);
  15466. this.progressValue = this.PROGRESS_MAX_VALUE;
  15467. this.slideEnable = false;
  15468. this.stop();
  15469. // ToastUtil.showToast('开始重新播放')
  15470. }else if (this.playType == 4) { //4:连续播放不循环
  15471. // 检查是否是最后一首
  15472. if (this.curIndex >= this.songList.length - 1) {
  15473. // 已经是最后一首,停止播放
  15474. Logger.info('heanup setProgress', '连续播放不循环模式:已到达最后一首,停止播放');
  15475. ToastUtil.showToast('已经是最后一首了');
  15476. this.showRePlay();
  15477. this.currentTime = this.stringForTime(duration);
  15478. this.progressValue = this.PROGRESS_MAX_VALUE;
  15479. this.slideEnable = false;
  15480. this.stop();
  15481. } else {
  15482. // 不是最后一首,继续播放下一首
  15483. this.playNext().catch(() => {
  15484. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  15485. });
  15486. }
  15487. }else{
  15488. this.playNext().catch(() => {
  15489. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  15490. });
  15491. }
  15492. }
  15493. }
  15494. }
  15495. private startProgressTask() {
  15496. let that = this;
  15497. if (this.updateProgressTimer) {
  15498. clearInterval(this.updateProgressTimer);
  15499. this.updateProgressTimer = 0;
  15500. }
  15501. this.updateProgressTimer = setInterval(() => {
  15502. //LogUtils.getInstance().LOGI("startProgressTask");
  15503. if (!that.mDestroyPage) {
  15504. that.setProgress();
  15505. }
  15506. }, this.progressUpdateIntervalMs);
  15507. }
  15508. private stopProgressTask() {
  15509. LogUtils.getInstance().LOGI("stopProgressTask");
  15510. clearInterval(this.updateProgressTimer);
  15511. this.updateProgressTimer = 0;
  15512. }
  15513. private showLoadIng() {
  15514. this.isPlayerLoading = true;
  15515. this.loadingVisible = Visibility.Visible;
  15516. this.replayVisible = Visibility.None;
  15517. }
  15518. private hideLoadIng() {
  15519. this.isPlayerLoading = false;
  15520. this.loadingVisible = Visibility.None;
  15521. this.replayVisible = Visibility.None;
  15522. }
  15523. private showRePlay() {
  15524. this.isPlayerLoading = false;
  15525. this.loadingVisible = Visibility.None;
  15526. this.replayVisible = Visibility.Visible;
  15527. }
  15528. private beginRemoteSongSwitchLoading(song?: VideoItem): boolean {
  15529. const shouldShow = !!song && isRemoteCloudType(song.type);
  15530. if (shouldShow) {
  15531. this.showLoadIng();
  15532. }
  15533. return shouldShow;
  15534. }
  15535. private clearInitialSeekGuardTimer(): void {
  15536. if (this.initialSeekGuardTimer) {
  15537. clearTimeout(this.initialSeekGuardTimer);
  15538. this.initialSeekGuardTimer = 0;
  15539. }
  15540. }
  15541. private ensurePlayerStartedAfterInitialSeek(reason: string): void {
  15542. try {
  15543. if (!this.mIjkMediaPlayer.isPlaying()) {
  15544. this.mIjkMediaPlayer.start();
  15545. }
  15546. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  15547. this.setIsPlaying(true);
  15548. this.updateSessionPlayState(true);
  15549. Logger.info(TAG, `记忆播放恢复开播: ${reason}`);
  15550. } catch (error) {
  15551. Logger.error(TAG, `记忆播放恢复开播失败(${reason}): ${(error as Error).message}`);
  15552. }
  15553. }
  15554. private finishInitialSeekWait(reason: string, shouldStart: boolean): void {
  15555. this.clearInitialSeekGuardTimer();
  15556. const wasWaiting = this.waitInitialSeekBeforeStart;
  15557. this.waitInitialSeekBeforeStart = false;
  15558. this.pendingMemorySeekPosition = 0;
  15559. this.isPlayerLoading = false;
  15560. this.hideLoadIng();
  15561. if (wasWaiting) {
  15562. Logger.info(TAG, `结束记忆seek等待: ${reason}`);
  15563. }
  15564. if (shouldStart) {
  15565. this.ensurePlayerStartedAfterInitialSeek(reason);
  15566. }
  15567. }
  15568. private startInitialSeekGuardTimer(scene: string): void {
  15569. this.clearInitialSeekGuardTimer();
  15570. if (!this.waitInitialSeekBeforeStart || this.pendingMemorySeekPosition <= 0) {
  15571. return;
  15572. }
  15573. const token = this.remoteRestoreSeekToken;
  15574. this.initialSeekGuardTimer = setTimeout(() => {
  15575. if (token !== this.remoteRestoreSeekToken || !this.waitInitialSeekBeforeStart) {
  15576. return;
  15577. }
  15578. Logger.warn(TAG, `记忆seek超时兜底开播, scene=${scene}, pos=${this.pendingMemorySeekPosition}`);
  15579. this.finishInitialSeekWait('seek-timeout', true);
  15580. }, this.initialSeekGuardTimeoutMs);
  15581. }
  15582. private async play(url: string,startOffset?:number) {
  15583. this.lyricController.setLyric(null)
  15584. this.lyricControllerSingle.setLyric(null)
  15585. this.lastLyricRenderPosition = Number.NaN;
  15586. this.isShowBgLiuGUANG = PreferencesUtil.getBooleanSync('isShowBgLiuGUANG', false)
  15587. console.info('onecold this.url 1= '+url)
  15588. if(!url.toLowerCase().startsWith('http')){
  15589. let hasPermission = await PermissionUtil.activatePermission(url)
  15590. console.info('onecold this.hasPermission 1= '+hasPermission)
  15591. if(!url.includes(this.packName)){
  15592. const file = fs.openSync(url)
  15593. this.videoUrl = file.path
  15594. url= this.videoUrl
  15595. }
  15596. console.info('onecold this.hasPermission 1= '+hasPermission)
  15597. console.info('onecold this.videoUrl 1= '+this.videoUrl)
  15598. }
  15599. let that = this;
  15600. const isBaiduStreamingPlaybackUrl = this.isBaiduStreamingUrl(url);
  15601. if (this.waitInitialSeekBeforeStart) {
  15602. that.showLoadIng();
  15603. } else {
  15604. that.hideLoadIng();
  15605. }
  15606. const startOnPreparedOption = this.waitInitialSeekBeforeStart ? "0" : "1";
  15607. this.isOpenAB = false
  15608. //设置XComponent回调的context
  15609. if (!!this.mContext) {
  15610. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  15611. }
  15612. // 每次播放前都先 reset,防止快速切换歌曲时崩溃
  15613. // 修复 SIGSEGV 崩溃:确保播放器在设置新数据源前完全停止并释放资源
  15614. try {
  15615. this.mIjkMediaPlayer.reset();
  15616. Logger.info(TAG, 'IjkPlayer reset 成功');
  15617. } catch (error) {
  15618. Logger.error(TAG, `IjkPlayer reset 失败: ${(error as Error).message}`);
  15619. }
  15620. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  15621. //设置debug模式(用于EQ日志采集)
  15622. this.mIjkMediaPlayer.setDebug(true);
  15623. //初始化配置
  15624. this.mIjkMediaPlayer.native_setup();
  15625. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  15626. this.applyCurrentVolume(true);
  15627. // 构建规范的HTTP请求头(统一一次性设置,避免未带认证提前发起连接)
  15628. const headers = new Map<string, string>();
  15629. headers.set("User-Agent", "TTMusic-WebDAV/1.0");
  15630. headers.set("Accept", "*/*");
  15631. if (this.currentSong&&StrUtil.isEmpty(this.currentSong.pixelMapPath)
  15632. &&PreferencesUtil.getStringSync('COVER_API', '') != '') {
  15633. //如果封面为空,则搜索封面
  15634. this.searchCover(this.currentSong, this.currentSong.name, this.currentSong.artist||'')
  15635. }
  15636. // 如果是WebDAV网络音频,使用webdav_account_id获取认证信息(等待完成后再设置一次性头部)
  15637. // SMB类型通过本地HTTP代理播放,不需要认证头,排除SMB和百度类型
  15638. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !isBaiduType(this.currentSong.type) && !isSmbType(this.currentSong.type)) {
  15639. Logger.info(`heanup WebDAV歌曲认证 - 歌曲名: ${this.currentSong.name}, webdav_account_id: ${this.currentSong.webdav_account_id || '未设置'}`);
  15640. if (this.currentSong.webdav_account_id) {
  15641. try {
  15642. const webdavManager = RemoteDriveManager.getInstance();
  15643. const webDavHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  15644. if (webDavHeaders && webDavHeaders.size > 0) {
  15645. webDavHeaders.forEach((value, key) => headers.set(key, value));
  15646. Logger.info(`heanup 成功通过webdav_account_id获取并合并WebDAV认证头`);
  15647. } else {
  15648. Logger.warn(`heanup 通过webdav_account_id获取认证头失败,播放可能无法继续`);
  15649. }
  15650. } catch (error) {
  15651. const err = error as Error;
  15652. Logger.error(`heanup 获取WebDAV认证头时出错: ${err.message}`);
  15653. }
  15654. } else {
  15655. Logger.error(`heanup WebDAV歌曲 "${this.currentSong.name}" 缺少webdav_account_id,无法进行认证`);
  15656. }
  15657. } else if (this.currentSong && isSmbType(this.currentSong.type)) {
  15658. Logger.info(`heanup SMB歌曲通过HTTP代理播放,无需认证头`);
  15659. }
  15660. // 统一设置带认证的请求头
  15661. // 百度类型也需要特殊请求头
  15662. if (this.currentSong && isBaiduType(this.currentSong.type)) {
  15663. try {
  15664. const webdavManager = RemoteDriveManager.getInstance();
  15665. const baiduHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  15666. baiduHeaders.forEach((value, key) => headers.set(key, value));
  15667. const headerSnapshot: Record<string, string> = {};
  15668. headers.forEach((value, key) => headerSnapshot[key] = value);
  15669. Logger.info(TAG, `Baidu播放请求头: ${JSON.stringify(headerSnapshot)}`);
  15670. } catch (error) {
  15671. Logger.error(`heanup 构建百度请求头失败: ${(error as Error).message}`);
  15672. }
  15673. }
  15674. //设置视频源(先准备好认证头,再设置数据源)
  15675. Logger.info(TAG, `IjkPlayer setDataSource url=${url}`);
  15676. this.mIjkMediaPlayer.setDataSource(url);
  15677. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  15678. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !isBaiduType(this.currentSong.type)) {
  15679. console.log(`heanup 为WebDAV播放设置IjkPlayer选项`);
  15680. // 网络超时设置(单位:微秒,文档显示应该是字符串格式)
  15681. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "30000000"); // 30秒
  15682. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "30000000"); // 连接超时30秒
  15683. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "listen_timeout", "30000000"); // 监听超时30秒
  15684. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "30000000"); // DNS缓存超时30秒
  15685. // 缓冲和播放优化设置
  15686. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "1024000"); // 增大缓冲区
  15687. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "50"); // 减少最小帧数
  15688. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", startOnPreparedOption); // 预加载启动
  15689. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0"); // 无缓冲播放
  15690. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "30000"); // 最大缓存30秒
  15691. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1"); // 无限制收流
  15692. // 网络相关设置
  15693. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1"); // 启用HTTP重定向
  15694. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", "TTMusic-WebDAV/1.0"); // 用户代理
  15695. // 重连设置
  15696. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "reconnect", "3"); // 重连3次
  15697. console.log(`heanup WebDAV IjkPlayer选项设置完成`);
  15698. } else if ((this.currentSong && isBaiduType(this.currentSong.type)) || isBaiduStreamingPlaybackUrl) {
  15699. console.log(`heanup 为百度网盘播放设置IjkPlayer选项`);
  15700. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "15000000");
  15701. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "15000000");
  15702. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1");
  15703. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "1");
  15704. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "2097152");
  15705. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "25");
  15706. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", BaiduConstants.USER_AGENT);
  15707. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", "3");
  15708. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http-detect-range-support", "1");
  15709. console.log(`heanup 百度网盘 IjkPlayer 选项设置完成`);
  15710. }
  15711. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  15712. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  15713. // }
  15714. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  15715. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  15716. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  15717. let bufferSize = 50 * 1024 ; // 默认缓冲区大小为1MB
  15718. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  15719. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  15720. //停止预读的最小帧数
  15721. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  15722. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  15723. // 设置其他缓冲相关选项
  15724. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  15725. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  15726. //启动预加载
  15727. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", startOnPreparedOption);
  15728. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  15729. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  15730. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  15731. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  15732. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  15733. // 因此需要播放器丢包,才不会累积延时
  15734. // 这个和第三个参数packet-buffering无关。
  15735. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  15736. // 无限制收流
  15737. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  15738. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  15739. // 屏幕常亮
  15740. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  15741. // 开启hls起播优化 默认是关闭的
  15742. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "fetch_first", "on");
  15743. // 设置超时
  15744. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  15745. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  15746. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  15747. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  15748. // 变速播放
  15749. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  15750. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  15751. let Speed = this.mIjkMediaPlayer.getSpeed()
  15752. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  15753. //是否开启循环播放
  15754. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  15755. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = new ImplOnVideoSizeChangedListener(
  15756. (width: number, height: number, sar_num: number, sar_den: number) => {
  15757. if (height === 0) {
  15758. return;
  15759. }
  15760. const va = width / height;
  15761. const vpa = that.videoParentAspectRatio;
  15762. if (vpa > va) {
  15763. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  15764. } else {
  15765. that.videoWidth = '100%';
  15766. }
  15767. if (width && height) {
  15768. that.videoAspectRatio = width / height;
  15769. }
  15770. LogUtils.getInstance()
  15771. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  15772. if (!that.waitInitialSeekBeforeStart) {
  15773. that.hideLoadIng();
  15774. }
  15775. }
  15776. );
  15777. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  15778. let mOnPreparedListener: OnPreparedListener = new ImplOnPreparedListener(
  15779. async () => {
  15780. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  15781. Logger.info(
  15782. TAG,
  15783. `[seek] prepared enter, waitInitial=${this.waitInitialSeekBeforeStart}, pendingMemory=${this.pendingMemorySeekPosition}, ` +
  15784. `songType=${this.currentSong?.type ?? -1}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  15785. );
  15786. if (!this.waitInitialSeekBeforeStart) {
  15787. // 无记忆seek时,prepared后可直接隐藏加载
  15788. this.isPlayerLoading = false;
  15789. }
  15790. try {
  15791. //保存碰一碰分享的当前的歌曲
  15792. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  15793. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  15794. await this.initLyric(lyricPath);
  15795. const applyDuration = (durationMs: number): void => {
  15796. const cueTrackDuration = this.currentSong && isCueSplitItem(this.currentSong)
  15797. ? getCueTrackDuration(this.currentSong)
  15798. : 0;
  15799. const effectiveDuration = cueTrackDuration > 0 ? cueTrackDuration : durationMs;
  15800. if (effectiveDuration <= 0) {
  15801. return;
  15802. }
  15803. this.duration = effectiveDuration;
  15804. this.durationTime = Math.floor(effectiveDuration / 1000);
  15805. this.durationStringTime = secondToTime(this.durationTime);
  15806. this.totalTime = this.stringForTime(effectiveDuration);
  15807. if (this.currentSong) {
  15808. this.currentSong.duration = this.totalTime;
  15809. try {
  15810. this.avSessionController.setAVMetadataMusic(this.currentSong, effectiveDuration, this.lyricContent);
  15811. } catch (metaError) {
  15812. Logger.warn(TAG, `heanup 首次播放写入AVSession失败: ${(metaError as Error).message}`);
  15813. }
  15814. }
  15815. };
  15816. const fetchBaiduM3u8Duration = async (url: string): Promise<number> => {
  15817. if (!url || !isBaiduType(this.currentSong?.type ?? -1)) {
  15818. return 0;
  15819. }
  15820. const httpRequest = http.createHttp();
  15821. try {
  15822. const response = await httpRequest.request(url, {
  15823. method: http.RequestMethod.GET,
  15824. connectTimeout: 8000,
  15825. readTimeout: 8000,
  15826. expectDataType: http.HttpDataType.STRING,
  15827. header: {
  15828. 'User-Agent': BaiduConstants.STREAMING_USER_AGENT,
  15829. 'Host': 'pan.baidu.com',
  15830. 'Referer': 'https://pan.baidu.com/disk/home',
  15831. 'Accept-Encoding': 'identity'
  15832. }
  15833. });
  15834. if (response.responseCode !== 200 || typeof response.result !== 'string') {
  15835. return 0;
  15836. }
  15837. const text = response.result;
  15838. if (text.indexOf('#EXTM3U') < 0) {
  15839. return 0;
  15840. }
  15841. const lines = text.split('\n');
  15842. let totalSeconds = 0;
  15843. for (let i = 0; i < lines.length; i++) {
  15844. const line = lines[i].trim();
  15845. if (line.startsWith('#EXTINF:')) {
  15846. const colonIndex = line.indexOf(':');
  15847. if (colonIndex < 0) {
  15848. continue;
  15849. }
  15850. const content = line.substring(colonIndex + 1);
  15851. const commaIndex = content.indexOf(',');
  15852. const numberPart = commaIndex >= 0 ? content.substring(0, commaIndex) : content;
  15853. const seconds = Number(numberPart);
  15854. if (!Number.isNaN(seconds) && seconds > 0) {
  15855. totalSeconds += seconds;
  15856. }
  15857. }
  15858. }
  15859. if (totalSeconds > 0) {
  15860. return Math.floor(totalSeconds * 1000);
  15861. }
  15862. return 0;
  15863. } catch (fetchError) {
  15864. Logger.warn(TAG, `heanup 解析百度M3U8时长失败: ${(fetchError as Error).message}`);
  15865. return 0;
  15866. } finally {
  15867. httpRequest.destroy();
  15868. }
  15869. };
  15870. const fetchDurationFallback = async (): Promise<void> => {
  15871. const durationMs = await fetchBaiduM3u8Duration(this.videoUrl);
  15872. if (durationMs > 0) {
  15873. Logger.info(TAG, `heanup 通过M3U8推导出时长: ${durationMs}ms`);
  15874. applyDuration(durationMs);
  15875. return;
  15876. }
  15877. Logger.warn(TAG, 'heanup 首次播放未拿到时长,保持未知');
  15878. };
  15879. const preparedDuration = this.mIjkMediaPlayer.getDuration();
  15880. Logger.info(
  15881. TAG,
  15882. `[seek] prepared duration snapshot, playerDuration=${preparedDuration}, metaDuration=${this.currentSong?.duration ?? ''}, ` +
  15883. `url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  15884. );
  15885. if (preparedDuration > 0) {
  15886. applyDuration(preparedDuration);
  15887. if (this.videoUrl.includes('method=streaming') && isBaiduType(this.currentSong?.type ?? -1)) {
  15888. const durationMs = await fetchBaiduM3u8Duration(this.videoUrl);
  15889. if (durationMs > 0 && Math.abs(durationMs - preparedDuration) > 1000) {
  15890. Logger.info(TAG, `heanup 使用M3U8时长覆盖播放器时长: ${preparedDuration}ms -> ${durationMs}ms`);
  15891. applyDuration(durationMs);
  15892. }
  15893. }
  15894. } else {
  15895. const metaDurationMs = this.parseDurationToMs(this.currentSong?.duration);
  15896. if (metaDurationMs > 0) {
  15897. Logger.info(TAG, `heanup 使用元数据时长: ${metaDurationMs}ms`);
  15898. applyDuration(metaDurationMs);
  15899. } else {
  15900. fetchDurationFallback();
  15901. }
  15902. }
  15903. setTimeout(() => {
  15904. this.avSessionController.initAvSession(false);
  15905. if (this.duration > 0) {
  15906. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  15907. }
  15908. this.setAvSessionListener();
  15909. this.updateSessionPlayState(true)
  15910. this.setCurrentPlayMode()
  15911. const cueTrackStartOffset = this.currentSong && isCueSplitItem(this.currentSong)
  15912. ? getCueTrackStartOffset(this.currentSong)
  15913. : 0;
  15914. if ((startOffset && startOffset > 0) || cueTrackStartOffset > 0) {//cue分轨播放
  15915. const cueSeekValue = cueTrackStartOffset > 0 && (!startOffset || startOffset <= 0) ? 0 : startOffset;
  15916. this.seekTo((cueSeekValue || 0) + "");
  15917. this.saveLastPlayList()
  15918. return
  15919. }
  15920. }, 500)
  15921. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  15922. let timeoutPlay = 0
  15923. if (StrUtil.isNotEmpty(this.videoUrl) &&
  15924. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  15925. timeoutPlay = 400
  15926. }
  15927. // 网盘流地址在prepare后立刻seek容易触发底层不稳定,统一延后记忆恢复
  15928. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.videoUrl.includes('://')) {
  15929. timeoutPlay = Math.max(timeoutPlay,
  15930. this.waitInitialSeekBeforeStart ? this.remoteMemorySeekInitialDelayMs : 700);
  15931. }
  15932. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  15933. if (this.modeType === 0) { //文件夹
  15934. let parentPath = FileUtil.getParentPath(this.videoUrl)
  15935. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  15936. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  15937. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  15938. } else if (this.modeType === 1) { //媒体库
  15939. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  15940. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  15941. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  15942. } else if (this.modeType === 2) { //艺术家
  15943. if (this.currentSong?.artist) {
  15944. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  15945. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  15946. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  15947. }
  15948. } else if (this.modeType === 3) { //专辑
  15949. if (this.currentSong?.album) {
  15950. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  15951. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  15952. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  15953. }
  15954. }
  15955. const playerDuration = this.mIjkMediaPlayer.getDuration()
  15956. if (playerDuration > 0 && (!this.currentSong || !isCueSplitItem(this.currentSong))) {
  15957. this.duration = playerDuration
  15958. }
  15959. const memoryPosition = this.pendingMemorySeekPosition > 0 ?
  15960. this.pendingMemorySeekPosition : PreferencesUtil.getNumberSync(this.getPlaybackMemoryKey(), 0);
  15961. if (this.waitInitialSeekBeforeStart && memoryPosition > 0) {
  15962. let targetSeekPosition = memoryPosition;
  15963. if (this.isOpenJump) {
  15964. targetSeekPosition = Math.max(targetSeekPosition, this.jumpTopTime * 1000);
  15965. }
  15966. this.pendingMemorySeekPosition = targetSeekPosition;
  15967. this.startInitialSeekGuardTimer('prepared-memory-seek');
  15968. Logger.info(TAG, `准备记忆播放seek: ${targetSeekPosition}ms, timeout=${timeoutPlay}ms`);
  15969. setTimeout(() => {
  15970. if (!this.waitInitialSeekBeforeStart) {
  15971. return;
  15972. }
  15973. this.restorePlaybackPosition();
  15974. }, timeoutPlay);
  15975. this.isFirstStartPlay = false
  15976. this.saveLastPlayList()
  15977. return
  15978. }
  15979. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  15980. if (this.mIjkMediaPlayer != null) {
  15981. let jumpTopTimeMs = this.jumpTopTime*1000;
  15982. if (jumpTopTimeMs <= this.duration) {
  15983. // 调用 seekTo 方法,跳到指定时间
  15984. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  15985. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  15986. this.seekTo(jumpTopTimeMs + ""); // 跳到开头或记忆进度中更靠后的位置
  15987. }
  15988. }, timeoutPlay)
  15989. } else {
  15990. // 提示用户无法跳过
  15991. ToastUtil.showToast('跳过时间超过视频时长');
  15992. }
  15993. }
  15994. } else {
  15995. this.jumpTopTime = 0
  15996. this.jumpEndTime = 0
  15997. // console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  15998. // console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  15999. // console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  16000. // PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  16001. //记忆播放(每一首都会记忆播放)
  16002. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  16003. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  16004. if (this.pendingMemorySeekPosition > 0 ||
  16005. PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  16006. this.restorePlaybackPosition() //读取播放记忆功能
  16007. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  16008. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  16009. this.restorePlaybackPosition() //读取播放记忆功能
  16010. }
  16011. this.isFirstStartPlay = false
  16012. }, timeoutPlay)
  16013. } else {
  16014. this.isFirstStartPlay = false
  16015. }
  16016. }
  16017. this.saveLastPlayList()
  16018. } catch (error) {
  16019. let err: BusinessError = error as BusinessError;
  16020. console.error('onecold failed with err: ' + JSON.stringify(err));
  16021. if (this.waitInitialSeekBeforeStart) {
  16022. this.finishInitialSeekWait('prepared-exception', true);
  16023. }
  16024. }
  16025. }
  16026. );
  16027. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  16028. let mOnTimedTextListener: OnTimedTextListener = new ImplOnTimedTextListener(
  16029. (text: string) => {
  16030. }
  16031. );
  16032. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  16033. let mOnCompletionListener: OnCompletionListener = new ImplOnCompletionListener(
  16034. () => {
  16035. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  16036. if (this.playType == 0) { //0:连续循环播放 1:单片重复播放 2:正常播放 4:连续播放不循环
  16037. // 异步调用playNext
  16038. this.playNext().catch(() => {
  16039. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  16040. });
  16041. } else if (this.playType == 1) { //1:单片重复播放
  16042. this.CONTROL_PlayStatus = PlayStatus.INIT
  16043. that.startPlayOrResumePlay();
  16044. } else if (this.playType == 2) { //2:正常播放,单曲播完
  16045. that.showRePlay();
  16046. that.currentTime = that.stringForTime(that.getActiveDuration());
  16047. that.progressValue = this.PROGRESS_MAX_VALUE;
  16048. that.slideEnable = false;
  16049. that.stop();
  16050. // ToastUtil.showToast('开始重新播放')
  16051. } else if (this.playType == 3) { //3:随机播放
  16052. // 异步调用randomPlay
  16053. this.randomPlay().catch(() => {
  16054. Logger.error('heanup OnCompletionListener randomPlay', `随机播放失败`);
  16055. });
  16056. } else if (this.playType == 4) { //4:连续播放不循环
  16057. // 异步调用playNext
  16058. this.playNext().catch(() => {
  16059. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  16060. });
  16061. }
  16062. }
  16063. );
  16064. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  16065. let mOnBufferingUpdateListener: OnBufferingUpdateListener = new ImplOnBufferingUpdateListener(
  16066. (percent: number) => {
  16067. if (this.isDebug) {
  16068. const now = Date.now();
  16069. if (now - this.lastBufferingLogTs > this.bufferingLogIntervalMs) {
  16070. this.lastBufferingLogTs = now;
  16071. Logger.info(TAG, `OnBufferingUpdateListener percent=${percent}`);
  16072. }
  16073. }
  16074. }
  16075. );
  16076. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  16077. let mOnSeekCompleteListener: OnSeekCompleteListener = new ImplOnSeekCompleteListener(
  16078. () => {
  16079. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  16080. that.logSeekTrace('seek-complete', undefined, undefined, true);
  16081. // seek 完成,延迟恢复播放,确保 ijkplayer 内部状态完全稳定
  16082. setTimeout(() => {
  16083. const waitingInitialSeek = that.waitInitialSeekBeforeStart;
  16084. that.isSeekTo = false;
  16085. if (waitingInitialSeek) {
  16086. that.finishInitialSeekWait('seek-complete', true);
  16087. } else {
  16088. that.hideLoadIng();
  16089. }
  16090. }, 200); // 延迟200ms,确保ijkplayer内部状态稳定
  16091. }
  16092. );
  16093. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  16094. let mOnInfoListener: OnInfoListener = new ImplOnInfoListener(
  16095. (what: number, extra: number) => {
  16096. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  16097. if (that.isSeekTraceActive()) {
  16098. Logger.info(
  16099. TAG,
  16100. `[seek] onInfo what=${what}, extra=${extra}, source=${that.lastSeekSource || 'unknown'}, ` +
  16101. `req=${that.lastSeekRequestMs}, url=${that.sanitizePlaybackUrl(that.videoUrl)}`
  16102. );
  16103. that.logSeekTrace(`info-${what}`, undefined, undefined, true);
  16104. }
  16105. if (!that.waitInitialSeekBeforeStart) {
  16106. that.hideLoadIng();
  16107. }
  16108. }
  16109. );
  16110. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  16111. let mOnErrorListener: OnErrorListener = new ImplOnErrorListener(
  16112. (what: number, extra: number) => {
  16113. this.finishInitialSeekWait('player-error', false);
  16114. this.stopProgressTask();
  16115. this.logSeekTrace(`error-${what}-${extra}`, undefined, undefined, true);
  16116. Logger.error(
  16117. TAG,
  16118. `[seek] onError what=${what}, extra=${extra}, url=${this.sanitizePlaybackUrl(this.videoUrl)}, ` +
  16119. `song=${JSON.stringify(this.currentSong)}`
  16120. );
  16121. // 检查是否为WebDAV播放错误
  16122. let isWebDavError = false;
  16123. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.currentSong.filePath) {
  16124. try {
  16125. const globalContext = GlobalContext.getContext();
  16126. const webDavAuthInfo = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
  16127. if (webDavAuthInfo) {
  16128. isWebDavError = true;
  16129. }
  16130. } catch (error) {
  16131. console.error('OnErrorListener-->go: 获取WebDAV认证信息失败');
  16132. }
  16133. }
  16134. if (isWebDavError) {
  16135. console.info(`heanup WebDAV播放错误 - what: ${what}, extra: ${extra}, URL: ${this.videoUrl}`);
  16136. // 播放失败时清空实例变量中的WebDAV认证信息,防止错误账户持续使用
  16137. // this.currentWebDavAuthInfo = null;
  16138. console.info('heanup WebDAV播放失败,保留认证信息用于后续歌曲切换');
  16139. // 根据错误代码提供更具体的错误信息
  16140. let errorMessage = "WebDAV播放失败";
  16141. if (what === -1) { // 网络错误
  16142. errorMessage = "网络连接失败,请检查WebDAV服务器连接";
  16143. } else if (what === -1004) { // HTTP 404
  16144. errorMessage = "文件未找到,请检查WebDAV服务器上的文件";
  16145. } else if (what === -1001) { // 超时
  16146. errorMessage = "连接超时,请检查网络或WebDAV服务器状态";
  16147. } else if (what === -1003) { // 无法解析主机
  16148. errorMessage = "无法连接到WebDAV服务器";
  16149. }
  16150. ToastUtil.showToast(errorMessage);
  16151. } else {
  16152. if (StrUtil.isNotEmpty(this.videoUrl) &&
  16153. !this.videoUrl.startsWith('http') &&
  16154. this.currentSong &&this.currentSong.type==CommonConstants.TYPE_LOCAL&&
  16155. !FileUtil.accessSync(this.videoUrl)) {
  16156. console.info('heanup 播放.文件不存在');
  16157. ToastUtil.showToast(Utility.resourceToString(this.context, $r('app.string.file_not_exist')))
  16158. }
  16159. }
  16160. that.hideLoadIng();
  16161. }
  16162. );
  16163. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  16164. this.mIjkMediaPlayer.setMessageListener();
  16165. // 应用均衡器设置
  16166. try {
  16167. const equalizerManager = EqualizerManager.getInstance();
  16168. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  16169. Logger.info(TAG, 'heanup 均衡器设置已应用');
  16170. this.markEqualizerApplied();
  16171. } catch (eqError) {
  16172. Logger.warn(TAG, `heanup 应用均衡器失败: ${(eqError as Error).message}`);
  16173. this.eqApplying = false;
  16174. }
  16175. this.mIjkMediaPlayer.prepareAsync();
  16176. this.mIjkMediaPlayer.start();
  16177. }
  16178. //保存最后播放的那首歌和已经对应的播放列表
  16179. saveLastPlayList() {
  16180. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  16181. PreferencesUtil.putSync('LastMusicList', this.songList)
  16182. PreferencesUtil.putSync('LastPlayQueueScope', this.playQueueScope)
  16183. PreferencesUtil.putSync('LastPlayModeType', this.modeType)
  16184. PreferencesUtil.putSync('LastPlayTotalCount', this.totalCount)
  16185. }
  16186. // 清空播放记录
  16187. clearVideoHistory() {
  16188. this.table.clearPlayHistory((success: boolean, error?: string) => {
  16189. if (success) {
  16190. this.historyList = [];
  16191. this.updateListData(this.historyList)
  16192. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  16193. ToastUtil.showToast('清空播放记录成功')
  16194. } else {
  16195. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  16196. }
  16197. });
  16198. }
  16199. public async setAvSessionListener() {
  16200. if (!this.avSessionController) {
  16201. return;
  16202. }
  16203. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  16204. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  16205. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  16206. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  16207. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  16208. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  16209. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  16210. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  16211. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  16212. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  16213. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  16214. }
  16215. setLoopMode() {
  16216. let itype = this.playType + 1
  16217. if (itype >= 5) {
  16218. this.playType = 0
  16219. ToastUtil.showToast('连续循环播放')
  16220. } else if (itype === 1) {
  16221. this.playType = 1
  16222. ToastUtil.showToast('单曲循环')
  16223. } else if (itype === 2) {
  16224. this.playType = 2
  16225. ToastUtil.showToast('单曲播完')
  16226. } else if (itype === 3) {
  16227. this.playType = 3
  16228. ToastUtil.showToast('随机播放')
  16229. } else if (itype === 4) {
  16230. this.playType = 4
  16231. ToastUtil.showToast('连续播放不循环')
  16232. } else if (itype === 0) {
  16233. this.playType = 0
  16234. ToastUtil.showToast('连续循环播放')
  16235. }
  16236. PreferencesUtil.putSync('musicPlayType', this.playType)
  16237. this.setCurrentPlayMode()
  16238. }
  16239. private sessionSetLoopModeCallback = (mode: number) => {
  16240. if (this.mIjkMediaPlayer != null) {
  16241. ToastUtil.showToast('当前播放模式:' + mode)
  16242. Logger.info('onecold 当前播放模式= ' + mode)
  16243. let hmPlayMode = mode + 1
  16244. if (hmPlayMode >= 4) {
  16245. hmPlayMode = 0
  16246. }
  16247. if (hmPlayMode === 1) {
  16248. this.playType = 1
  16249. ToastUtil.showToast('单曲循环')
  16250. } else if (hmPlayMode === 0) {
  16251. this.playType = 2
  16252. ToastUtil.showToast('单曲播完')
  16253. } else if (hmPlayMode === 3) {
  16254. this.playType = 3
  16255. ToastUtil.showToast('随机播放')
  16256. } else if (hmPlayMode === 2) {
  16257. this.playType = 0
  16258. ToastUtil.showToast('连续循环播放')
  16259. } else if (hmPlayMode === 4) {
  16260. this.playType = 4
  16261. ToastUtil.showToast('连续播放不循环')
  16262. }
  16263. PreferencesUtil.putSync('musicPlayType', this.playType)
  16264. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  16265. let playBackState: avSession.AVPlaybackState = {
  16266. loopMode: hmPlayMode,
  16267. };
  16268. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  16269. console.info(`set setLoopMode AVPlaybackState successfully`);
  16270. }).catch((err: BusinessError) => {
  16271. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  16272. });
  16273. }
  16274. }
  16275. setCurrentPlayMode() {
  16276. if (!this.avSessionController) {
  16277. return;
  16278. }
  16279. let mLoopMode = 0
  16280. switch (this.playType) {
  16281. case 0:
  16282. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续循环播放
  16283. break;
  16284. case 1:
  16285. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  16286. break;
  16287. case 2:
  16288. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  16289. break;
  16290. case 3:
  16291. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  16292. break;
  16293. case 4:
  16294. mLoopMode = avSession.LoopMode.LOOP_MODE_CUSTOM //连续播放不循环
  16295. break;
  16296. }
  16297. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  16298. let playBState: avSession.AVPlaybackState = {
  16299. loopMode: mLoopMode,
  16300. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  16301. };
  16302. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  16303. console.info(`set setLoopMode AVPlaybackState successfully`);
  16304. }).catch((err: BusinessError) => {
  16305. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  16306. });
  16307. }
  16308. private sessionToggleFavoriteCallback = (assetId: string) => {
  16309. if (this.mIjkMediaPlayer != null && this.currentSong) {
  16310. console.info(`on toggleFavorite `);
  16311. // 应用收到收藏命令,进行收藏处理。
  16312. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  16313. this.doFav(this.currentSong)
  16314. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  16315. let playbackState: avSession.AVPlaybackState = {
  16316. isFavorite: !this.isFac,
  16317. };
  16318. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  16319. console.info(`SetAVPlaybackState successfully`);
  16320. }).catch((err: BusinessError) => {
  16321. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  16322. });
  16323. }
  16324. }
  16325. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  16326. device: avSession.OutputDeviceInfo) => {
  16327. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  16328. // 将 connectState 转换为可读的字符串
  16329. let stateName = 'UNKNOWN';
  16330. switch (connectState) {
  16331. case avSession.ConnectionState.STATE_CONNECTED:
  16332. stateName = 'CONNECTED(1)';
  16333. break;
  16334. case avSession.ConnectionState.STATE_DISCONNECTED:
  16335. stateName = 'DISCONNECTED(2)';
  16336. break;
  16337. case avSession.ConnectionState.STATE_CONNECTING:
  16338. stateName = 'CONNECTING(3)';
  16339. break;
  16340. default:
  16341. stateName = `OTHER(${connectState})`;
  16342. }
  16343. Logger.info('heanup sessionOutputDeviceChange', `设备状态变化: connectState=${stateName}, castCategory=${currentDevice?.castCategory}, isCastPlaying=${this.isCastPlaying}`);
  16344. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  16345. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  16346. await this.startCasting();
  16347. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  16348. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  16349. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  16350. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  16351. if (device) {
  16352. Logger.info('heanup sessionOutputDeviceChange', '设备断开连接');
  16353. Logger.info('heanup sessionOutputDeviceChange', '用户主动断开连接或已停止播放,调用endCasting');
  16354. this.endCasting();
  16355. }
  16356. }
  16357. };
  16358. private async startCasting() {
  16359. try {
  16360. Logger.info('heanup startCasting', '========== 开始投播初始化 ==========');
  16361. // 获取原始的 AVCastController
  16362. let avCastCtrl = await this.avSessionController.getAvSession()?.getAVCastController();
  16363. if (!avCastCtrl) {
  16364. Logger.error('heanup startCasting', '获取 AVCastController 失败');
  16365. return;
  16366. }
  16367. this.castController = avCastCtrl;
  16368. Logger.info('heanup startCasting', '✅ 获取 AVCastController 成功');
  16369. // 创建新的 CastController 封装器
  16370. this.castControllerWrapper = new CastController(avCastCtrl);
  16371. Logger.info('heanup startCasting', '✅ 创建 CastController 成功');
  16372. // 设置回调函数
  16373. let callbacks: CastControllerCallbacks = {
  16374. onPlayNext: () => {
  16375. Logger.info('heanup CastController', '收到 playNext 回调');
  16376. this.playNext();
  16377. },
  16378. onPlayPrevious: () => {
  16379. Logger.info('heanup CastController', '收到 playPrevious 回调');
  16380. this.playPrevious();
  16381. },
  16382. onPositionChanged: (position: number) => {
  16383. this.positionChange(position);
  16384. },
  16385. onDurationChanged: (duration: number) => {
  16386. this.playDurationChange(duration);
  16387. }
  16388. };
  16389. this.castControllerWrapper.setCallbacks(callbacks);
  16390. Logger.info('heanup startCasting', '✅ 设置回调成功');
  16391. // 暂停本地播放
  16392. this.pause();
  16393. Logger.info('heanup startCasting', '✅ 暂停本地播放成功');
  16394. // 初始化投播会话
  16395. Logger.info('heanup startCasting', `准备调用 initAVCast: songList.length=${this.songList.length}, curIndex=${this.curIndex}, videoUrl=${this.videoUrl}`);
  16396. await this.castControllerWrapper.initAVCast(
  16397. this.songList,
  16398. this.curIndex,
  16399. this.mIjkMediaPlayer.getCurrentPosition(),
  16400. this.videoUrl,
  16401. this.getActiveDuration()
  16402. );
  16403. Logger.info('heanup startCasting', '✅ initAVCast 调用完成');
  16404. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  16405. refToIsCasting?.set(true);
  16406. this.castSeek = true;
  16407. // 从 CastController 获取投播状态
  16408. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  16409. if (this.isCastPlaying) {
  16410. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  16411. this.setIsPlaying(true);
  16412. this.updateSessionPlayState(true);
  16413. }
  16414. Logger.info('heanup startCasting', `✅ 投播初始化完成, isCastPlaying=${this.isCastPlaying}`);
  16415. } catch (error) {
  16416. Logger.error('heanup startCasting', `❌ 投播初始化失败: ${error}`);
  16417. }
  16418. }
  16419. async changeCasting() {
  16420. Logger.info('heanup changeCasting', '切换投播');
  16421. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  16422. this.initQueueItem();
  16423. await this.prepare();
  16424. this.setPlaybackStateChangeListener();
  16425. // isCastPlaying 会在 playbackStateChangeListener 中根据实际状态更新
  16426. this.castSeek = true;
  16427. }
  16428. public endCasting() {
  16429. Logger.info('heanup endCasting', 'endCasting被调用');
  16430. this.avSessionController.getAvSession()?.stopCasting();
  16431. this.stopCast();
  16432. // 关闭文件描述符
  16433. if (this.castFile) {
  16434. try {
  16435. fs.closeSync(this.castFile);
  16436. this.castFile = undefined;
  16437. Logger.info('heanup endCasting', '关闭投播文件描述符');
  16438. } catch (error) {
  16439. Logger.warn('heanup endCasting', `关闭文件描述符失败: ${error}`);
  16440. }
  16441. }
  16442. this.isCastPlaying = false;
  16443. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  16444. refToIsCasting?.set(false);
  16445. this.pause();
  16446. this.setIsPlaying(false);
  16447. // if (this.curIndex === this.curSource.index) {
  16448. // this.play
  16449. // this.seek(this.currentTime * 1000);
  16450. // this.setIsPlaying(true);
  16451. // } else {
  16452. // this.pauseVideo();
  16453. // this.setIsPlaying(false);
  16454. // }
  16455. }
  16456. public setIsPlaying(isPlayer: boolean) {
  16457. this.isPlaying = isPlayer;
  16458. // 发送播放状态变化事件给歌单详情页面
  16459. try {
  16460. const eventPlaybackStatus: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYBACK_STATUS }
  16461. const currentFilePath = this.currentSong?.filePath || ''
  16462. const eventData: emitter.EventData = {
  16463. data: {
  16464. isPlaying: this.isPlaying,
  16465. curIndex: this.curIndex,
  16466. currentFilePath: currentFilePath
  16467. }
  16468. };
  16469. emitter.emit(eventPlaybackStatus, eventData)
  16470. Logger.info(`heanup 发送播放状态变化事件: isPlaying=${this.isPlaying}, curIndex=${this.curIndex}, currentFilePath=${currentFilePath}`)
  16471. } catch (error) {
  16472. Logger.error('heanup 发送播放状态变化事件失败: ' + error)
  16473. }
  16474. }
  16475. private setPlaybackStateChangeListener(): void {
  16476. // 注意: HarmonyOS 的投播控制器可能不返回 state 字段
  16477. // 我们需要通过其他方式来判断播放状态
  16478. // 1. 监听位置变化
  16479. this.castController?.on('playbackStateChange', ['position'], (playbackState: avSession.AVPlaybackState) => {
  16480. if (playbackState.position && typeof playbackState.position.elapsedTime !== 'undefined') {
  16481. Logger.info('heanup playbackStateChange[position]', `elapsedTime=${playbackState.position.elapsedTime}`);
  16482. this.positionChange(playbackState.position.elapsedTime);
  16483. }
  16484. });
  16485. // 2. 监听时长变化
  16486. this.castController?.on('playbackStateChange', ['extras'], (playbackState: avSession.AVPlaybackState) => {
  16487. const duration = playbackState?.extras?.duration;
  16488. if (typeof duration === 'number') {
  16489. this.playDurationChange(duration);
  16490. }
  16491. });
  16492. // 3. 监听所有状态变化(用于调试和状态判断)
  16493. this.castController?.on('playbackStateChange', 'all', (playbackState: avSession.AVPlaybackState) => {
  16494. Logger.info('heanup playbackStateChange[all]', `完整状态=${JSON.stringify(playbackState)}`);
  16495. // 检查是否有 state 字段(某些设备可能返回)
  16496. if (playbackState.state !== undefined) {
  16497. Logger.info('heanup playbackStateChange', `state字段存在: ${playbackState.state}`);
  16498. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  16499. this.isCastPlaying = true;
  16500. }
  16501. }
  16502. });
  16503. // 4. 监听播放完成事件
  16504. this.castController?.on('endOfStream', this.playNextCallback);
  16505. this.castController?.on('playNext', this.playNextCallback);
  16506. this.castController?.on('playPrevious', this.playPreviousCallback);
  16507. // 5. 监听错误事件
  16508. this.castController?.on('error', (error: BusinessError) => {
  16509. Logger.error('heanup playbackStateChange', `投播错误: code=${error.code}, message=${error.message}`);
  16510. this.isCastPlaying = false;
  16511. });
  16512. }
  16513. private updateSessionPlayState(isPlay: boolean): void {
  16514. // if(!this.isBgPlayOpen)
  16515. // return
  16516. const elapsedTime = (this.castControllerWrapper && this.isCastPlaying) ? this.currentTime2 * 1000
  16517. : this.mIjkMediaPlayer.getCurrentPosition();
  16518. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  16519. this.setAVSessionPlayState({
  16520. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  16521. position: {
  16522. elapsedTime: elapsedTime,
  16523. updateTime: new Date().getTime()
  16524. }
  16525. });
  16526. }
  16527. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  16528. this.avSessionController.setAvSessionPlayState(playbackState)
  16529. }
  16530. private positionChange(position: number) {
  16531. this.currentTime2 = position / 1000;
  16532. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  16533. if (this.castControllerWrapper && this.isCastPlaying) {
  16534. this.updateCastProgress(position);
  16535. if (this.isSeekTo) {
  16536. this.isSeekTo = false;
  16537. }
  16538. }
  16539. }
  16540. private playDurationChange(duration: number) {
  16541. this.duration = duration;
  16542. this.durationTime = Math.floor(this.duration / 1000);
  16543. this.durationStringTime = secondToTime((this.durationTime));
  16544. if (this.castControllerWrapper && this.isCastPlaying) {
  16545. this.totalTime = this.stringForTime(this.duration);
  16546. }
  16547. }
  16548. // playbackStateChangeListener 方法已被删除,改用 setPlaybackStateChangeListener 中的内联函数
  16549. private reloadCasting = async () => {
  16550. Logger.info('heanup reloadCasting', '重新加载投播');
  16551. // 使用 initQueueItem() 方法来准备投播项目,保持逻辑一致
  16552. this.initQueueItem();
  16553. await this.prepare();
  16554. };
  16555. public playNextCallback = (): void => {
  16556. this.playNext().catch(() => {
  16557. Logger.error('heanup playNextCallback', `播放下一首失败`);
  16558. });
  16559. };
  16560. public playPreviousCallback = (): void => {
  16561. this.playPrevious().catch(() => {
  16562. Logger.error('heanup playNextCallback', `播放上一首失败`);
  16563. });
  16564. };
  16565. async prepare() {
  16566. try {
  16567. Logger.info('heanup prepare', `开始准备投播: ${this.castItem?.description?.title}`);
  16568. await this.castController?.prepare(this.castItem);
  16569. Logger.info('heanup prepare', '投播prepare成功');
  16570. await this.castController?.start(this.castItem);
  16571. Logger.info('heanup prepare', '投播start成功');
  16572. // 投播启动成功,设置为投播状态
  16573. this.isCastPlaying = true;
  16574. Logger.info('heanup prepare', '投播启动成功,设置isCastPlaying=true');
  16575. } catch (error) {
  16576. Logger.error('heanup prepare', `投播准备失败: ${error}`);
  16577. this.isCastPlaying = false;
  16578. }
  16579. }
  16580. public initQueueItem() {
  16581. let item = this.songList[this.curIndex];
  16582. // 判断是否是流媒体地址 - 使用 videoUrl 判断而不是 filePath
  16583. // 因为 filePath 可能是 navidrome:// 等自定义协议,而 videoUrl 才是真实的流地址
  16584. let isStreaming = this.isUrl(this.videoUrl);
  16585. Logger.info('heanup initQueueItem', `准备投播歌曲: ${item.name}, 是否流媒体: ${isStreaming}, videoUrl: ${this.videoUrl}`);
  16586. // 关闭之前的文件描述符
  16587. if (this.castFile) {
  16588. try {
  16589. fs.closeSync(this.castFile);
  16590. Logger.info('heanup initQueueItem', '关闭之前的文件描述符');
  16591. } catch (error) {
  16592. Logger.warn('heanup initQueueItem', `关闭文件描述符失败: ${error}`);
  16593. }
  16594. }
  16595. let description: avSession.AVMediaDescription = {
  16596. assetId: 'AUDIO-' + item.filePath,
  16597. title: item.name,
  16598. artist: item.artist || '',
  16599. // 该字段大写,音频'AUDIO',视频'VIDEO'
  16600. mediaType: 'AUDIO',
  16601. mediaSize: item.videoSize,
  16602. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  16603. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  16604. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  16605. duration: this.duration,
  16606. albumCoverUri: item.pixelMapPath, // 本地路径电视可能无法访问,暂时注释
  16607. appName: this.appName,
  16608. lyricContent: item.lyricContent,
  16609. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  16610. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  16611. };
  16612. console.log('heanup initQueueItem this.lyricContent', item.lyricContent);
  16613. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  16614. if (isStreaming) {
  16615. // 流媒体地址使用 mediaUri
  16616. description.mediaUri = this.videoUrl;
  16617. Logger.info('heanup initQueueItem', `使用流媒体地址投播: ${this.videoUrl}`);
  16618. } else {
  16619. // 本地文件使用 fdSrc
  16620. const localPath = this.videoUrl || item.filePath;
  16621. let uri = fileUri.getUriFromPath(localPath);
  16622. this.castFile = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  16623. let fdSrc: media.AVFileDescriptor = {
  16624. fd: this.castFile.fd
  16625. };
  16626. description.fdSrc = fdSrc;
  16627. Logger.info('heanup initQueueItem', `使用本地文件投播: ${localPath}, fd: ${this.castFile.fd}`);
  16628. }
  16629. this.castItem = {
  16630. itemId: this.curIndex,
  16631. description: description
  16632. };
  16633. Logger.info('heanup initQueueItem', `投播项目创建完成: ${JSON.stringify({
  16634. title: description.title,
  16635. mediaType: description.mediaType,
  16636. hasMediaUri: !!description.mediaUri,
  16637. hasFdSrc: !!description.fdSrc,
  16638. duration: description.duration
  16639. })}`);
  16640. }
  16641. // 判断是否是 URL 或流媒体地址
  16642. private isUrl(str: string): boolean {
  16643. if (!str) {
  16644. return false;
  16645. }
  16646. // 检查常见的流媒体协议
  16647. if (str.startsWith('http://') || str.startsWith('https://') ||
  16648. str.startsWith('rtmp://') || str.startsWith('rtsp://') ||
  16649. str.startsWith('rtp://') || str.startsWith('mms://')) {
  16650. return true;
  16651. }
  16652. // 扩展的URL正则表达式,支持多种协议
  16653. const urlPattern = new RegExp(
  16654. '^((https?|ftp|rtmp|rtsp|mms|ws|rtp|wss):\\/\\/)?' + // 支持多种协议
  16655. '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // 域名
  16656. '((\\d{1,3}\\.){3}\\d{1,3})|' + // 或IPv4地址
  16657. '\\[([a-f\\d]{1,4}:){7}[a-f\\d]{1,4}\\]|' + // 或IPv6地址
  16658. 'localhost)' + // 或localhost
  16659. '(\\:\\d+)?' + // 端口号(可选)
  16660. '(\\/[-a-z\\d%_.~+]*)*' + // 路径
  16661. '(\\?[;&a-z\\d%_.~+=-]*)?' + // 查询字符串(可选)
  16662. '(\\#[-a-z\\d_]*)?$', // 片段标识符(可选)
  16663. 'i' // 不区分大小写
  16664. );
  16665. return urlPattern.test(str);
  16666. }
  16667. async stopCast() {
  16668. try {
  16669. // 使用 CastController 释放资源
  16670. if (this.castControllerWrapper) {
  16671. await this.castControllerWrapper.releaseAVCast();
  16672. Logger.info('heanup stopCast', 'CastController 释放投播控制器成功');
  16673. }
  16674. // 清空引用
  16675. this.castControllerWrapper = undefined;
  16676. this.castController = undefined;
  16677. this.castItem = undefined;
  16678. this.castFile = undefined;
  16679. } catch (error) {
  16680. Logger.error('heanup stopCast', `停止投播失败: ${error}`);
  16681. }
  16682. }
  16683. private sessionPlayCallback = (): void => {
  16684. this.playOrPause()
  16685. };
  16686. private sessionPauseCallback = (): void => {
  16687. this.pause()
  16688. };
  16689. private async playOrPause() {
  16690. if (!this.debounce()) {
  16691. return;
  16692. }
  16693. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  16694. await this.pause();
  16695. } else {
  16696. // 如果是投播模式,使用 CastController 的 play 方法
  16697. if (this.castControllerWrapper && this.isCastPlaying) {
  16698. try {
  16699. Logger.info('heanup playOrPause', '投播模式播放');
  16700. await this.castControllerWrapper.setPlaying();
  16701. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  16702. this.setIsPlaying(true);
  16703. this.updateSessionPlayState(true);
  16704. Logger.info('heanup playOrPause', '投播播放成功');
  16705. this.playChange();
  16706. } catch (error) {
  16707. Logger.error('heanup playOrPause', `投播播放失败: ${error}`);
  16708. }
  16709. } else {
  16710. console.info('onecold startPlayOrResumePlay 11064')
  16711. this.startPlayOrResumePlay();
  16712. this.playChange()
  16713. }
  16714. }
  16715. }
  16716. private sessionPlayNextCallback = (): void => {
  16717. this.playNext().catch(() => {
  16718. Logger.error('heanup sessionPlayPreviousCallback', `播放下 一首失败`);
  16719. });
  16720. };
  16721. private sessionPlayPreviousCallback = (): void => {
  16722. this.playPrevious().catch(() => {
  16723. Logger.error('heanup sessionPlayPreviousCallback', `播放上一首失败`);
  16724. });
  16725. };
  16726. private sessionStopCallback = (): void => {
  16727. this.stop()
  16728. };
  16729. private sessionFastForwardCallback = async (time?: number) => {
  16730. if (!time) {
  16731. return;
  16732. }
  16733. let curPosition: number;
  16734. if (this.castController && this.isCastPlaying) {
  16735. // 投播模式,使用UI显示的时间
  16736. curPosition = this.currentTime2 * 1000;
  16737. } else if (this.mIjkMediaPlayer != null) {
  16738. // 本地播放器模式
  16739. curPosition = this.mIjkMediaPlayer.getCurrentPosition();
  16740. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  16741. curPosition = Math.max(0, curPosition - getCueTrackStartOffset(this.currentSong));
  16742. }
  16743. } else {
  16744. return;
  16745. }
  16746. let seeTime = curPosition + time * 1000;
  16747. // 限制 seekValue 在合法范围内
  16748. if (seeTime < 0) {
  16749. seeTime = 0;
  16750. } else if (seeTime > this.duration) {
  16751. seeTime = this.duration;
  16752. }
  16753. Logger.info('heanup sessionFastForwardCallback', `快进: ${time}秒, 目标位置: ${seeTime}ms`);
  16754. this.setSeekToActionProgress(seeTime);
  16755. await this.seekTo(seeTime + "");
  16756. };
  16757. private getActiveDuration(): number {
  16758. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  16759. const cueDuration = getCueTrackDuration(this.currentSong);
  16760. if (cueDuration > 0) {
  16761. return cueDuration;
  16762. }
  16763. }
  16764. let duration = this.mIjkMediaPlayer.getDuration();
  16765. if (this.castControllerWrapper && this.isCastPlaying) {
  16766. return this.duration > 0 ? this.duration : duration;
  16767. }
  16768. if (duration <= 0 && this.duration > 0) {
  16769. duration = this.duration;
  16770. }
  16771. return duration;
  16772. }
  16773. private isBaiduStreamingUrl(url: string): boolean {
  16774. if (StrUtil.isEmpty(url)) {
  16775. return false;
  16776. }
  16777. const lowerUrl = url.toLowerCase();
  16778. return lowerUrl.includes('pan.baidu.com/rest/2.0/xpan/file') && lowerUrl.includes('method=streaming');
  16779. }
  16780. @Builder
  16781. InlineSpectrumView() {
  16782. SpectrumView({
  16783. isVisible: this.currentSwiperIndex === 0,
  16784. isPlaying: this.CONTROL_PlayStatus === PlayStatus.PLAY
  16785. })
  16786. .width( '83%')
  16787. .height(this.isCoverOpacity() ? 80 : 100)
  16788. .margin({bottom: 3 })
  16789. .clip(true)
  16790. .zIndex(-2)
  16791. .onClick(()=>{
  16792. this.cycleSpectrumMode();
  16793. })
  16794. }
  16795. private cycleSpectrumMode(): void {
  16796. const modeNames: string[] = ['柱状', '波形', '水波纹', '圆形', '粒子', '脉冲', '镜像柱', '影子柱', '轨道线', '点阵', '星爆', '心电图', '特效'];
  16797. if (modeNames.length <= 0) {
  16798. return;
  16799. }
  16800. const nextIndex: number = (this.spectrumModeIndex + 1) % modeNames.length;
  16801. this.spectrumModeIndex = nextIndex;
  16802. PreferencesUtil.putSync('spectrumModeIndex', nextIndex);
  16803. AppStorage.setOrCreate<number>('spectrumMode', nextIndex);
  16804. Logger.info('heanup-LocalMusic', `频谱特效已顺序切换为: ${modeNames[nextIndex]}`);
  16805. }
  16806. private getSongDurationMs(song?: VideoItem): number {
  16807. if (!song || !song.duration) {
  16808. return 0;
  16809. }
  16810. const raw = song.duration.trim();
  16811. if (!raw) {
  16812. return 0;
  16813. }
  16814. const parts = raw.split(':').map((part) => Number(part));
  16815. if (parts.some((part) => Number.isNaN(part))) {
  16816. return 0;
  16817. }
  16818. let seconds = 0;
  16819. if (parts.length === 3) {
  16820. seconds = parts[0] * 3600 + parts[1] * 60 + parts[2];
  16821. } else if (parts.length === 2) {
  16822. seconds = parts[0] * 60 + parts[1];
  16823. } else if (parts.length === 1) {
  16824. seconds = parts[0];
  16825. }
  16826. return seconds > 0 ? seconds * 1000 : 0;
  16827. }
  16828. private updateCastProgress(position: number): void {
  16829. const duration = this.getActiveDuration();
  16830. if (duration <= 0) {
  16831. return;
  16832. }
  16833. this.slideEnable = true;
  16834. let pos = (position / duration) * 100;
  16835. if (pos > this.PROGRESS_MAX_VALUE) {
  16836. this.progressValue = this.PROGRESS_MAX_VALUE;
  16837. } else if (pos < 0) {
  16838. this.progressValue = 0;
  16839. } else {
  16840. this.progressValue = pos;
  16841. }
  16842. this.totalTime = this.stringForTime(duration);
  16843. if (position > duration) {
  16844. position = duration;
  16845. }
  16846. this.isCurrentTime = true;
  16847. this.currentTime = this.stringForTime(position);
  16848. this.isCurrentTime = false;
  16849. const lyricPosition = position + this.timeOffset * 1000;
  16850. this.updateLyricPosition(lyricPosition);
  16851. }
  16852. /**
  16853. * Gesture method onActionUpdate.
  16854. *
  16855. * @param event Gesture event.手势拖动设置快进和后退
  16856. */
  16857. private setSeekToActionProgress(position: number) {
  16858. // 投播模式使用this.duration,本地模式使用播放器获取
  16859. let duration = this.getActiveDuration();
  16860. let pos = 0;
  16861. if (duration > 0) {
  16862. this.slideEnable = true;
  16863. let curPercent = position / duration;
  16864. pos = curPercent * 100;
  16865. if (pos > this.PROGRESS_MAX_VALUE) {
  16866. this.progressValue = this.PROGRESS_MAX_VALUE
  16867. } else {
  16868. this.progressValue = pos;
  16869. }
  16870. }
  16871. // LogUtils.getInstance()
  16872. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  16873. this.totalTime = this.stringForTime(duration);
  16874. if (position > duration) {
  16875. position = duration;
  16876. }
  16877. this.isCurrentTime = true;
  16878. this.currentTime = this.stringForTime(position);
  16879. this.isCurrentTime = false
  16880. }
  16881. private sessionRewindCallback = async (time?: number) => {
  16882. if (!time) {
  16883. return;
  16884. }
  16885. let curPosition: number;
  16886. if (this.castController && this.isCastPlaying) {
  16887. // 投播模式,使用UI显示的时间
  16888. curPosition = this.currentTime2 * 1000;
  16889. } else if (this.mIjkMediaPlayer != null) {
  16890. // 本地播放器模式
  16891. curPosition = this.mIjkMediaPlayer.getCurrentPosition();
  16892. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  16893. curPosition = Math.max(0, curPosition - getCueTrackStartOffset(this.currentSong));
  16894. }
  16895. } else {
  16896. return;
  16897. }
  16898. let seeTime = curPosition - time * 1000;
  16899. // 限制 seekValue 在合法范围内
  16900. if (seeTime < 0) {
  16901. seeTime = 0;
  16902. } else if (seeTime > this.duration) {
  16903. seeTime = this.duration;
  16904. }
  16905. Logger.info('heanup sessionRewindCallback', `快退: ${time}秒, 目标位置: ${seeTime}ms`);
  16906. this.setSeekToActionProgress(seeTime);
  16907. await this.seekTo(seeTime + "");
  16908. };
  16909. private sessionSeekCallback = async (seekTime: number) => {
  16910. Logger.info('heanup sessionSeekCallback', `收到seek请求: ${seekTime}ms, 投播模式: ${this.isCastPlaying}`);
  16911. // 投播模式直接调用seekTo,它会自动处理投播控制器的seek命令
  16912. await this.seekTo(seekTime + "");
  16913. };
  16914. private async getFileSize(filePath: string): Promise<number> {
  16915. try {
  16916. const stat = await fs.stat(filePath);
  16917. return stat.size;
  16918. } catch (err) {
  16919. console.error('Failed to get file size: ' + err.message);
  16920. return 0;
  16921. }
  16922. }
  16923. private async pause() {
  16924. // 如果是投播模式,使用 CastController 的 pause 方法
  16925. if (this.castControllerWrapper && this.isCastPlaying) {
  16926. try {
  16927. Logger.info('heanup pause', '投播模式暂停');
  16928. await this.castControllerWrapper.setPause();
  16929. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  16930. this.setIsPlaying(false);
  16931. this.updateSessionPlayState(false);
  16932. Logger.info('heanup pause', '投播暂停成功');
  16933. } catch (error) {
  16934. Logger.error('heanup pause', `投播暂停失败: ${error}`);
  16935. }
  16936. } else if (this.mIjkMediaPlayer.isPlaying()) {
  16937. // 本地播放器模式
  16938. this.savePlaybackPosition();
  16939. this.mIjkMediaPlayer.pause();
  16940. this.setProgress();
  16941. this.mDestroyPage = true;
  16942. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  16943. this.updateSessionPlayState(false)
  16944. this.playChange()
  16945. if (this.pipController) {
  16946. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  16947. PiPWindow.PiPControlStatus.PAUSE);
  16948. }
  16949. }
  16950. }
  16951. private stop() {
  16952. this.clearInitialSeekGuardTimer();
  16953. this.waitInitialSeekBeforeStart = false;
  16954. this.pendingMemorySeekPosition = 0;
  16955. this.isPlayerLoading = false;
  16956. this.savePlaybackPosition();
  16957. this.CONTROL_PlayStatus = PlayStatus.INIT;
  16958. this.mIjkMediaPlayer.stop();
  16959. this.mIjkMediaPlayer.release();
  16960. this.stopProgressTask();
  16961. this.updateSessionPlayState(false)
  16962. this.playChange()
  16963. this.watchStatus();
  16964. }
  16965. //保持记忆播放功能
  16966. private savePlaybackPosition() {
  16967. if (this.mIjkMediaPlayer != null) {
  16968. let position = this.mIjkMediaPlayer.getCurrentPosition();
  16969. // ToastUtil.showToast('保存记忆播放 = ' + position)
  16970. let duration = this.mIjkMediaPlayer.getDuration();
  16971. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  16972. position = Math.max(0, position - getCueTrackStartOffset(this.currentSong));
  16973. const cueDuration = getCueTrackDuration(this.currentSong);
  16974. if (cueDuration > 0) {
  16975. duration = cueDuration;
  16976. }
  16977. }
  16978. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  16979. // 如果播放位置接近视频末尾,则保存 position 为 0
  16980. const playbackPosition = (duration - position < threshold) ? 0 : position;
  16981. const memoryKey = this.activePlaybackMemoryKey || this.getPlaybackMemoryKey();
  16982. PreferencesUtil.putSync(memoryKey, playbackPosition);
  16983. }
  16984. }
  16985. private buildPlaybackMemoryKey(song?: VideoItem, playbackUrl?: string): string {
  16986. if (song && isRemoteCloudType(song.type)) {
  16987. const accountId = song.webdav_account_id || 'unknown';
  16988. const stablePath = song.remote_rel_path || song.id || song.baiduFsId || song.filePath || playbackUrl || '';
  16989. return `memory_play_remote:${song.type}:${accountId}:${stablePath}`;
  16990. }
  16991. if (song && isCueSplitItem(song)) {
  16992. return `memory_play_local_cue:${song.filePath}`;
  16993. }
  16994. return playbackUrl || '';
  16995. }
  16996. private getPlaybackMemoryKey(): string {
  16997. return this.buildPlaybackMemoryKey(this.currentSong, this.videoUrl);
  16998. }
  16999. private restoreRemotePlaybackPositionSafely(position: number, token: number, retryCount: number = 0): void {
  17000. if (token !== this.remoteRestoreSeekToken) {
  17001. return;
  17002. }
  17003. if (!this.mIjkMediaPlayer || position <= 0) {
  17004. if (this.waitInitialSeekBeforeStart) {
  17005. this.finishInitialSeekWait('invalid-memory-position', true);
  17006. }
  17007. return;
  17008. }
  17009. const duration = this.getActiveDuration();
  17010. const currentPos = this.mIjkMediaPlayer.getCurrentPosition();
  17011. let safePosition = position;
  17012. if (duration > 0) {
  17013. safePosition = Math.max(0, Math.min(position, duration - 500));
  17014. } else {
  17015. safePosition = Math.max(0, position);
  17016. }
  17017. if (safePosition <= 0) {
  17018. if (this.waitInitialSeekBeforeStart) {
  17019. this.finishInitialSeekWait('memory-position-too-small', true);
  17020. }
  17021. return;
  17022. }
  17023. if (retryCount === 0 && duration <= 0 && currentPos <= 0) {
  17024. Logger.info(TAG, `远程记忆seek提前尝试: pos=${safePosition}, duration=${duration}, current=${currentPos}`);
  17025. }
  17026. this.seekTo(safePosition + "", retryCount === 0 ? 'remote-memory-restore' : 'remote-memory-retry');
  17027. if (retryCount >= this.remoteMemorySeekMaxRetryCount) {
  17028. return;
  17029. }
  17030. setTimeout(() => {
  17031. if (token !== this.remoteRestoreSeekToken || !this.waitInitialSeekBeforeStart || !this.mIjkMediaPlayer) {
  17032. return;
  17033. }
  17034. const latestPos = this.mIjkMediaPlayer.getCurrentPosition();
  17035. if (Math.abs(latestPos - safePosition) <= 1500) {
  17036. return;
  17037. }
  17038. this.restoreRemotePlaybackPositionSafely(position, token, retryCount + 1);
  17039. }, this.remoteMemorySeekRetryIntervalMs);
  17040. }
  17041. //获取记忆播放功能
  17042. private restorePlaybackPosition() {
  17043. const position: number = this.pendingMemorySeekPosition > 0 ?
  17044. this.pendingMemorySeekPosition : PreferencesUtil.getNumberSync(this.getPlaybackMemoryKey(), 0);
  17045. if (!this.mIjkMediaPlayer || position <= 0) {
  17046. if (this.waitInitialSeekBeforeStart) {
  17047. this.finishInitialSeekWait('no-memory-position', true);
  17048. }
  17049. return;
  17050. }
  17051. const isRemoteSong = this.currentSong ? isRemoteCloudType(this.currentSong.type) : false;
  17052. if (isRemoteSong && this.videoUrl.includes('://')) {
  17053. const token = this.remoteRestoreSeekToken;
  17054. this.restoreRemotePlaybackPositionSafely(position, token);
  17055. return;
  17056. }
  17057. const duration = this.getActiveDuration();
  17058. let safePosition = position;
  17059. if (duration > 0) {
  17060. safePosition = Math.max(0, Math.min(position, duration - 500));
  17061. } else {
  17062. safePosition = Math.max(0, position);
  17063. }
  17064. if (safePosition <= 0) {
  17065. if (this.waitInitialSeekBeforeStart) {
  17066. this.finishInitialSeekWait('memory-position-too-small', true);
  17067. }
  17068. return;
  17069. }
  17070. this.seekTo(safePosition + "", isRemoteSong ? 'remote-memory-restore' : 'memory-restore');
  17071. }
  17072. private async seekTo(value: string, source: string = 'internal') {
  17073. // if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  17074. // ToastUtil.showToast('wma格式不支持拖动快进。')
  17075. // return
  17076. // }
  17077. // 如果是投播模式,使用 CastController 的 seek 方法
  17078. if (this.castControllerWrapper && this.isCastPlaying) {
  17079. try {
  17080. let seekPos = Number.parseInt(value);
  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. if (duration > 0) {
  17086. seekPos = Math.max(0, Math.min(seekPos, duration - 200));
  17087. }
  17088. if (cueTrackItem) {
  17089. seekPos += cueTrackStartOffset;
  17090. if (cueTrackEndOffset > cueTrackStartOffset) {
  17091. seekPos = Math.min(seekPos, cueTrackEndOffset - 200);
  17092. }
  17093. }
  17094. this.beginSeekTrace(source, seekPos);
  17095. this.isSeekTo = true;
  17096. Logger.info(
  17097. TAG,
  17098. `[seek] cast dispatch, source=${source}, target=${seekPos}, duration=${duration}, ` +
  17099. `uiDuration=${this.duration}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  17100. );
  17101. // 检查是否接近末尾
  17102. if (this.duration > 0 && seekPos >= this.duration - 500) {
  17103. Logger.warn('heanup seekTo', `快进位置接近末尾(${seekPos}ms >= ${this.duration}ms),可能触发播放完成`);
  17104. }
  17105. await this.castControllerWrapper.seek(seekPos);
  17106. Logger.info('heanup seekTo', `投播seek命令发送成功,位置: ${seekPos}ms`);
  17107. } catch (error) {
  17108. Logger.error('heanup seekTo', `投播seek失败: ${error}`);
  17109. }
  17110. } else {
  17111. // 本地播放器模式
  17112. let seekPos = Number.parseInt(value);
  17113. if (Number.isNaN(seekPos)) {
  17114. return;
  17115. }
  17116. const cueTrackItem = this.currentSong && isCueSplitItem(this.currentSong) ? this.currentSong : undefined;
  17117. const cueTrackStartOffset = cueTrackItem ? getCueTrackStartOffset(cueTrackItem) : 0;
  17118. const cueTrackEndOffset = cueTrackItem ? getCueTrackEndOffset(cueTrackItem) : 0;
  17119. const duration = this.getActiveDuration();
  17120. const isRemoteSong = this.currentSong ? isRemoteCloudType(this.currentSong.type) : false;
  17121. if (duration > 0) {
  17122. seekPos = Math.max(0, Math.min(seekPos, duration - 200));
  17123. } else if (seekPos < 0) {
  17124. seekPos = 0;
  17125. }
  17126. if (cueTrackItem) {
  17127. seekPos += cueTrackStartOffset;
  17128. if (cueTrackEndOffset > cueTrackStartOffset) {
  17129. seekPos = Math.min(seekPos, cueTrackEndOffset - 200);
  17130. }
  17131. }
  17132. if (isRemoteSong && duration <= 0 && seekPos > 0) {
  17133. Logger.warn(TAG, `seekTo 跳过未知时长远程seek: ${seekPos}ms`);
  17134. return;
  17135. }
  17136. if (isRemoteSong && duration <= 0) {
  17137. Logger.info(TAG, `seekTo 远程歌曲时长未知,仅允许起点seek: ${seekPos}ms`);
  17138. }
  17139. if (source !== 'internal') {
  17140. this.beginSeekTrace(source, seekPos);
  17141. }
  17142. this.isSeekTo = true
  17143. try {
  17144. if (isRemoteSong || source !== 'internal' || this.isSeekTraceActive()) {
  17145. Logger.info(
  17146. TAG,
  17147. `[seek] player dispatch, source=${source}, target=${seekPos}, activeDuration=${duration}, ` +
  17148. `playerDuration=${this.mIjkMediaPlayer.getDuration()}, current=${this.mIjkMediaPlayer.getCurrentPosition()}, ` +
  17149. `isPlaying=${this.mIjkMediaPlayer.isPlaying()}, url=${this.sanitizePlaybackUrl(this.videoUrl)}`
  17150. );
  17151. }
  17152. this.mIjkMediaPlayer.seekTo(seekPos + "");
  17153. this.logSeekTrace('seek-dispatched', this.mIjkMediaPlayer.getCurrentPosition(), this.mIjkMediaPlayer.getDuration(), true);
  17154. this.setProgress()
  17155. } catch (error) {
  17156. Logger.error(TAG, `本地播放器seek失败: ${error}`);
  17157. this.logSeekTrace('seek-dispatch-error', undefined, undefined, true);
  17158. } finally {
  17159. this.isSeekTo = false
  17160. }
  17161. }
  17162. }
  17163. // 添加到下一首播放
  17164. private addToNextPlay(song: VideoItem) {
  17165. if (!this.debounce()) {
  17166. return;
  17167. }
  17168. if (this.currentSong) {
  17169. if (this.currentSong === song) {
  17170. ToastUtil.showToast('当前已经在播放这首歌了!')
  17171. return
  17172. }
  17173. }
  17174. // 如果未开始播放或队列为空
  17175. if (this.curIndex === -1 || this.songList.length === 0) {
  17176. this.songList = [song];
  17177. this.curIndex = 0;
  17178. this.doPlay(song)
  17179. return;
  17180. }
  17181. // 插入到当前索引+1的位置
  17182. const insertPos = this.curIndex + 1;
  17183. this.songList.splice(insertPos, 0, song);
  17184. this.songList = [...this.songList]; // 触发状态更新
  17185. this.sonDataSource.pushArrayData(this.songList)
  17186. ToastUtil.showToast('已添加至下一首播放')
  17187. }
  17188. //后退10s,可再设置设置默认几秒
  17189. async backForward() {
  17190. // 如果是投播模式,从currentTime2获取当前位置
  17191. let pos: number;
  17192. if (this.castController && this.isCastPlaying) {
  17193. pos = this.currentTime2 * 1000; // 使用秒转毫秒
  17194. Logger.info('heanup backForward', `投播模式当前位置: ${pos}ms`);
  17195. } else if (this.mIjkMediaPlayer) {
  17196. pos = this.mIjkMediaPlayer.getCurrentPosition();
  17197. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17198. pos = Math.max(0, pos - getCueTrackStartOffset(this.currentSong));
  17199. }
  17200. } else {
  17201. return;
  17202. }
  17203. let value = pos - Number(this.fastForwardSeconds) * 1000;
  17204. if (value < 0) {
  17205. value = 0;
  17206. }
  17207. await this.seekTo(value + "");
  17208. }
  17209. //快进10s,可再设置设置默认几秒
  17210. async fastForward() {
  17211. // 如果是投播模式,从currentTime2获取当前位置
  17212. let pos: number;
  17213. if (this.castController && this.isCastPlaying) {
  17214. pos = this.currentTime2 * 1000; // 使用秒转毫秒
  17215. Logger.info('heanup fastForward', `投播模式当前位置: ${pos}ms`);
  17216. } else if (this.mIjkMediaPlayer) {
  17217. pos = this.mIjkMediaPlayer.getCurrentPosition();
  17218. if (this.currentSong && isCueSplitItem(this.currentSong)) {
  17219. pos = Math.max(0, pos - getCueTrackStartOffset(this.currentSong));
  17220. }
  17221. } else {
  17222. return;
  17223. }
  17224. let value = pos + Number(this.fastForwardSeconds) * 1000;
  17225. // 限制不超过总时长
  17226. if (this.duration > 0 && value > this.duration) {
  17227. value = this.duration;
  17228. }
  17229. await this.seekTo(value + "");
  17230. }
  17231. //下一个
  17232. private async playNext() {
  17233. this.lyricController.setLyric(null)
  17234. this.lyricControllerXF.setLyric(null)
  17235. this.lyricControllerSingle.setLyric(null)
  17236. Logger.info('heanup playNext', '========== playNext 开始 ==========');
  17237. Logger.info('heanup playNext', `isCastPlaying=${this.isCastPlaying}, castControllerWrapper存在=${!!this.castControllerWrapper}`);
  17238. if (!this.debounce()) {
  17239. Logger.warn('heanup playNext', 'debounce() 返回 false,退出');
  17240. return;
  17241. }
  17242. Logger.info('heanup playNext', `playType=${this.playType}`);
  17243. if (this.playType == 3) { //3:随机播放
  17244. Logger.info('heanup playNext', '随机播放模式');
  17245. await this.randomPlay()
  17246. return;
  17247. }
  17248. if (ArrayUtil.isNotEmpty(this.songList)) {
  17249. if (this.curIndex >= this.songList.length - 1) {
  17250. // playType=0 或 3: 尝试加载更多或循环
  17251. // playType=4: 不循环,检查是否是最后一首
  17252. if (this.playType == 4) {
  17253. // 连续播放不循环模式:到达最后一首时停止播放
  17254. Logger.info('heanup playNext', '连续播放不循环模式:已到达最后一首,停止播放');
  17255. ToastUtil.showToast('已经是最后一首了');
  17256. this.showRePlay();
  17257. this.currentTime = this.stringForTime(this.getActiveDuration());
  17258. this.progressValue = this.PROGRESS_MAX_VALUE;
  17259. this.slideEnable = false;
  17260. this.stop();
  17261. return;
  17262. }
  17263. await this.tryLoadNextPageForPlayback();
  17264. }
  17265. if (this.curIndex >= this.songList.length - 1) {
  17266. // playType=4 不应该执行到这里,因为上面已经return了
  17267. this.curIndex = 0;
  17268. } else {
  17269. this.curIndex++;
  17270. }
  17271. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  17272. this.currentSong = this.songList[this.curIndex];
  17273. console.info('heanup playNext', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  17274. const nextLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  17275. const nextUrl = await this.resolvePlaybackUrlForCurrentSong('playNext');
  17276. if (!nextUrl) {
  17277. if (nextLoading) {
  17278. this.hideLoadIng();
  17279. }
  17280. return;
  17281. }
  17282. this.videoUrl = nextUrl;
  17283. this.artist = this.songList[this.curIndex].artist
  17284. this.name = this.songList[this.curIndex].name
  17285. //this.cover = this.songList[this.curIndex].pixelMapPath
  17286. console.info('heanup playNext 1 ', `this.isCastPlaying: ${ this.isCastPlaying}`)
  17287. console.info('heanup playNext 2 ', `this.castControllerWrapper: ${this.castControllerWrapper}`)
  17288. // 如果是投播模式,使用 CastController 播放下一首
  17289. if (this.castControllerWrapper) {
  17290. console.info('heanup playNext', '使用 CastController 播放下一首');
  17291. try {
  17292. const nextDuration = this.getSongDurationMs(this.currentSong);
  17293. if (nextDuration > 0) {
  17294. this.duration = nextDuration;
  17295. this.durationTime = Math.floor(nextDuration / 1000);
  17296. this.durationStringTime = secondToTime(this.durationTime);
  17297. this.totalTime = this.stringForTime(nextDuration);
  17298. this.avSessionController.setAVMetadataMusic(this.currentSong, nextDuration, this.lyricContent);
  17299. }
  17300. this.updateCastProgress(0);
  17301. await this.castControllerWrapper.playNext(this.songList, this.curIndex, this.videoUrl, nextDuration);
  17302. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  17303. if (nextLoading) {
  17304. this.hideLoadIng();
  17305. }
  17306. console.info('heanup playNext', 'CastController 播放下一首成功');
  17307. return;
  17308. } catch (error) {
  17309. console.error('heanup playNext', `CastController 播放下一首失败: ${error}`);
  17310. // 如果投播失败,回退到本地播放
  17311. this.isCastPlaying = false;
  17312. }
  17313. }
  17314. // 本地播放器模式,需要先stop
  17315. this.CONTROL_PlayStatus = PlayStatus.INIT;
  17316. this.stop();
  17317. if (nextLoading) {
  17318. this.showLoadIng();
  17319. }
  17320. this.changeImageAnimation()
  17321. }
  17322. }
  17323. changeImageAnimation() {
  17324. if(this.openSkipSongAnimate){
  17325. // 第一步:淡出动画
  17326. this.getUIContext()?.animateTo({
  17327. duration: 500,
  17328. curve: Curve.EaseOut,
  17329. }, () => {
  17330. this.opacityValueImage = 0.1;
  17331. if(this.isCoverRectangle){
  17332. this.scaleValueImage = 0.88
  17333. }
  17334. });
  17335. // 第二步:切换图片后淡入
  17336. setTimeout(() => {
  17337. this.cover = this.songList[this.curIndex].pixelMapPath
  17338. this.getUIContext()?.animateTo({
  17339. duration: 500,
  17340. curve: Curve.EaseIn,
  17341. }, () => {
  17342. this.opacityValueImage = 1;
  17343. this.scaleValueImage = 1 // 图标恢复到原始大小
  17344. this.startPlayOrResumePlay()
  17345. });
  17346. }, 500);
  17347. }else{
  17348. this.cover = this.songList[this.curIndex].pixelMapPath
  17349. this.startPlayOrResumePlay()
  17350. }
  17351. }
  17352. // 内部方法:提前缓存下一首
  17353. private async preloadNextSongInternal(): Promise<void> {
  17354. // 随机模式下传递已播放索引集合
  17355. if (this.playType === 3) {
  17356. this.preloadNextRandomIndex = await preloadNextSongIfNeeded(
  17357. this.songList,
  17358. this.curIndex,
  17359. this.playType,
  17360. this.playedIndices
  17361. );
  17362. } else {
  17363. this.preloadNextRandomIndex = await preloadNextSongIfNeeded(
  17364. this.songList,
  17365. this.curIndex,
  17366. this.playType
  17367. );
  17368. }
  17369. }
  17370. // 存储已播放的歌曲索引
  17371. private playedIndices: Set<number> = new Set();
  17372. // 存储已播放的本地歌曲路径(随机播放去重用)
  17373. private playedLocalFilePaths: Set<string> = new Set();
  17374. // 随机播放模式下的播放历史栈(记录实际播放顺序,用于"上一首"功能)
  17375. private randomPlayHistory: VideoItem[] = [];
  17376. //随机播放
  17377. private async randomPlay() {
  17378. // if (!this.debounce()) {
  17379. // return;
  17380. // }
  17381. // 网盘模式: 渐进式扩展播放库的随机播放
  17382. // 通过检查当前歌曲类型判断是否为网盘音乐(而非modeType,因为不同网盘类型modeType不同)
  17383. const isCloudSong = this.currentSong && isRemoteCloudType(this.currentSong.type);
  17384. if (isCloudSong) {
  17385. // 阈值常量
  17386. const UNPLAYED_THRESHOLD = 10; // 剩余未播放歌曲阈值
  17387. const LOAD_MORE_PAGES = 3; // 每次加载页数
  17388. // 获取网盘播放列表
  17389. const navidromeList = getNavidromeVideoItems();
  17390. const webdavList = getWebdavVideoItems();
  17391. const isNavidrome = navidromeList.length > 0;
  17392. const remoteList = isNavidrome ? navidromeList : webdavList;
  17393. if (remoteList.length > 0) {
  17394. // 将当前歌加入历史栈
  17395. if (this.currentSong) {
  17396. this.randomPlayHistory.unshift(this.currentSong);
  17397. if (this.randomPlayHistory.length > 50) {
  17398. this.randomPlayHistory = this.randomPlayHistory.slice(0, 50);
  17399. }
  17400. // 标记当前歌曲为已播放
  17401. markAsPlayed(this.currentSong.filePath);
  17402. Logger.info(TAG, `randomPlay(网盘模式): 将当前歌加入历史栈, 栈大小: ${this.randomPlayHistory.length}`);
  17403. }
  17404. // 检查未播放歌曲数量(仅Navidrome支持渐进式加载)
  17405. let unplayedCount = isNavidrome ? getUnplayedCount() : remoteList.length;
  17406. const totalCount = remoteList.length;
  17407. const playedCount = isNavidrome ? getPlayedCount() : 0;
  17408. Logger.info(TAG, `randomPlay(网盘模式): 总数${totalCount}, 已播放${playedCount}, 未播放${unplayedCount}`);
  17409. // 如果未播放数量不足阈值,且还有更多数据,触发加载更多页
  17410. if (isNavidrome && unplayedCount < UNPLAYED_THRESHOLD && hasMoreData()) {
  17411. Logger.info(TAG, `randomPlay(网盘模式): 未播放(${unplayedCount})不足阈值(${UNPLAYED_THRESHOLD}),触发加载更多`);
  17412. const loadSuccess = await triggerLoadMoreSongs(LOAD_MORE_PAGES);
  17413. if (loadSuccess) {
  17414. // 重新获取未播放数量
  17415. unplayedCount = getUnplayedCount();
  17416. Logger.info(TAG, `randomPlay(网盘模式): 加载完成,未播放数量更新为${unplayedCount}`);
  17417. }
  17418. }
  17419. // 从未播放歌曲中随机选择
  17420. let candidates: VideoItem[];
  17421. if (isNavidrome) {
  17422. candidates = getUnplayedSongs();
  17423. // 如果全部播放完,重置已播放记录
  17424. if (candidates.length === 0) {
  17425. Logger.info(TAG, 'randomPlay(网盘模式): 全部播放完毕,重置已播放记录');
  17426. clearPlayedHistory();
  17427. // 排除当前歌曲
  17428. const currentFilePath = this.currentSong?.filePath;
  17429. candidates = currentFilePath
  17430. ? getNavidromeVideoItems().filter(v => v.filePath !== currentFilePath)
  17431. : getNavidromeVideoItems();
  17432. }
  17433. } else {
  17434. // WebDAV模式:简单排除当前歌曲
  17435. const currentFilePath = this.currentSong?.filePath;
  17436. candidates = currentFilePath
  17437. ? remoteList.filter(v => v.filePath !== currentFilePath)
  17438. : remoteList;
  17439. }
  17440. if (candidates.length > 0) {
  17441. const randomIndex = Math.floor(Math.random() * candidates.length);
  17442. const randomSong = candidates[randomIndex];
  17443. // 标记为已播放
  17444. if (isNavidrome) {
  17445. markAsPlayed(randomSong.filePath);
  17446. }
  17447. Logger.info(TAG, `randomPlay(网盘模式): 从${candidates.length}首候选中随机选择: ${randomSong.name}`);
  17448. // 将选中的歌曲加入播放列表(如果不存在)
  17449. let nextIndex = this.songList.findIndex(song => song.filePath === randomSong.filePath);
  17450. if (nextIndex < 0) {
  17451. this.songList = [...this.songList, randomSong];
  17452. this.sonDataSource.pushArrayData(this.songList);
  17453. nextIndex = this.songList.length - 1;
  17454. }
  17455. this.curIndex = nextIndex;
  17456. this.playedIndices.add(this.curIndex);
  17457. this.CONTROL_PlayStatus = PlayStatus.INIT;
  17458. this.stop();
  17459. this.currentSong = randomSong;
  17460. const randomRemoteListLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  17461. const randomRemoteListUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-remote-list');
  17462. if (!randomRemoteListUrl) {
  17463. if (randomRemoteListLoading) {
  17464. this.hideLoadIng();
  17465. }
  17466. return;
  17467. }
  17468. this.videoUrl = randomRemoteListUrl;
  17469. this.name = this.currentSong.name;
  17470. this.artist = this.currentSong.artist;
  17471. this.changeImageAnimation();
  17472. return;
  17473. }
  17474. Logger.warn(TAG, 'randomPlay(网盘模式): 无可用候选歌曲,回退到默认随机逻辑');
  17475. }
  17476. }
  17477. if (this.currentSong) {
  17478. // 将当前歌加入到随机播放历史栈(在切换到新歌之前)
  17479. this.randomPlayHistory.unshift(this.currentSong);
  17480. // 限制历史栈大小,避免无限增长
  17481. if (this.randomPlayHistory.length > 50) {
  17482. this.randomPlayHistory = this.randomPlayHistory.slice(0, 50);
  17483. }
  17484. Logger.info(TAG, `randomPlay: 将当前歌加入历史栈, 栈大小: ${this.randomPlayHistory.length}`);
  17485. const isCurrentRemote = isRemoteCloudType(this.currentSong.type);
  17486. const currentFilePath = this.currentSong.filePath;
  17487. if (isCurrentRemote) {
  17488. const remoteOptions: RandomSongQueryOptions = {
  17489. type: this.currentSong.type,
  17490. excludeFilePaths: currentFilePath ? [currentFilePath] : []
  17491. };
  17492. const randomRemoteSong = await this.table.queryRandomSong(remoteOptions);
  17493. if (randomRemoteSong) {
  17494. // 验证并修正webdav_account_id
  17495. if (randomRemoteSong.webdav_account_id) {
  17496. const manager = RemoteDriveManager.getInstance();
  17497. const account = await manager.getWebDavAccountById(randomRemoteSong.webdav_account_id);
  17498. if (!account) {
  17499. Logger.warn(TAG, `随机播放的歌曲账号ID无效: ${randomRemoteSong.webdav_account_id}, 尝试查找同类型账号`);
  17500. // 获取所有账号,查找相同类型的账号
  17501. const allAccounts = manager.getAllWebDavAccounts();
  17502. let foundAccount: WebDavAccount | null = null;
  17503. for (let i = 0; i < allAccounts.length; i++) {
  17504. if (allAccounts[i].webType === randomRemoteSong.type) {
  17505. foundAccount = allAccounts[i];
  17506. break;
  17507. }
  17508. }
  17509. if (foundAccount && foundAccount.id) {
  17510. Logger.info(TAG, `找到同类型账号,更新webdav_account_id: ${randomRemoteSong.webdav_account_id} -> ${foundAccount.id}`);
  17511. randomRemoteSong.webdav_account_id = foundAccount.id.toString();
  17512. // 更新数据库记录
  17513. await this.table.updateWebDavAccountId(randomRemoteSong.filePath, foundAccount.id.toString());
  17514. } else {
  17515. Logger.error(TAG, `无法找到类型为${randomRemoteSong.type}的账号,跳过此歌曲`);
  17516. return;
  17517. }
  17518. }
  17519. }
  17520. let nextIndex = this.songList.findIndex(song => song.filePath === randomRemoteSong.filePath);
  17521. if (nextIndex < 0) {
  17522. this.songList = [...this.songList, randomRemoteSong];
  17523. this.sonDataSource.pushArrayData(this.songList);
  17524. nextIndex = this.songList.length - 1;
  17525. }
  17526. this.curIndex = nextIndex;
  17527. this.playedIndices.add(this.curIndex);
  17528. this.CONTROL_PlayStatus = PlayStatus.INIT;
  17529. this.stop();
  17530. this.currentSong = randomRemoteSong;
  17531. const randomRemoteDbLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  17532. const randomRemoteUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-remote-db');
  17533. if (!randomRemoteUrl) {
  17534. if (randomRemoteDbLoading) {
  17535. this.hideLoadIng();
  17536. }
  17537. return;
  17538. }
  17539. this.videoUrl = randomRemoteUrl;
  17540. this.name = this.currentSong.name;
  17541. this.artist = this.currentSong.artist;
  17542. this.changeImageAnimation();
  17543. return;
  17544. }
  17545. Logger.warn(TAG, '随机播放未获取到网盘歌曲,回退到列表随机');
  17546. } else {
  17547. if (currentFilePath) {
  17548. this.playedLocalFilePaths.add(currentFilePath);
  17549. }
  17550. // 根据modeType构建不同的查询选项
  17551. const localOptions: RandomSongQueryOptions = {
  17552. type: CommonConstants.TYPE_LOCAL,
  17553. excludeFilePaths: Array.from(this.playedLocalFilePaths)
  17554. };
  17555. Logger.info(TAG, `randomPlay: 本地播放模式, modeType=${this.modeType}, currentPlaylistSongFilePaths.length=${this.currentPlaylistSongFilePaths.length}, currentPath=${this.currentPath}`);
  17556. // modeType==0: 文件夹模式,添加parentPath过滤
  17557. if (this.modeType === 0 && this.currentPath) {
  17558. localOptions.parentPath = this.currentPath;
  17559. Logger.info(TAG, `randomPlay: 文件夹模式, parentPath=${this.currentPath}`);
  17560. }
  17561. // modeType==4: 歌单模式,添加playlistSongFilePaths
  17562. else if (this.modeType === 4 && this.currentPlaylistSongFilePaths.length > 0) {
  17563. localOptions.playlistSongFilePaths = this.currentPlaylistSongFilePaths;
  17564. Logger.info(TAG, `randomPlay: 歌单模式,歌曲数量=${this.currentPlaylistSongFilePaths.length}, 前3首=${this.currentPlaylistSongFilePaths.slice(0, 3).join(', ')}`);
  17565. } else if (this.modeType === 4) {
  17566. Logger.warn(TAG, `randomPlay: 歌单模式但没有歌曲路径列表! currentPlaylistSongFilePaths.length=${this.currentPlaylistSongFilePaths.length}`);
  17567. }
  17568. let randomLocalSong = await this.table.queryRandomSong(localOptions);
  17569. if (!randomLocalSong) {
  17570. this.playedLocalFilePaths.clear();
  17571. if (currentFilePath) {
  17572. this.playedLocalFilePaths.add(currentFilePath);
  17573. }
  17574. const fallbackLocalOptions: RandomSongQueryOptions = {
  17575. type: CommonConstants.TYPE_LOCAL,
  17576. excludeFilePaths: currentFilePath ? [currentFilePath] : []
  17577. };
  17578. // fallback时也要保持modeType的过滤条件
  17579. if (this.modeType === 0 && this.currentPath) {
  17580. fallbackLocalOptions.parentPath = this.currentPath;
  17581. } else if (this.modeType === 4 && this.currentPlaylistSongFilePaths.length > 0) {
  17582. fallbackLocalOptions.playlistSongFilePaths = this.currentPlaylistSongFilePaths;
  17583. }
  17584. randomLocalSong = await this.table.queryRandomSong(fallbackLocalOptions);
  17585. }
  17586. if (randomLocalSong !== null) {
  17587. const selectedLocalSong = randomLocalSong;
  17588. let nextIndex = this.songList.findIndex(song => song.filePath === selectedLocalSong.filePath);
  17589. if (nextIndex < 0) {
  17590. this.songList = [...this.songList, selectedLocalSong];
  17591. this.sonDataSource.pushArrayData(this.songList);
  17592. nextIndex = this.songList.length - 1;
  17593. }
  17594. this.curIndex = nextIndex;
  17595. this.playedIndices.add(this.curIndex);
  17596. this.CONTROL_PlayStatus = PlayStatus.INIT;
  17597. this.stop();
  17598. this.currentSong = selectedLocalSong;
  17599. const randomLocalUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-local-db');
  17600. if (!randomLocalUrl) {
  17601. return;
  17602. }
  17603. this.videoUrl = randomLocalUrl;
  17604. this.name = this.currentSong.name;
  17605. this.artist = this.currentSong.artist;
  17606. this.changeImageAnimation();
  17607. return;
  17608. }
  17609. Logger.warn(TAG, '随机播放未获取到本地歌曲,回退到列表随机');
  17610. }
  17611. }
  17612. if (ArrayUtil.isNotEmpty(this.songList)) {
  17613. if (this.curIndex >= 0 && this.curIndex < this.songList.length) {
  17614. this.playedIndices.add(this.curIndex);
  17615. }
  17616. if (this.songList.length > 3) {
  17617. // 优先使用预缓存的随机索引(仅网盘播放时)
  17618. const nextSong = this.songList[this.preloadNextRandomIndex >= 0 ? this.preloadNextRandomIndex : 0];
  17619. const isNextRemote = nextSong && isRemoteCloudType(nextSong.type);
  17620. const isCurrentRemote = this.currentSong && isRemoteCloudType(this.currentSong.type);
  17621. if (this.preloadNextRandomIndex >= 0 && this.preloadNextRandomIndex < this.songList.length && isNextRemote && isCurrentRemote) {
  17622. Logger.info('heanup randomPlay', `使用预缓存的随机索引: ${this.preloadNextRandomIndex} (网盘播放)`);
  17623. this.curIndex = this.preloadNextRandomIndex;
  17624. this.playedIndices.add(this.curIndex);
  17625. this.preloadNextRandomIndex = -1; // 重置预缓存索引
  17626. // 立即预缓存下一首,避免下次点击时没有预缓存
  17627. void this.preloadNextSongInternal();
  17628. } else {
  17629. // 如果没有预缓存索引,则正常随机选择
  17630. // 如果所有歌曲都播放过一次,清空已播放索引集合
  17631. if (this.playedIndices.size === this.songList.length) {
  17632. this.playedIndices.clear();
  17633. }
  17634. // 随机选择一个未播放的歌曲索引
  17635. let newIndex: number;
  17636. // 添加超时机制防止无限循环
  17637. let attempt = 0;
  17638. const maxAttempts = 100; // 根据需求调整
  17639. do {
  17640. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  17641. attempt++;
  17642. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  17643. if (attempt >= maxAttempts) {
  17644. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  17645. newIndex = Math.floor(Math.random() * this.songList.length);
  17646. }
  17647. this.curIndex = newIndex;
  17648. this.playedIndices.add(newIndex);
  17649. }
  17650. } else {
  17651. // 当歌曲数量小于或等于3时,直接播放下一首
  17652. if (this.curIndex == this.songList.length - 1) {
  17653. this.curIndex = 0;
  17654. } else {
  17655. this.curIndex++;
  17656. }
  17657. }
  17658. this.CONTROL_PlayStatus = PlayStatus.INIT;
  17659. this.stop();
  17660. this.currentSong = this.songList[this.curIndex];
  17661. const randomFallbackLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  17662. const randomFallbackUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-fallback');
  17663. if (!randomFallbackUrl) {
  17664. if (randomFallbackLoading) {
  17665. this.hideLoadIng();
  17666. }
  17667. return;
  17668. }
  17669. this.videoUrl = randomFallbackUrl;
  17670. this.name = this.songList[this.curIndex].name;
  17671. this.artist = this.songList[this.curIndex].artist
  17672. // this.cover = this.songList[this.curIndex].pixelMapPath
  17673. this.changeImageAnimation()
  17674. // 预缓存下一首(包括网盘和本地)
  17675. void this.preloadNextSongInternal();
  17676. }
  17677. }
  17678. private async playIndex(index: number) {
  17679. if (!this.debounce()) {
  17680. return;
  17681. }
  17682. if (ArrayUtil.isNotEmpty(this.songList)) {
  17683. this.curIndex = index;
  17684. this.currentSong = this.songList[index];
  17685. const playIndexLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  17686. const playIndexUrl = await this.resolvePlaybackUrlForCurrentSong('playIndex');
  17687. if (!playIndexUrl) {
  17688. if (playIndexLoading) {
  17689. this.hideLoadIng();
  17690. }
  17691. return;
  17692. }
  17693. this.videoUrl = playIndexUrl;
  17694. this.name = this.currentSong.name
  17695. this.artist = this.currentSong.artist
  17696. // 如果是投播模式,需要为投播设备准备当前歌曲
  17697. if (this.castController && this.isCastPlaying) {
  17698. Logger.info('heanup playIndex', '投播模式播放指定歌曲,不调用本地stop()');
  17699. this.initQueueItem();
  17700. await this.prepare();
  17701. if (playIndexLoading) {
  17702. this.hideLoadIng();
  17703. }
  17704. this.cover = this.currentSong.pixelMapPath;
  17705. return;
  17706. }
  17707. // 本地播放器模式,需要先stop
  17708. this.CONTROL_PlayStatus = PlayStatus.INIT;
  17709. this.stop();
  17710. if (playIndexLoading) {
  17711. this.showLoadIng();
  17712. }
  17713. this.changeImageAnimation()
  17714. }
  17715. }
  17716. //上一个
  17717. private async playPrevious() {
  17718. if (!this.debounce()) {
  17719. return;
  17720. }
  17721. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  17722. this.randomModePlayFromHistory()
  17723. return;
  17724. }
  17725. if (this.curIndex == 0) {
  17726. this.curIndex = this.songList.length - 1;
  17727. } else {
  17728. this.curIndex--;
  17729. }
  17730. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  17731. this.currentSong = this.songList[this.curIndex];
  17732. Logger.info('heanup playPrevious', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  17733. // 验证并修正webdav_account_id(针对远程类型歌曲)
  17734. if (isRemoteCloudType(this.currentSong.type) && this.currentSong.webdav_account_id) {
  17735. const manager = RemoteDriveManager.getInstance();
  17736. const account = await manager.getWebDavAccountById(this.currentSong.webdav_account_id);
  17737. if (!account) {
  17738. Logger.warn(TAG, `playPrevious: 歌曲账号ID无效: ${this.currentSong.webdav_account_id}, 尝试查找同类型账号`);
  17739. // 获取所有账号,查找相同类型的账号
  17740. const allAccounts = manager.getAllWebDavAccounts();
  17741. let foundAccount: WebDavAccount | null = null;
  17742. for (let i = 0; i < allAccounts.length; i++) {
  17743. if (allAccounts[i].webType === this.currentSong.type) {
  17744. foundAccount = allAccounts[i];
  17745. break;
  17746. }
  17747. }
  17748. if (foundAccount && foundAccount.id) {
  17749. Logger.info(TAG, `playPrevious: 找到同类型账号,更新webdav_account_id: ${this.currentSong.webdav_account_id} -> ${foundAccount.id}`);
  17750. this.currentSong.webdav_account_id = foundAccount.id.toString();
  17751. // 更新数据库记录
  17752. await this.table.updateWebDavAccountId(this.currentSong.filePath, foundAccount.id.toString());
  17753. } else {
  17754. Logger.error(TAG, `playPrevious: 无法找到类型为${this.currentSong.type}的账号,跳过此歌曲`);
  17755. // 跳过无效账号的歌曲,继续查找上一首
  17756. if (this.curIndex == 0) {
  17757. this.curIndex = this.songList.length - 1;
  17758. } else {
  17759. this.curIndex--;
  17760. }
  17761. this.currentSong = this.songList[this.curIndex];
  17762. }
  17763. }
  17764. }
  17765. const previousLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  17766. const previousUrl = await this.resolvePlaybackUrlForCurrentSong('playPrevious');
  17767. if (!previousUrl) {
  17768. if (previousLoading) {
  17769. this.hideLoadIng();
  17770. }
  17771. return;
  17772. }
  17773. this.videoUrl = previousUrl;
  17774. this.name = this.songList[this.curIndex].name
  17775. this.artist = this.songList[this.curIndex].artist
  17776. // 如果是投播模式,使用 CastController 切换上一首
  17777. if (this.castControllerWrapper) {
  17778. Logger.info('heanup playPrevious', '投播模式播放上一首,不调用本地stop()');
  17779. try {
  17780. const prevDuration = this.getSongDurationMs(this.currentSong);
  17781. if (prevDuration > 0) {
  17782. this.duration = prevDuration;
  17783. this.durationTime = Math.floor(prevDuration / 1000);
  17784. this.durationStringTime = secondToTime(this.durationTime);
  17785. this.totalTime = this.stringForTime(prevDuration);
  17786. this.avSessionController.setAVMetadataMusic(this.currentSong, prevDuration, this.lyricContent);
  17787. }
  17788. this.updateCastProgress(0);
  17789. await this.castControllerWrapper.playPrevious(this.songList, this.curIndex, this.videoUrl, prevDuration);
  17790. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  17791. if (previousLoading) {
  17792. this.hideLoadIng();
  17793. }
  17794. } catch (error) {
  17795. Logger.error('heanup playPrevious', `CastController 播放上一首失败: ${error}`);
  17796. this.isCastPlaying = false;
  17797. }
  17798. this.cover = this.songList[this.curIndex].pixelMapPath;
  17799. return;
  17800. }
  17801. // 本地播放器模式,需要先stop
  17802. this.CONTROL_PlayStatus = PlayStatus.INIT;
  17803. this.stop();
  17804. if (previousLoading) {
  17805. this.showLoadIng();
  17806. }
  17807. this.changeImageAnimation()
  17808. }
  17809. //随机播放模式下点击上一首: 播放刚刚播放过的那一首
  17810. private async randomModePlayFromHistory() {
  17811. if (this.randomPlayHistory.length >= 1) {
  17812. // 播放历史栈的第一首(刚刚播放过的)
  17813. const prevSong = this.randomPlayHistory[0];
  17814. Logger.info('heanup randomModePlayFromHistory', `从随机播放历史栈获取歌曲: ${prevSong.name}, type: ${prevSong.type}, 栈大小: ${this.randomPlayHistory.length}`);
  17815. // 从栈中移除这首歌(因为即将播放它,它应该成为当前歌,而不是历史)
  17816. this.randomPlayHistory.shift();
  17817. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  17818. this.CONTROL_PlayStatus = PlayStatus.INIT;
  17819. this.stop();
  17820. // 验证并修正webdav_account_id(针对远程类型歌曲)
  17821. if (isRemoteCloudType(prevSong.type) && prevSong.webdav_account_id) {
  17822. const manager = RemoteDriveManager.getInstance();
  17823. const account = await manager.getWebDavAccountById(prevSong.webdav_account_id);
  17824. if (!account) {
  17825. Logger.warn(TAG, `randomModePlayFromHistory: 歌曲账号ID无效: ${prevSong.webdav_account_id}, 尝试查找同类型账号`);
  17826. const allAccounts = manager.getAllWebDavAccounts();
  17827. let foundAccount: WebDavAccount | null = null;
  17828. for (let i = 0; i < allAccounts.length; i++) {
  17829. if (allAccounts[i].webType === prevSong.type) {
  17830. foundAccount = allAccounts[i];
  17831. break;
  17832. }
  17833. }
  17834. if (foundAccount && foundAccount.id) {
  17835. Logger.info(TAG, `randomModePlayFromHistory: 找到同类型账号,更新webdav_account_id: ${prevSong.webdav_account_id} -> ${foundAccount.id}`);
  17836. prevSong.webdav_account_id = foundAccount.id.toString();
  17837. await this.table.updateWebDavAccountId(prevSong.filePath, foundAccount.id.toString());
  17838. } else {
  17839. Logger.error(TAG, `randomModePlayFromHistory: 无法找到类型为${prevSong.type}的账号`);
  17840. // 无法播放这首歌,继续尝试下一首历史记录
  17841. if (this.randomPlayHistory.length >= 1) {
  17842. this.randomModePlayFromHistory();
  17843. return;
  17844. } else {
  17845. // 历史记录为空,无法继续
  17846. ToastUtil.showToast('没有更多历史记录');
  17847. return;
  17848. }
  17849. }
  17850. }
  17851. }
  17852. this.currentSong = prevSong;
  17853. const historyLoading = this.beginRemoteSongSwitchLoading(this.currentSong);
  17854. const historyUrl = await this.resolvePlaybackUrlForCurrentSong('randomPlay-history');
  17855. if (!historyUrl) {
  17856. if (historyLoading) {
  17857. this.hideLoadIng();
  17858. }
  17859. return;
  17860. }
  17861. this.videoUrl = historyUrl;
  17862. this.cover = this.currentSong.pixelMapPath
  17863. this.artist = this.currentSong.artist
  17864. this.name = this.currentSong.name;
  17865. console.info('onecold startPlayOrResumePlay randomModePlayFromHistory')
  17866. this.startPlayOrResumePlay();
  17867. } else {
  17868. ToastUtil.showToast('随机播放模式暂无历史记录');
  17869. }
  17870. }
  17871. debounce() {
  17872. const delay = 600;
  17873. let cur = new Date().getTime();
  17874. if (cur - this.last > delay) {
  17875. this.last = cur;
  17876. return true;
  17877. }
  17878. return false;
  17879. }
  17880. /**
  17881. * Sets whether the screen is a constant based on the playback status.
  17882. */
  17883. watchStatus() {
  17884. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  17885. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  17886. this.windowClass.setWindowKeepScreenOn(true);
  17887. } else {
  17888. this.windowClass.setWindowKeepScreenOn(false);
  17889. }
  17890. }
  17891. /**
  17892. * Volume gesture method onActionStart.
  17893. *
  17894. * @param event Gesture event.
  17895. */
  17896. private customDialogComponentIdMM: number = 0
  17897. @Builder
  17898. customDialogComponentMM() {
  17899. Column() {
  17900. Row() {
  17901. Blank()
  17902. Text('验证密码')
  17903. .fontSize(22)
  17904. .fontColor($r('app.color.pri_bg'))
  17905. .margin({ top: 18 })
  17906. Blank()
  17907. Image($r('app.media.close'))
  17908. .fillColor(Color.White)
  17909. .margin({ top: 18, right: 18 })
  17910. .width(20)
  17911. .onClick(() => {
  17912. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  17913. })
  17914. }
  17915. .width('100%') // 使Row占据整个宽度
  17916. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  17917. Verify({
  17918. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  17919. });
  17920. }.height('60%')
  17921. .backgroundColor($r('app.color.index_background'))
  17922. .justifyContent(FlexAlign.SpaceBetween)
  17923. }
  17924. private handleVerifyCompleted(isSuccess: boolean) {
  17925. if (isSuccess) {
  17926. console.log('验证成功');
  17927. // 在这里处理验证成功后的逻辑
  17928. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  17929. this.currentPath = this.lockPath
  17930. this.getSortedFiles(this.currentPath)
  17931. } else {
  17932. // console.log('验证失败');
  17933. ToastUtil.showToast('验证失败')
  17934. }
  17935. }
  17936. private showVerifyDialog() {
  17937. promptAction.openCustomDialog({
  17938. transition: TransitionEffect.asymmetric(
  17939. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  17940. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  17941. ,
  17942. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  17943. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  17944. ),
  17945. builder: () => {
  17946. this.customDialogComponentMM()
  17947. },
  17948. isModal: true,
  17949. autoCancel: true,
  17950. maskColor: Color.Transparent,
  17951. alignment: DialogAlignment.Bottom,
  17952. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  17953. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  17954. console.log("dialog onWillDismiss")
  17955. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  17956. dismissDialogAction.dismiss()
  17957. }
  17958. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  17959. dismissDialogAction.dismiss()
  17960. }
  17961. }
  17962. }).then((dialogId: number) => {
  17963. this.customDialogComponentIdMM = dialogId
  17964. })
  17965. }
  17966. //左滑操作 移动文件 重命名 删除等操作
  17967. @Builder
  17968. DeleteButton(item: VideoItem, index: number, filePath: string) {
  17969. Row() {
  17970. //加入收藏
  17971. // Button() {
  17972. // Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  17973. // .fillColor(Color.White)
  17974. // .width(20)
  17975. // }
  17976. // .width(40)
  17977. // .height(40)
  17978. // .type(ButtonType.Circle)
  17979. // .backgroundColor(this.themeColor)
  17980. // .margin(5)
  17981. // .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  17982. // .onClick(() => {
  17983. // if (item) {
  17984. // this.doFav(item)
  17985. // }
  17986. // })
  17987. //加入下一首播放
  17988. Button() {
  17989. Image($r('app.media.next_to_play'))
  17990. .fillColor(Color.White)
  17991. .width(20)
  17992. }
  17993. .width(40)
  17994. .height(40)
  17995. .type(ButtonType.Circle)
  17996. .backgroundColor(this.themeColor)
  17997. .margin(5)
  17998. .visibility(this.supportsLocalAudioActions(item) ? Visibility.Visible : Visibility.None)
  17999. .onClick(() => {
  18000. this.addToNextPlay(item);
  18001. })
  18002. //复制文件
  18003. Button() {
  18004. Image($r('app.media.copy'))
  18005. .fillColor(Color.White)
  18006. .width(20)
  18007. }
  18008. .width(40)
  18009. .height(40)
  18010. .type(ButtonType.Circle)
  18011. .backgroundColor(this.themeColor)
  18012. .margin(5)
  18013. .id(filePath + 'copy')
  18014. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  18015. .onClick(() => {
  18016. this.showCopyDialog(false, item, index, filePath + 'copy');
  18017. })
  18018. //移动文件
  18019. Button() {
  18020. Image($r('app.media.cut'))
  18021. .fillColor(Color.White)
  18022. .width(20)
  18023. }
  18024. .width(40)
  18025. .height(40)
  18026. .type(ButtonType.Circle)
  18027. .backgroundColor(this.themeColor)
  18028. .margin(5)
  18029. .id(filePath)
  18030. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  18031. .onClick(() => {
  18032. this.showCutDialog(false, item, index, filePath);
  18033. })
  18034. Button() {
  18035. Image($r('app.media.cut_current'))
  18036. .fillColor(Color.White)
  18037. .width(20)
  18038. }
  18039. .width(40)
  18040. .height(40)
  18041. .type(ButtonType.Circle)
  18042. .backgroundColor(this.themeColor)
  18043. .margin(5)
  18044. .id(filePath + 'current')
  18045. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  18046. (this.isHasDir ? Visibility.Visible : Visibility.None))
  18047. .onClick(() => {
  18048. this.showCutDialog(true, item, index, filePath + 'current');
  18049. })
  18050. //重命名
  18051. // Button() {
  18052. // Image($r('app.media.rename2'))
  18053. // .fillColor(Color.White)
  18054. // .width(20)
  18055. // }
  18056. // .width(40)
  18057. // .height(40)
  18058. // .type(ButtonType.Circle)
  18059. // .backgroundColor(this.themeColor)
  18060. // .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  18061. // (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  18062. // item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  18063. // .margin(5)
  18064. // .onClick(() => {
  18065. // this.showReNameDialog(item, index + '', filePath)
  18066. //
  18067. // })
  18068. Button() {
  18069. Image($r('app.media.delete2'))
  18070. .fillColor(Color.White)
  18071. .width(20)
  18072. }
  18073. .width(40)
  18074. .height(40)
  18075. .type(ButtonType.Circle)
  18076. .backgroundColor(this.themeColor)
  18077. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  18078. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  18079. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  18080. .margin({ left:5,top:5,bottom:5,right:20} )
  18081. .onClick(() => {
  18082. this.selectSingleItemForDelete(item)
  18083. this.showWarnIsDelete()
  18084. // this.showWarnIsDeleteFile(item, index + '', filePath)
  18085. })
  18086. // Button() {
  18087. // Image($r('app.media.share2'))
  18088. // .fillColor(Color.White)
  18089. // .width(20)
  18090. // }
  18091. // .width(40)
  18092. // .height(40)
  18093. // .type(ButtonType.Circle)
  18094. // .backgroundColor(this.themeColor)
  18095. // .margin(5)
  18096. // .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  18097. // .onClick(() => {
  18098. // Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  18099. // })
  18100. }
  18101. }
  18102. /**
  18103. * 穿山甲banner广告
  18104. */
  18105. // private declare bannerAd: CSJNativeExpressAd;
  18106. // @State private status: string = "未加载"
  18107. // @State private isShowAd: boolean = false
  18108. // private declare mAdSlot: AdSlot;
  18109. // private mBiddingAdm = '' //服务端bidding才需要设置
  18110. // private expressLoadAdListener: NativeExpressAdListener = {
  18111. // /**
  18112. // * 加载失败的回调
  18113. // *
  18114. // * @param code
  18115. // * @param message
  18116. // */
  18117. // onError: (code: number, message: string) => {
  18118. // console.error("加载广告失败,code=" + code + ",message=" + message);
  18119. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  18120. // },
  18121. //
  18122. // /**
  18123. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  18124. // *
  18125. // * @param ads 返回的广告列表
  18126. // */
  18127. //
  18128. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  18129. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  18130. // if (ads && ads.length > 0) {
  18131. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  18132. // ad.setExpressInteractionListener({
  18133. // /**
  18134. // *广告的点击回调
  18135. // * @param type 广告的交互类型
  18136. // */
  18137. // onAdClicked: (type: number) => {
  18138. // console.log("BannerExpressAdPage==onAdClicked......");
  18139. // },
  18140. //
  18141. // /**
  18142. // * 广告的展示回调 每个广告仅回调一次
  18143. // * @param type 广告的交互类型
  18144. // */
  18145. // onAdShow: (type: number) => {
  18146. // console.log("BannerExpressAdPage==onAdShow......");
  18147. // },
  18148. //
  18149. // /**
  18150. // * 模板渲染失败
  18151. // */
  18152. // onRenderFail: (code: number, msg: string) => {
  18153. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  18154. // },
  18155. //
  18156. // /**
  18157. // * 模板渲染成功
  18158. // * @param width 返回view的宽 单位 vp
  18159. // * @param height 返回view的高 单位 vp
  18160. // */
  18161. // onRenderSuccess: (width: number, height: number) => {
  18162. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  18163. // this.bannerAd = ad;
  18164. // this.status = "广告加载完成待展示";
  18165. //
  18166. // this.showBannerAd()
  18167. // }
  18168. // })
  18169. // //渲染广告
  18170. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  18171. // this.setDislikeCallback(ad); //设置dislike
  18172. // ad.render(this.getUIContext())
  18173. // this.status = "广告加载中...";
  18174. // });
  18175. // }
  18176. // }
  18177. // }
  18178. //
  18179. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  18180. // ad.setDislikeCallback({
  18181. // /**
  18182. // * dislike show
  18183. // */
  18184. // onShow: () => {
  18185. // console.log("BannerExpressAdPage==dislike......show");
  18186. // },
  18187. //
  18188. // /**
  18189. // * @param position 选择的位置
  18190. // * @param value 选择的内容
  18191. // * @param enforceRemove 是否强制关闭广告
  18192. // */
  18193. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  18194. // this.isShowAd = false;
  18195. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  18196. // ",enforce=" + enforceRemove);
  18197. // },
  18198. //
  18199. // /**
  18200. // * 点击取消
  18201. // */
  18202. // onCancel: () => {
  18203. // console.log("BannerExpressAdPage==dislike......onCancel");
  18204. // }
  18205. //
  18206. // })
  18207. // }
  18208. /**
  18209. * 加载Banner广告
  18210. */
  18211. loadBannerAd(rit: string) {
  18212. // if (Utility.isNoble()) {
  18213. // return
  18214. // }
  18215. // if (!Utility.isPassInstallTime(2)) {
  18216. // return
  18217. // }
  18218. // this.isShowAd = false;
  18219. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  18220. // this.mAdSlot = new AdSlotBuilder()
  18221. // .setCodeId(rit)
  18222. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  18223. // .setAdCount(1)
  18224. // .setBidAdm(this.mBiddingAdm)
  18225. // .build()
  18226. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  18227. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  18228. // this.status = "广告加载中..."
  18229. }
  18230. /**
  18231. * 展示Banner广告
  18232. */
  18233. // showBannerAd() {
  18234. // if (!this.bannerAd) {
  18235. // return
  18236. // }
  18237. // this.isShowAd = true
  18238. // this.status = "已展示"
  18239. // }
  18240. /**
  18241. * 穿山甲广告代码结束
  18242. */
  18243. /**
  18244. * 处理歌单播放请求
  18245. */
  18246. private syncWebdavQueueWithoutRestart(): void {
  18247. try {
  18248. if (!this.currentSong || !isWebDavType(this.currentSong.type)) {
  18249. return;
  18250. }
  18251. const webdavList = getWebdavVideoItems();
  18252. if (!ArrayUtil.isNotEmpty(webdavList)) {
  18253. return;
  18254. }
  18255. const currentPath = this.currentSong.filePath;
  18256. let targetIndex = webdavList.findIndex((item: VideoItem) => item.filePath === currentPath);
  18257. if (targetIndex < 0) {
  18258. const memoryIndex = getWebdavCurrentPlayIndex();
  18259. if (memoryIndex >= 0 && memoryIndex < webdavList.length) {
  18260. targetIndex = memoryIndex;
  18261. }
  18262. }
  18263. if (targetIndex < 0) {
  18264. targetIndex = 0;
  18265. }
  18266. this.songList = [...webdavList];
  18267. this.currentSongList = [...webdavList];
  18268. this.sonDataSource.pushArrayData(this.songList);
  18269. this.currentPlaylistSongFilePaths = this.songList.map(song => song.filePath);
  18270. this.curIndex = targetIndex;
  18271. PreferencesUtil.putSync('LastMusicList', this.songList);
  18272. Logger.info(TAG, `WebDAV播放队列已刷新,当前索引=${this.curIndex}, 队列长度=${this.songList.length}`);
  18273. } catch (error) {
  18274. Logger.error(TAG, `刷新WebDAV播放队列失败: ${(error as Error).message}`);
  18275. }
  18276. }
  18277. private async handlePlaylistPlayRequest(playlistId: string, playlistName:
  18278. string, songFilePaths: string[], startIndex: number, isJump: boolean, songCount?: number) {
  18279. try {
  18280. const totalCount = songCount ?? songFilePaths.length;
  18281. Logger.info(`heanup 处理歌单播放请求: ${playlistName}, 已加载: ${songFilePaths.length}, 服务端总数: ${totalCount}, 开始索引: ${startIndex}`)
  18282. // 检查是否为WebDAV播放请求
  18283. if (playlistId === 'webdav-playlist') {
  18284. Logger.info(`heanup 检测到WebDAV播放请求,从内存读取videoItems`)
  18285. // 从全局内存读取videoItems数据
  18286. const videoItems = getWebdavVideoItems();
  18287. const currentPlayIndex = getWebdavCurrentPlayIndex();
  18288. Logger.info(`heanup 从内存读取到WebDAV歌曲列表,长度:${videoItems.length},索引:${currentPlayIndex}`)
  18289. if (videoItems && videoItems.length > 0) {
  18290. // 验证webdav_account_id设置情况
  18291. const accountIds = videoItems.map(item => item.webdav_account_id).filter(id => id);
  18292. Logger.info(`heanup 有 ${accountIds.length}/${videoItems.length} 首歌曲设置了webdav_account_id`)
  18293. if(isJump){
  18294. this.setShowPlayTrue()//显示播放页
  18295. }
  18296. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName, totalCount)
  18297. return
  18298. } else {
  18299. return
  18300. }
  18301. }
  18302. if (playlistId === 'navidrome-playlist') {
  18303. Logger.info(`heanup 检测到Navidrome播放请求,从内存读取videoItems`);
  18304. const videoItems = getNavidromeVideoItems();
  18305. const currentPlayIndex = getNavidromeCurrentPlayIndex();
  18306. Logger.info(`heanup Navidrome歌曲列表长度: ${videoItems.length}, 服务端总数: ${totalCount}`);
  18307. if (videoItems && videoItems.length > 0) {
  18308. if(isJump){
  18309. this.setShowPlayTrue()//显示播放页
  18310. }
  18311. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName, totalCount);
  18312. return;
  18313. } else {
  18314. Logger.warn('heanup Navidrome播放请求缺少歌曲数据');
  18315. return;
  18316. }
  18317. }
  18318. if (playlistId === 'find-album-playlist' || playlistId.indexOf('find-') === 0) {
  18319. Logger.info(`heanup 检测到发现页播放请求,从内存读取videoItems`)
  18320. const videoItems = getFindVideoItems();
  18321. const currentPlayIndex = getFindCurrentPlayIndex();
  18322. Logger.info(`heanup 发现页歌曲列表长度: ${videoItems.length}, 索引: ${currentPlayIndex}`)
  18323. if (videoItems && videoItems.length > 0) {
  18324. if (isJump) {
  18325. this.setShowPlayTrue()
  18326. }
  18327. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName, totalCount)
  18328. return
  18329. } else {
  18330. Logger.warn('heanup 发现页播放请求缺少歌曲数据')
  18331. return
  18332. }
  18333. }
  18334. // 从数据库重新加载这些歌曲,使用索引记录位置以保持顺序
  18335. const songMap: Map<number, VideoItem> = new Map()
  18336. let completedQueries = 0
  18337. Logger.info(`heanup 开始从数据库查询 ${songFilePaths.length} 首歌曲`)
  18338. // 遍历所有文件路径,使用索引记录位置
  18339. for (let i = 0; i < songFilePaths.length; i++) {
  18340. const filePath = songFilePaths[i]
  18341. const index = i
  18342. // Logger.info(`heanup 正在查询歌曲[${index}]: ${filePath}`)
  18343. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  18344. const queryPromise = this.table.queryVideoByFilePath(filePath)
  18345. // Logger.info(`heanup 创建了查询Promise,开始等待结果[${index}]: ${filePath}`)
  18346. queryPromise.then((videoItem) => {
  18347. completedQueries++
  18348. // Logger.info(`heanup 查询Promise返回结果[${index}]: ${filePath}, 找到歌曲: ${videoItem ? videoItem.name : 'null'}`)
  18349. if (videoItem) {
  18350. // 使用索引作为key保存到Map中,保持原始顺序
  18351. songMap.set(index, videoItem)
  18352. // Logger.info(`heanup 从数据库找到歌曲[${index}]: ${videoItem.name} (${completedQueries}/${songFilePaths.length})`)
  18353. } else {
  18354. Logger.warn(`heanup 数据库中未找到歌曲[${index}]: ${filePath} (${completedQueries}/${songFilePaths.length})`)
  18355. }
  18356. // 检查是否所有歌曲都已加载完成
  18357. if (completedQueries === songFilePaths.length) {
  18358. // Logger.info(`heanup 所有数据库查询完成,共找到 ${songMap.size} 首歌曲`)
  18359. // 按照索引顺序重建歌曲数组
  18360. const songs: VideoItem[] = []
  18361. for (let j = 0; j < songFilePaths.length; j++) {
  18362. const song = songMap.get(j)
  18363. if (song) {
  18364. songs.push(song)
  18365. // Logger.info(`heanup 按顺序添加歌曲[${j}]: ${song.name}`)
  18366. }
  18367. }
  18368. Logger.info(`heanup 最终歌曲列表顺序: ${songs.map((s, idx) => `[${idx}]${s.name}`).join(', ')}`)
  18369. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  18370. }
  18371. }).catch((error: Error) => {
  18372. completedQueries++
  18373. Logger.error(`heanup 查询歌曲失败[${index}]: ${filePath}, 错误: ${error.message} (${completedQueries}/${songFilePaths.length})`)
  18374. // 即使出错也要检查是否完成所有查询
  18375. if (completedQueries === songFilePaths.length) {
  18376. Logger.info(`heanup 所有数据库查询完成(包含错误),共找到 ${songMap.size} 首歌曲`)
  18377. // 按照索引顺序重建歌曲数组
  18378. const songs: VideoItem[] = []
  18379. for (let j = 0; j < songFilePaths.length; j++) {
  18380. const song = songMap.get(j)
  18381. if (song) {
  18382. songs.push(song)
  18383. }
  18384. }
  18385. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  18386. }
  18387. })
  18388. }
  18389. } catch (error) {
  18390. Logger.error('heanup 处理简化歌单播放请求失败: ' + error)
  18391. ToastUtil.showToast('播放失败')
  18392. }
  18393. }
  18394. /**
  18395. * 完成歌单加载并开始播放
  18396. */
  18397. private finishLoadingPlaylist(songs: VideoItem[], startIndex: number, playlistName: string, totalCount?: number) {
  18398. if (songs.length === 0) {
  18399. Logger.error('heanup 没有找到任何可播放的歌曲')
  18400. ToastUtil.showToast('没有找到可播放的歌曲')
  18401. return
  18402. }
  18403. this.songList = songs
  18404. this.currentSongList = songs // 同步更新 currentSongList
  18405. this.sonDataSource.pushArrayData(songs)
  18406. this.sonDataSource.notifyDataReload()
  18407. this.curIndex = startIndex
  18408. // 保存歌单的歌曲路径列表,用于随机播放
  18409. this.currentPlaylistSongFilePaths = songs.map(song => song.filePath);
  18410. const actualTotal = totalCount ?? songs.length;
  18411. // 如果是网盘播放,保存服务端总数到全局存储
  18412. if (totalCount && totalCount > 0 && songs.length > 0) {
  18413. const firstSong = songs[0];
  18414. if (firstSong && (isNavidromeType(firstSong.type) ||
  18415. isJellyfinType(firstSong.type) ||
  18416. isEmbyType(firstSong.type) ||
  18417. isAudioStationType(firstSong.type) ||
  18418. isPlexType(firstSong.type) ||
  18419. isDaoLiYuType(firstSong.type))) {
  18420. setNavidromeTotalCount(totalCount);
  18421. Logger.info('heanup finishLoadingPlaylist', `已保存服务端总数到全局存储: ${totalCount}`);
  18422. }
  18423. }
  18424. Logger.info('heanup finishLoadingPlaylist', `保存歌单歌曲路径列表,已加载=${this.currentPlaylistSongFilePaths.length}, 服务端总数=${actualTotal}`);
  18425. if (songs[startIndex]) {
  18426. // 确保当前播放的歌曲也更新到存储
  18427. AppStorage.setOrCreate('currentSong', songs[startIndex])
  18428. // 设置isFromSonPlayList=true,避免doPlay方法重新从全局列表构建播放列表
  18429. this.doPlay(songs[startIndex], startIndex, true)
  18430. }
  18431. PreferencesUtil.putSync('LastMusicList', this.songList)
  18432. // ToastUtil.showToast(`开始播放歌单: ${playlistName}`)
  18433. }
  18434. }
  18435. //视频气泡窗口的布局
  18436. @Builder
  18437. function customPopupBuilder(dataBu: BubbleBean) {
  18438. List() {
  18439. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  18440. ListItem() {
  18441. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  18442. Row() {
  18443. Column() {
  18444. Image(dataBu.imageRes[index])
  18445. .height(28)
  18446. .fillColor(dataBu.color)
  18447. .alignSelf(ItemAlign.Center)
  18448. }
  18449. .width(32)
  18450. Text(item)
  18451. .padding({
  18452. top: 10,
  18453. bottom: 10,
  18454. right: 10,
  18455. left: 10
  18456. })
  18457. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  18458. .textAlign(TextAlign.Start)
  18459. .width("100%")
  18460. }
  18461. }
  18462. .backgroundColor($r('app.color.settings_background_main'))
  18463. .margin({ top: 6, bottom: 6 })
  18464. }
  18465. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  18466. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  18467. TransitionEffect.scale({ x: 0, y: 0 })))
  18468. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  18469. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  18470. .onClick(() => {
  18471. dataBu.onItemClick?.(index)
  18472. })
  18473. })
  18474. }
  18475. .scrollBar(BarState.Off)
  18476. .width(120)
  18477. .divider({
  18478. strokeWidth: 1,
  18479. color: "#22FFFFFF"
  18480. })
  18481. }
  18482. // Function to calculate a hash for the file list
  18483. function simpleHash(fileList: string[]): string {
  18484. let hash = 0;
  18485. const str = fileList.join(',');
  18486. for (let i = 0; i < str.length; i++) {
  18487. const char = str.charCodeAt(i);
  18488. hash = (hash << 5) - hash + char;
  18489. hash |= 0; // Convert to 32bit integer
  18490. }
  18491. return hash.toString();
  18492. }
  18493. interface MoreItem {
  18494. id: number;
  18495. image: Resource;
  18496. title: string;
  18497. }
  18498. //视频气泡窗口的布局
  18499. @Builder
  18500. function cutPopupBuilder(dataBu: BubbleBean) {
  18501. Column() {
  18502. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  18503. .padding({
  18504. top: 10,
  18505. bottom: 10,
  18506. right: 10,
  18507. left: 10
  18508. })
  18509. .textAlign(TextAlign.Start)
  18510. .width(160)
  18511. .fontWeight(666)
  18512. .fontSize(16)
  18513. List() {
  18514. ForEach(dataBu.data, (item: string, index: number) => {
  18515. ListItem() {
  18516. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  18517. Row() {
  18518. Column() {
  18519. Image($r('app.media.music_group'))
  18520. .height(28)
  18521. .fillColor(dataBu.color)
  18522. .alignSelf(ItemAlign.Center)
  18523. }
  18524. .width(32)
  18525. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  18526. .padding({
  18527. top: 10,
  18528. bottom: 10,
  18529. right: 10,
  18530. left: 10
  18531. })
  18532. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  18533. .fontSize(15)
  18534. }
  18535. }
  18536. .backgroundColor(Color.Transparent)
  18537. .margin({ top: 7, bottom: 7 })
  18538. }
  18539. .onClick(() => {
  18540. dataBu.onItemClick?.(index)
  18541. })
  18542. })
  18543. }
  18544. .scrollBar(BarState.Off)
  18545. .width(150)
  18546. .divider({
  18547. strokeWidth: 1,
  18548. color: "#22FFFFFF"
  18549. })
  18550. }
  18551. .height(300)
  18552. .padding({
  18553. bottom: 30
  18554. })
  18555. }
  18556. @Concurrent
  18557. function buildAlphabetIndexTask(items: Array<AlphaTaskItem>, sortType: number, isShowFileName: boolean): Array<string> {
  18558. const alphabetSet = new Set<string>()
  18559. for (const item of items) {
  18560. let text = isShowFileName ? (item.fileName || '') :
  18561. (item.type != CommonConstants.TYPE_IS_DIR && item.pyStr) ? item.pyStr : (item.name || '')
  18562. if (sortType === 0 || sortType == 1) {
  18563. text = item.artist || ''
  18564. } else if (sortType === 2 || sortType == 3) {
  18565. text = item.album || ''
  18566. }
  18567. if (text && text.length > 0) {
  18568. const first = getFirstLetter(text)
  18569. if (!alphabetSet.has(first)) {
  18570. alphabetSet.add(first)
  18571. }
  18572. }
  18573. }
  18574. const sorted = Array.from(alphabetSet).sort((a, b) => {
  18575. if (sortType === 4 || sortType == 0 || sortType == 2 || sortType == 6) {
  18576. return a.localeCompare(b)
  18577. }
  18578. return b.localeCompare(a)
  18579. })
  18580. return sorted
  18581. }
  18582. function getFileDirName(filePath: string,rootPath:string): string{
  18583. if(filePath===rootPath){
  18584. return '首页'
  18585. }
  18586. let result = FileUtil.getFileName(filePath)
  18587. if(StrUtil.isEmpty(result))
  18588. return ''
  18589. if(result.startsWith('.'))
  18590. result = result.replace(/\./g, '')
  18591. return result
  18592. }
  18593. //只扫描当前目录下文件(不扫描子文件夹)的方法
  18594. @Concurrent
  18595. async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
  18596. const table: MediaTable = new MediaTable(context);
  18597. try {
  18598. // 直接获取当前目录下的文件列表
  18599. const files = FileUtil.listFileSync(dirPath);
  18600. await Promise.all(files.map(async (file) => {
  18601. const fPath = `${dirPath}/${file}`;
  18602. // 跳过目录,只处理文件
  18603. if (FileUtil.isDirectory(fPath)) {
  18604. return;
  18605. }
  18606. // 跳过特定格式文件
  18607. if (fPath.endsWith('.lrc') || fPath.endsWith('.srt')) {
  18608. return;
  18609. }
  18610. // 检查是否为媒体文件
  18611. if (Utility.isMeidaByExtension(fPath)) {
  18612. let mType = CommonConstants.TYPE_LOCAL;
  18613. if (fPath.includes(lockPath)) {
  18614. mType = CommonConstants.TYPE_LOCK;
  18615. }
  18616. const mediaItem = await Utility.uriGetMusicAssetsFromFile(
  18617. context, fPath, mType, true
  18618. );
  18619. table.insert(mediaItem, (id: number) => {
  18620. // 插入回调函数
  18621. }, cover_api);
  18622. }
  18623. }));
  18624. } catch (error) {
  18625. console.error(' 扫描当前目录失败:', error);
  18626. }
  18627. }
  18628. //内嵌标签后更新库
  18629. @Concurrent
  18630. async function updateInfoDb(
  18631. context: Context,
  18632. filePath: string,
  18633. titleStr: string,
  18634. artistStr: string,
  18635. albumStr: string,
  18636. lyricConStr: string,
  18637. yearStr: string,
  18638. genreStr: string,
  18639. trackStr: string,
  18640. albumArtistStr: string,
  18641. composerStr: string,
  18642. lyricistStr: string,
  18643. commentStr: string,
  18644. discStr: string,
  18645. ): Promise<boolean> {
  18646. const table: MediaTable = new MediaTable(context);
  18647. await new Promise<void>((resolve, reject) => {
  18648. table.getRdbStore(context, (err:Error) => {
  18649. err ? reject(err) : resolve();
  18650. });
  18651. });
  18652. return await new Promise<boolean>((resolve) => {
  18653. table.updateMediaInfo(filePath, titleStr, artistStr, albumStr, lyricConStr,
  18654. yearStr, genreStr, trackStr, albumArtistStr, composerStr, lyricistStr, commentStr, discStr,
  18655. (success: boolean, error?: string) => {
  18656. if (success) {
  18657. console.log("onecold 编辑信息成功,数据库已同步");
  18658. } else {
  18659. console.error("onecold 编辑信息数据库失败原因: " + error);
  18660. }
  18661. resolve(success);
  18662. });
  18663. });
  18664. }
  18665. @Concurrent
  18666. async function replaceLocalMusicCoverTask(
  18667. context: Context,
  18668. filePath: string,
  18669. sandboxCoverPath: string
  18670. ): Promise<boolean> {
  18671. const coverResult: boolean = await changeMusicCover(context, filePath, sandboxCoverPath, true, '');
  18672. if (!coverResult) {
  18673. return false;
  18674. }
  18675. const table: MediaTable = new MediaTable(context);
  18676. await new Promise<void>((resolve, reject) => {
  18677. table.getRdbStore(context, (err: Error) => {
  18678. err ? reject(err) : resolve();
  18679. });
  18680. });
  18681. return await new Promise<boolean>((resolve) => {
  18682. table.updateCustomCoverPath(filePath, fileUri.getUriFromPath(sandboxCoverPath),
  18683. (success: boolean, _error?: string) => {
  18684. resolve(success);
  18685. });
  18686. });
  18687. }