LocalMusic.ets 672 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954
  1. import TitleBar from './TitleBar'
  2. import { curves, display, MenuModifier, PiPWindow, promptAction, router, SymbolGlyphModifier, window } from '@kit.ArkUI';
  3. import { VideoItem } from '../viewmodel/VideoItem';
  4. import { LengthMetrics, SegmentButton,SegmentButtonOptions } from '@kit.ArkUI';
  5. import { getWebdavVideoItems, getWebdavCurrentPlayIndex } from '../pages/WebDavMainPage';
  6. import {
  7. getNavidromeVideoItems,
  8. getNavidromeCurrentPlayIndex,
  9. getUnplayedSongs,
  10. getUnplayedCount,
  11. markAsPlayed,
  12. clearPlayedHistory,
  13. getPlayedCount,
  14. getNavidromeTotalCount,
  15. setNavidromeTotalCount
  16. } from '../common/util/NavidromePlaylistStore';
  17. import { triggerLoadMoreSongs, hasMoreData } from '../common/util/NavidromeRandomLoader';
  18. import {
  19. ImplOnBufferingUpdateListener,
  20. ImplOnCompletionListener,
  21. ImplOnErrorListener,
  22. ImplOnInfoListener,
  23. ImplOnPreparedListener,
  24. ImplOnSeekCompleteListener,
  25. ImplOnTimedTextListener,
  26. ImplOnVideoSizeChangedListener
  27. } from '../common/IjkPlayerListenerImpls';
  28. import {
  29. ButtonFancyModifier,
  30. ImageFancyModifier,
  31. ShadowModifier,
  32. SymbolGlyphFancyModifier } from '../common/util/AttributeModifierUtil'
  33. import {
  34. AppUtil,
  35. ArrayUtil,
  36. Base64Util,
  37. DateUtil,
  38. DeviceUtil,
  39. FileUtil,
  40. GlobalContext,
  41. LogUtil,
  42. MD5,
  43. PreferencesUtil,
  44. RandomUtil,
  45. StrUtil,
  46. ToastUtil
  47. } from '@pura/harmony-utils';
  48. import { imagePathToPixelMap } from '../common/util/CommUtils';
  49. import LyricUtil from '../common/util/LyricUtil';
  50. import { unifiedDataChannel, uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData';
  51. import { CommonConstants } from '../common/constants/CommonConstants';
  52. import { BaiduConstants } from '../common/constants/BaiduConstants';
  53. import { EventConstants } from '../common/constants/EventConstants';
  54. import Logger from '../common/util/Logger';
  55. import { http } from '@kit.NetworkKit';
  56. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  57. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  58. import { BubbleBean } from '../viewmodel/BubbleBean';
  59. import { PopupPosition, XPopup } from '@chinalike/popup';
  60. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  61. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  62. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  63. import { MessageEvents, util, worker, ErrorEvent, JSON } from '@kit.ArkTS';
  64. import { Verify } from './Verify';
  65. import { taskpool } from '@kit.ArkTS';
  66. import { RotatingCover } from './RotatingCover';
  67. import { SpectrumView } from './spectrum/SpectrumView';
  68. import { PointLightButton } from './PointLight/PointLightButton';
  69. import { PlayConstants } from '../common/constants/PlayConstants';
  70. import { effectKit } from '@kit.ArkGraphics2D';
  71. import { ColorConversion } from '../common/util/ColorConversion';
  72. import { Lyric, LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  73. import { AvSessionController } from '../controller/AvSessionController';
  74. import { EqualizerManager } from '../common/util/EqualizerManager';
  75. import { EqualizerViewWithCallback } from './EqualizerView';
  76. import { CastController, CastControllerCallbacks } from '../controller/CastController';
  77. import { repairAudioMetadata, convertDsfToWav, getApiLyric,changeMusicCover} from '../common/util/MusicTagUtils';
  78. import { extractHwMediaMetadata, FFMpegTags,Utility } from '../common/util/Utility';
  79. import { TagsContentCover } from '../view/TagsContentCover';
  80. import {
  81. DeviceChangeReason,
  82. IjkMediaPlayer,
  83. InterruptEvent,
  84. InterruptHintType,
  85. LogUtils,
  86. OnBufferingUpdateListener,
  87. OnCompletionListener,
  88. OnErrorListener,
  89. OnInfoListener,
  90. OnPreparedListener,
  91. OnSeekCompleteListener,
  92. OnTimedTextListener,
  93. OnVideoSizeChangedListener
  94. } from '@ohos/ijkplayer';
  95. import { PlayStatus } from '../common/PlayStatus';
  96. import fs from '@ohos.file.fs';
  97. import { image } from '@kit.ImageKit';
  98. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  99. import { media } from '@kit.MediaKit';
  100. import { UniversalDetector } from '@ohos/juniversalchardet';
  101. import { SettingPage } from '../pages/SettingPage';
  102. import { secondToTime,getTransverterText } from '../common/util/CommUtils';
  103. import { CommonConstants2 } from '../common/util/CommonConstants2';
  104. import { hilog } from '@kit.PerformanceAnalysisKit';
  105. import { LazyDataSource } from '../common/util/LazyDataSource';
  106. import MediaTable, { PageQueryOptions, PageQueryResult, RandomSongQueryOptions } from '../common/util/MediaTable';
  107. import FileDeletionWatcher from '../common/util/FileDeletionWatcher';
  108. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  109. import { ringtone } from '@kit.RingtoneKit';
  110. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  111. import { resourceManager } from '@kit.LocalizationKit';
  112. import { deviceInfo } from '@kit.BasicServicesKit';
  113. import '../common/network/RemoteCacheRegistry';
  114. import { ServerLogUtil } from '../common/util/ServerLogUtil';
  115. import { lyricService, SongData } from '../common/service/LyricService';
  116. import { shouldResolveRemoteLyricOnPlay, tryResolveRemotePlaybackLyric } from '../common/util/RemotePlaybackLyricUtil';
  117. import {
  118. cloneVideoItem,
  119. preloadNextSongIfNeeded,
  120. setVideoUrlForSong,
  121. getTypeOrder,
  122. isWebDavType,
  123. isSmbType,
  124. isNavidromeType,
  125. isFtpType,
  126. isBaiduType,
  127. isJellyfinType,
  128. isEmbyType,
  129. isAudioStationType,
  130. isPlexType,
  131. isRemoteCloudType,
  132. WorkerEditMusicResult,
  133. WebDavMetadataUpdatePayload,
  134. isDaoLiYuType
  135. } from '../common/util/RemotePlayerUtil';
  136. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  137. import app from '@system.app';
  138. import { TextNodeController } from './PipLyricTextBuilder';
  139. import { IndexerView } from './IndexerView';
  140. import { KeyCode } from '@kit.InputKit';
  141. import { KnockController } from '../controller/KnockController';
  142. import { DeleteComptent } from '../view/DeleteComptent';
  143. import { ABLoopComptent } from '../view/ABLoopComptent';
  144. import { FixMessyView } from '../view/FixMessyView';
  145. import { parseCueFile,CueTrack,CueInfo } from '../common/util/CueUtils';
  146. import { CueComptent } from '../view/CueComptent';
  147. import PlaylistTable from '../common/util/PlaylistTable';
  148. import { showAddToPlaylistDialog } from '../dialog/AddToPlaylistDialog';
  149. import { showCreatePlaylistDialog } from '../dialog/PlaylistDialog';
  150. import { convertPlaylistSongsToVideoItems, emptyView,updateAllSongsSortOrder } from '../pages/PlaylistDetailPage';
  151. import { Playlist, PlaylistSong } from '../viewmodel/Playlist';
  152. import { Song } from '../viewmodel/Song';
  153. import { WebDavAccount } from '../viewmodel/WebDavAccount';
  154. import { SongType } from '../common/enums/SongType';
  155. import { RemoteDriveManager, WebDavAuthInfo as WebDavManagerAuthInfo,
  156. buildHttpHeadersWithWebDav,
  157. WebDavAuthItem} from '../common/util/RemoteDriveManager';
  158. import PermissionUtil from '../common/util/PermissionUtil'
  159. import { EditAudio, setRingTone } from './EditAudio';
  160. import { ExtractAccompaniment } from './ExtractAccompaniment';
  161. import { ExtractAudioFromVideo } from './ExtractAudioFromVideo';
  162. import { AudioFormatConverter } from './AudioFormatConverter';
  163. import { MergeAudio } from './MergeAudio';
  164. import { AIVoiceSeparation } from './AIVoiceSeparation';
  165. import { WebDavUrlUtil } from '../common/util/WebDavUrlUtil';
  166. import { ChangeTone } from './ChangeTone';
  167. import {
  168. hdsEffect,
  169. HdsVisualComponent,
  170. HdsSceneController,
  171. HdsSceneType,
  172. HdsVisualComponentAttribute,
  173. } from '@kit.UIDesignKit';
  174. import { GlobalAlphabetIndexerModifier } from '../Styels/GlobalStyles'
  175. import { getFirstLetter } from '../Constants';
  176. import { audio } from '@kit.AudioKit';
  177. import { PointLightDefaultButton } from './PointLight/PointLightDeFaultButton';
  178. import { CoverThumbCache } from '../common/util/CoverThumbCache';
  179. import { LyricCopySheet } from './LyricCopySheet';
  180. const TAG = 'LocalMusic';
  181. const HICAR_LOG_TAG = 'HiCarWindow';
  182. function logHiCarWindow(message: string): void {
  183. void ServerLogUtil.info(HICAR_LOG_TAG, message);
  184. }
  185. export interface WorkerMetadataPayload {
  186. originFilePath: string;
  187. originId?: string;
  188. bit_rate?: string;
  189. duration?: string;
  190. sampleRate?: string;
  191. mimeType?: string;
  192. md5Str?: string;
  193. videoSize?: number;
  194. size?: string;
  195. pixelMapPath?: string;
  196. artist?: string;
  197. album?: string;
  198. name?: string;
  199. lyricContent?: string;
  200. bits_per_raw_sample?: string;
  201. channels?: string;
  202. channel_layout?: string;
  203. start_time?: string;
  204. genre?: string;
  205. year?: string;
  206. probe_score?: number;
  207. track?: string;
  208. disc?: string;
  209. ALBUMARTIST?: string;
  210. COMPOSER?: string;
  211. COMMENT?: string;
  212. LYRICIST?: string;
  213. nb_streams?: number;
  214. nb_programs?: number;
  215. error?: string;
  216. }
  217. interface WorkerMessageScanDone {
  218. code: 101;
  219. data: Record<string, never>;
  220. }
  221. interface WorkerMessageMediaList {
  222. code: 102;
  223. data: Array<VideoItem>;
  224. totalCount: number;
  225. }
  226. interface WorkerMessageArtistList {
  227. code: 103;
  228. data1: Map<string, Array<VideoItem>>;
  229. data2: Array<VideoItem>;
  230. totalCount: number;
  231. }
  232. interface WorkerMessageAlbumList {
  233. code: 104;
  234. data1: Map<string, Array<VideoItem>>;
  235. data2: Array<VideoItem>;
  236. totalCount: number;
  237. }
  238. interface WorkerMessageMetadata {
  239. code: 105;
  240. data: WorkerMetadataPayload;
  241. }
  242. interface WorkerMessageEditResult {
  243. code: 106;
  244. data: WorkerEditMusicResult;
  245. }
  246. interface AlphaTaskItem {
  247. type: number;
  248. name?: string;
  249. pyStr?: string;
  250. fileName?: string;
  251. artist?: string;
  252. album?: string;
  253. }
  254. type LocalMusicWorkerMessage =
  255. WorkerMessageScanDone
  256. | WorkerMessageMediaList
  257. | WorkerMessageArtistList
  258. | WorkerMessageAlbumList
  259. | WorkerMessageMetadata
  260. | WorkerMessageEditResult;
  261. /**
  262. * 歌单播放事件数据
  263. */
  264. interface PlaylistEventData {
  265. playlistId: string;
  266. playlistName: string;
  267. songCount: number;
  268. startIndex: number;
  269. songFilePaths: string[];
  270. isJump: boolean;
  271. webDavAuthInfo?: WebDavAuthItem; // 新增WebDAV认证信息
  272. }
  273. const DEFAULT_INDEX =
  274. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  275. 'X', 'Y', 'Z']
  276. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  277. // 元数据提取状态追踪
  278. const metadataExtractionInFlight: Map<string, Promise<void>> = new Map();
  279. // setVideoUrlForSong 函数已移至 MusicPlayerUtil.ets
  280. // 定义接口
  281. interface HiCarAspectRatio {
  282. ratio: number;
  283. name: string;
  284. }
  285. interface GeneratedObjectLiteralInterface_1 {
  286. assetId: string;
  287. title: string;
  288. artist: string;
  289. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  290. mediaUri: string;
  291. // 该字段大写,音频'AUDIO',视频'VIDEO'
  292. mediaType: string;
  293. mediaSize: number;
  294. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  295. startPosition: number;
  296. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  297. duration: number;
  298. albumCoverUri: string;
  299. albumTitle: string;
  300. appName: string;
  301. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  302. drmScheme: string;
  303. }
  304. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  305. const ITEM_HEIGHT: number = 65; // 列表项中高度
  306. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  307. /**
  308. * 排序模式枚举
  309. * 定义各种排序方式的升序基准值
  310. */
  311. export enum SortMode {
  312. ByArtist = 0, // 按艺术家升序
  313. ByAlbum = 2, // 按专辑升序
  314. ByName = 4, // 按名称升序
  315. ByTime = 6, // 按时间升序
  316. ByAddTime = 7, // 按添加时间(只有降序)
  317. ByCount = 8, // 按数量升序
  318. ByDiscTrack = 10 // 按碟片编号-音轨号升序
  319. }
  320. //功能强大的音乐播放器
  321. @Preview
  322. @Component
  323. export struct LocalMusic {
  324. @State isGeKongPlayNext: boolean = true//是否开启隔空手势播放下一首
  325. @State bluetoothDisconnectPause: boolean = false // 蓝牙设备断开暂停
  326. @State isBluetoothConnected: boolean = false // 蓝牙连接状态
  327. @State bluetoothLyricEnabled: boolean = false // 蓝牙歌词开关
  328. @State bluetoothLyricMode: number = 0 // 蓝牙歌词显示模式
  329. private lastBluetoothLyricLine: string = '' // 上一次发送的歌词行
  330. @State showFindLocation: boolean = true
  331. @StorageProp("EnablePointLight") enablePointLight: boolean = true
  332. @State showSimple: boolean = true//开启沉浸模式
  333. @State isPaging: boolean = true;//是否分页加载机制
  334. @State isCoverRectangle: boolean = true;
  335. @State showZMIndex: boolean = false //是否右侧显示字母索引
  336. private prevOffsetY: number = 0; // 记录上一次的Y轴偏移量
  337. @State autoHideTitle: boolean = true //滚动自动隐藏标题栏
  338. // 字母表
  339. @State alphaBet: string[] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
  340. 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  341. @State alphaBetStyle: GlobalAlphabetIndexerModifier = new GlobalAlphabetIndexerModifier()
  342. @State selectAlphaBetIndex: number = 0
  343. @State isShowAlphaBet: boolean = false
  344. @State isScrolling: boolean = false
  345. @State isTouchingAlphaBet: boolean = false
  346. @State alphabetHeight: number = 0
  347. public enableShowAlphabet: boolean = true // 是否显示字母表
  348. private alphaBetHideTimer: number = 0
  349. private alphaBetRebuildTimer: number = 0
  350. private alphaBetDirty: boolean = false
  351. private alphaBetCacheKey: string = ''
  352. private alphaBetBuildVersion: number = 0
  353. @State isShowPrecious: boolean = false //播控条显示上一首按钮
  354. //背景两侧流光控制器
  355. @State sceneBgController: HdsSceneController|undefined = deviceInfo.sdkApiVersion>=20
  356. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  357. new HdsSceneController()
  358. .setSceneParams({
  359. backgroundMaskColors: [Color.Green, Color.Red],
  360. firstEdgeFlowLight: {
  361. startPos: 0,
  362. endPos: 0.5,
  363. color: Color.Red
  364. },
  365. secondEdgeFlowLight: {
  366. startPos: 0,
  367. endPos: -0.5,
  368. color: Color.Green
  369. }
  370. }) : undefined;
  371. //背景流光控制器
  372. @State bgController: hdsEffect.ShaderEffectController|undefined = deviceInfo.sdkApiVersion>=20
  373. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  374. new hdsEffect.ShaderEffectController():undefined;
  375. @State showAddSheet:boolean = false
  376. private loadingDialogId: string = ''
  377. private loadingProgressDialogId: string = ''
  378. searchController: SearchController = new SearchController()
  379. @State rightTopImage:Resource = $r('sys.symbol.sort')
  380. @State isEditAudio:boolean = false
  381. @State isExtractAcc:boolean = false
  382. @State isConverter:boolean = false
  383. @State isAIVoiceSeparation:boolean = false
  384. @State isExtractAudio:boolean = false
  385. @State isMergeAudio:boolean = false
  386. @State isCopyFileToDownLoad: boolean = false
  387. @State isChangeTone:boolean = false
  388. @State offHeight: number = 75
  389. @State currentSongList: Array<VideoItem> = []//当前歌单
  390. @Consume currentSongListName:string //当前歌单名称
  391. @Consume @Watch('onIDChange') currentSongListID:string //当前歌单ID
  392. @State currentPlaylistSongFilePaths: string[] = [] //当前歌单的歌曲路径列表(用于随机播放)
  393. @State isRefreshing: boolean = false;
  394. @State maxRefreshingHeight: number = 100.0;
  395. @State isPlayerLoading: boolean = false; // 播放器加载状态
  396. private contentNode?: ComponentContent<Object> = undefined;
  397. // WebDAV相关实例变量(现在改为从内存读取,不再需要存储)
  398. @State ratioL: number = 1;
  399. @State mediaKuCount: number = 0;
  400. @State albumCount: number = 0;
  401. @State artistCount: number = 0;
  402. @State fastForwardSeconds: string = '10'
  403. @State isShowBackFast: boolean = true//快进快退按钮
  404. @State isCanAuto:boolean = true
  405. @State opacityValueImage: number = 1;
  406. @State tipPopup:boolean = false
  407. @State preloadNextSong: boolean = PreferencesUtil.getBooleanSync('preload_next_song', true) // 是否提前缓存下一首
  408. @Consume mType: number;
  409. @StorageProp('themeColor') themeColor: string =
  410. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  411. themeMode: number = 0;
  412. @State titleName: string = '首页'
  413. @State textStr: string = ''
  414. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  415. // private download_path: string = '';
  416. @Consume rootPath: string //音频根目录
  417. @Consume currentPath: string
  418. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  419. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  420. @State lockPath: string = ''
  421. @State favPath: string = ''
  422. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  423. @State historyPath: string = ''
  424. @State historyList: Array<VideoItem> = []
  425. @Consume isHistory: boolean
  426. static readonly HISTORY_MUSIC: string = 'music_historyList';
  427. private table: MediaTable = new MediaTable(getContext(this))
  428. private playlistTable: PlaylistTable | null = null
  429. private deletionWatcher: FileDeletionWatcher | null = null
  430. @State allPlaylists: Playlist[] = []
  431. @State isZero: boolean = false
  432. @State fileList: Array<string> = []
  433. @State dirList: Array<VideoItem> = []
  434. @Consume videoLocalList:VideoItem[]
  435. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  436. @State listRefreshKey: number = 0
  437. @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  438. @State artistList: Array<VideoItem> = []; //艺术家文件
  439. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  440. @State artistSongCountMap: Map<string, number> = new Map();
  441. @State albumList: Array<VideoItem> = []; //专辑文件
  442. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  443. @State albumSongCountMap: Map<string, number> = new Map();
  444. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  445. @State imageOpacities: number[] = [];
  446. @Consume isCanBack: boolean
  447. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  448. @State showSingleLyric: boolean = false
  449. @State sortType: number = 4 //默认排序方式
  450. @State isShowSimi: boolean = false //是否显示私密音频
  451. @State isShowFAV: boolean = true //是否显示我的收藏
  452. @State isShowTitleBar: boolean = true //是否显示分类导航条
  453. @State isShowAllBar: boolean = true //是否显示播放全部条
  454. @State isShowSingleLineLyric: boolean = false //是否显示单行歌词
  455. @State isEnableWordByWordLyric: boolean = true //是否开启逐字歌词
  456. @State isShowHistory: boolean = true //是否显示最近播放
  457. @State @Watch('onColorModeChange') isCustomizeBg: boolean = false //自定义背景界面
  458. @State isGridMusic: boolean = false //是否网格布局
  459. @State isCircleBtn: boolean = false //是否圆形播放按钮
  460. @State twoFingerType: number = 3 //双支放大缩小的类型
  461. @State isScrollHide: boolean = false //是否滚动隐藏
  462. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  463. @State isStartAutoPlay: boolean = false //启动后自动播放
  464. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  465. @State isShowHeader: boolean = true
  466. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  467. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  468. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  469. @State isSwipe: boolean = false //listItem的左滑开关
  470. @State openSkipSongAnimate: boolean = true//切歌动画效果
  471. @State isPlayPageSwipeNext: boolean = true // 播放页上滑切歌
  472. @State customizeBgPath: string | undefined = '';
  473. @State isDarkMode: boolean = false
  474. @State lyricTextWeight: number = 400
  475. @State lyricTextWeightPip: number = 400
  476. @State currentSwiperIndex: number = 0
  477. @State blurValue: number = 0 //背景模糊
  478. @State bgBrightness: number = 0 //背景亮度
  479. private listScroller: ListScroller = new ListScroller()
  480. private playListScroller: Scroller = new Scroller()
  481. @State isOneKeyTags:boolean = false
  482. @State isFixMessy:boolean = false
  483. // 分页相关状态
  484. @State private currentPage: number = 0 // 当前页码
  485. @State private pageSize: number = 53 // 每页数量
  486. @State private totalCount: number = 0 // 总记录数
  487. @State private hasMoreData: boolean = true // 是否还有更多数据
  488. @State private isLoadingPage: boolean = false // 是否正在加载分页数据
  489. private pageCache: Map<number, VideoItem[]> = new Map() // 页面缓存(最多保留3页)
  490. private pageHasMoreCache: Map<number, boolean> = new Map()
  491. private pageTotalCountCache: Map<number, number> = new Map()
  492. private prefetchingPages: Set<number> = new Set()
  493. private preloadStartRatio: number = 0.18
  494. private appendStartRatio: number = 0.30
  495. private earlyAppendReserveCount: number = 28
  496. private lastScrollTriggerPage: number = -1
  497. private lastVisibleEndIndex: number = -1
  498. private isPagingTransition: boolean = false
  499. private pagingScheduleTimer: number = 0
  500. private listScrollAlphaCheckAt: number = 0
  501. private listScrollPagingCheckAt: number = 0
  502. private listScrollLastAlphaStart: number = -1
  503. private listScrollLastPagingEnd: number = -1
  504. private gridScrollPagingCheckAt: number = 0
  505. private gridScrollLastPagingEnd: number = -1
  506. private waterScrollPagingCheckAt: number = 0
  507. private waterScrollLastPagingEnd: number = -1
  508. private gridWaterScrollIdleTimer: number = 0
  509. private gridWaterLastActiveTs: number = 0
  510. private listUpdateTimer: number = 0
  511. private listUpdateVersion: number = 0
  512. private detailBackTransitioning: boolean = false
  513. private mediaLibraryEnterTs: number = 0
  514. private mediaLibraryWarmupPrefetchTimer: number = 0
  515. private listVisibleStart: number = -1
  516. private listVisibleEnd: number = -1
  517. private listThumbWarmupCheckAt: number = 0
  518. private listThumbWarmupStart: number = -1
  519. private listThumbWarmupEnd: number = -1
  520. private gridThumbWarmupCheckAt: number = 0
  521. private gridThumbWarmupStart: number = -1
  522. private gridThumbWarmupEnd: number = -1
  523. private waterThumbWarmupCheckAt: number = 0
  524. private waterThumbWarmupStart: number = -1
  525. private waterThumbWarmupEnd: number = -1
  526. private gridVisibleStart: number = -1
  527. private gridVisibleEnd: number = -1
  528. private waterVisibleStart: number = -1
  529. private waterVisibleEnd: number = -1
  530. private titleBarToggleMinDelta: number = 12
  531. private titleBarLastCheckTs: number = 0
  532. @State private coverThumbVersion: number = 0
  533. private coverThumbCache: CoverThumbCache = new CoverThumbCache(1, 960)
  534. private coverThumbCacheReady: boolean = false
  535. private pendingCoverThumbRefresh: boolean = false
  536. private playQueueScope: 'view' | 'history' | 'fav' | 'playlist' | 'single' = 'view'
  537. private isHydratingPlayList: boolean = false
  538. @StorageProp('isLandscape') @Watch('onIsLandscapeChange') isLandscape: boolean = false;
  539. @StorageProp('topSafeHeight') topSafeHeight: number = 0;
  540. @StorageProp('bottomSafeHeight') bottomSafeHeight: number = 0;
  541. @StorageProp('windowWidth') windowWidth: number = 0;
  542. @StorageProp('windowHeight') windowHeight: number = 0;
  543. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  544. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  545. private UNKONWN:string = '';
  546. private listArea: Area = {
  547. width: 0,
  548. height: 0,
  549. position: {},
  550. globalPosition: {}
  551. }
  552. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  553. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  554. // WebDAV认证信息缓存(作为实例变量,比全局上下文更可靠)
  555. private currentWebDavAuthInfo: WebDavAuthItem | null = null;
  556. // 当前实际播放中的记忆key,避免切歌时 currentSong 已切换导致串写
  557. private activePlaybackMemoryKey: string = '';
  558. // 网盘流地址记忆恢复token,切歌后用于取消旧的延迟seek任务
  559. private remoteRestoreSeekToken: number = 0;
  560. // 本次是否需要先seek到记忆点再开始播放
  561. private waitInitialSeekBeforeStart: boolean = false;
  562. // 本次播放记忆点(毫秒)
  563. private pendingMemorySeekPosition: number = 0;
  564. // 记忆播放seek兜底,避免一直转圈
  565. private initialSeekGuardTimer: number = 0;
  566. private readonly initialSeekGuardTimeoutMs: number = 2000;
  567. private readonly remoteMemorySeekInitialDelayMs: number = 120;
  568. private readonly remoteMemorySeekRetryIntervalMs: number = 80;
  569. private readonly remoteMemorySeekMaxRetryCount: number = 6;
  570. //瀑布流的列数横竖屏动态切换
  571. onIsLandscapeChange() {
  572. if(this.isLandscape){
  573. this.columns = 4
  574. }else{
  575. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  576. }
  577. }
  578. onColorModeChange() {
  579. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  580. }
  581. //点击某个歌单id发生变化的时候回调
  582. onIDChange(){
  583. console.log('onecold 歌单id发生变化this.currentSongListID='+this.currentSongListID)
  584. console.log('onecold 歌单id发生变化this.currentSongListName='+this.currentSongListName)
  585. if(this.modeType==4){
  586. this.titleName = this.currentSongListName
  587. this.rightTopImage = $r('sys.symbol.sort')
  588. //获取缓存
  589. const cacheSongs:string =PreferencesUtil.getStringSync(this.currentSongListID+'currentSongList', '')
  590. console.log('onecold 歌单id发生变化获取缓存2 cacheSongs = '+cacheSongs)
  591. if(StrUtil.isNotEmpty(cacheSongs)){
  592. this.currentSongList = JSON.parse(cacheSongs) as VideoItem[]
  593. this.updateListData(this.currentSongList, true)
  594. }
  595. this.doSongListTask()//获取歌单信息
  596. }
  597. }
  598. async doSongListTask() {
  599. // 初始化歌单数据库
  600. const playlistTable = new PlaylistTable(this.context);
  601. // 查询歌单中的所有歌曲
  602. const playlistSongs: PlaylistSong[] = await playlistTable.queryPlaylistSongs(this.currentSongListID);
  603. console.log('onecold 歌单id发生变化获取缓存7 playlistSongs='+playlistSongs.length)
  604. if (ArrayUtil.isEmpty(playlistSongs)) {
  605. this.updateListData([], true)
  606. // 清空歌单路径列表
  607. this.currentPlaylistSongFilePaths = [];
  608. } else {
  609. this.currentSongList = await convertPlaylistSongsToVideoItems(this.context, playlistSongs);
  610. console.log('onecold 从数据库读取的歌曲为 playlistSongs='+this.currentSongList.length)
  611. this.updateListData(this.currentSongList, true)
  612. // 保存歌单的歌曲路径列表,用于随机播放
  613. this.currentPlaylistSongFilePaths = playlistSongs.map(song => song.songFilePath);
  614. Logger.info('heanup doSongListTask', `保存歌单歌曲路径列表,歌单ID=${this.currentSongListID}, 数量=${this.currentPlaylistSongFilePaths.length}`);
  615. if (ArrayUtil.isNotEmpty(this.currentSongList)&&this.currentSongList.length > 100) {
  616. // 只保存前100条记录到缓存中
  617. let canceList = this.currentSongList.slice(0, 100);
  618. PreferencesUtil.putSync(this.currentSongListID+'currentSongList',
  619. JSON.stringify(canceList))
  620. } else {
  621. PreferencesUtil.putSync(this.currentSongListID+'currentSongList', JSON.stringify(this.currentSongList));
  622. }
  623. }
  624. this.isRefreshing = false
  625. }
  626. async onModeChange(preserveList: boolean = false): Promise<void> {
  627. this.isFavMusic = false
  628. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  629. this.refreshDirVisibilitySettings()
  630. if (this.mediaLibraryWarmupPrefetchTimer) {
  631. clearTimeout(this.mediaLibraryWarmupPrefetchTimer)
  632. this.mediaLibraryWarmupPrefetchTimer = 0
  633. }
  634. Logger.info('heanup LocalMusic', `onModeChange: 切换模式 modeType=${this.modeType}`);
  635. switch (this.modeType) {
  636. case 0:
  637. // 首页模式已在 resetAndLoadFirstPage 中处理
  638. // 切换模式时加载对应的排序类型
  639. this.titleName = Utility.resourceToString(this.context,$r('app.string.home'))
  640. this.sortType = this.loadSortTypeForCurrentMode()
  641. this.mediaLibraryEnterTs = 0
  642. break
  643. case 1:
  644. this.rightTopImage = $r('sys.symbol.sort')
  645. this.titleName = Utility.resourceToString(this.context,$r('app.string.media_ku'))
  646. // 切换模式时加载对应的排序类型
  647. this.sortType = this.loadSortTypeForCurrentMode()
  648. this.mediaLibraryEnterTs = Date.now()
  649. break
  650. case 2:
  651. this.rightTopImage = $r('sys.symbol.sort')
  652. this.titleName = Utility.resourceToString(this.context,$r('app.string.artist'))
  653. // 切换到艺术家模式时,加载艺术家模式的排序类型(默认按数量降序)
  654. this.sortType = this.loadSortTypeForCurrentMode()
  655. this.mediaLibraryEnterTs = 0
  656. break
  657. case 3:
  658. this.rightTopImage = $r('sys.symbol.sort')
  659. this.titleName = Utility.resourceToString(this.context,$r('app.string.album'))
  660. // 切换到专辑模式时,加载专辑模式的排序类型(默认按数量降序)
  661. this.sortType = this.loadSortTypeForCurrentMode()
  662. this.mediaLibraryEnterTs = 0
  663. break
  664. }
  665. // 模式切换时重置分页状态并加载第一页
  666. await this.resetAndLoadFirstPage(!preserveList);
  667. Logger.info('heanup onModeChange', `doSortType: 切换排序方式 sortType=${this.sortType}, mode=${this.modeType}`);
  668. }
  669. // @Consume currentSong: VideoItem | undefined;
  670. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  671. // @StorageLink('isPlay') isPlay: boolean = false;
  672. @Consume isShowPlay: boolean ;
  673. @StorageLink('songList') songList: Array<VideoItem> = [];
  674. @State translateY: number = 0;
  675. @State isShowSheet: boolean = false;
  676. @State isShowSheetView: boolean = false;
  677. @State isShowLyricCopySheet: boolean = false;
  678. @State lyricCopyLines: string[] = [];
  679. @State lyricSelectedIndexes: number[] = [];
  680. @State isShowTimeCloseView: boolean = false;
  681. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  682. @StorageLink('currIndex') curIndex: number = 0;
  683. @Consume isShowDrawer: boolean;
  684. @Consume offsetX: number;
  685. @State isFac: boolean = false;
  686. @State favList: Array<VideoItem> = []
  687. @Consume isFavMusic: boolean
  688. @State isClickedPLayAll: boolean = false;
  689. private scrollerForlist: ListScroller = new ListScroller();
  690. private knockController: KnockController | undefined = undefined;
  691. // 修改为:
  692. imagesF: ImageFrameInfo[] = CommonConstants.IMAGE_FRAME_INFO;
  693. @StorageProp('animationState') animationState: AnimationStatus = AnimationStatus.Initial
  694. // 缓存机制
  695. private cache: Map<string, Array<VideoItem>> = new Map();
  696. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  697. // 持久化缓存
  698. private async saveCacheToStorage() {
  699. const cacheArray = Array.from(this.cache.entries());
  700. const stringCacheArray = Array.from(this.stringCache.entries());
  701. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  702. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  703. }
  704. // 载入缓存
  705. private async loadCacheFromStorage() {
  706. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  707. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  708. if (cacheString) {
  709. const parsedCache: Object | null = JSON.parse(cacheString);
  710. if (parsedCache && Array.isArray(parsedCache)) {
  711. const cacheArray: [string, Array<VideoItem>][] = parsedCache;
  712. this.cache = new Map(cacheArray);
  713. }
  714. }
  715. if (stringCacheString) {
  716. const parsedStringCache: Object | null = JSON.parse(stringCacheString);
  717. if (parsedStringCache && Array.isArray(parsedStringCache)) {
  718. const stringCacheArray: [string, string][] = parsedStringCache;
  719. this.stringCache = new Map(stringCacheArray);
  720. }
  721. }
  722. }
  723. // 查找缓存
  724. private findCache(key: string): Array<VideoItem> | undefined {
  725. return this.cache.get(key);
  726. }
  727. // 查找字符串缓存
  728. private findStringCache(key: string): string | undefined {
  729. return this.stringCache.get(key);
  730. }
  731. // 添加缓存
  732. private addCache(key: string, value: Array<VideoItem>) {
  733. this.cache.set(key, value);
  734. }
  735. // 添加字符串缓存
  736. private addStringCache(key: string, value: string) {
  737. this.stringCache.set(key, value);
  738. }
  739. // 删除缓存
  740. private deleteCache(key: string) {
  741. this.cache.delete(key);
  742. this.saveCacheToStorage()
  743. }
  744. // 删除字符串缓存
  745. private deleteStringCache(key: string) {
  746. this.stringCache.delete(key);
  747. }
  748. // 多选机制
  749. @State selectedFiles: Array<VideoItem> = [];
  750. @Consume isMultiSelect: boolean;
  751. @State isAllSelected: boolean = false;
  752. @State appName: string = ''
  753. @State isHasDir: boolean = false
  754. @State packName: string = ''
  755. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  756. doSwipBack() {
  757. if(this.isSearchMode){
  758. console.info('onecold doSwipBack = ' +this.isSearchMode)
  759. this.isSearchMode = false
  760. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  761. this.searchText = ''
  762. this.getSortedFiles(this.currentPath)
  763. return
  764. }
  765. this.onSearchInput('')
  766. return
  767. }
  768. this.isZero = false
  769. if (this.modeType !== 0 && this.isCanBack) {
  770. if (this.detailBackTransitioning) {
  771. return
  772. }
  773. this.detailBackTransitioning = true
  774. // 先设置 isCanBack=false,确保 onModeChange 读取的是列表页的排序设置
  775. this.isCanBack = false
  776. this.rightTopImage = $r('sys.symbol.sort')
  777. if (this.modeType == 2) {
  778. this.titleName = Utility.resourceToString(this.context,$r('app.string.artist'))
  779. if (ArrayUtil.isNotEmpty(this.artistList)) {
  780. this.updateListData(this.artistList, true, true)
  781. }
  782. } else if (this.modeType == 3) {
  783. this.titleName = Utility.resourceToString(this.context,$r('app.string.album'))
  784. if (ArrayUtil.isNotEmpty(this.albumList)) {
  785. this.updateListData(this.albumList, true, true)
  786. }
  787. }
  788. // 返回列表页时保留当前列表,避免先清空导致闪现
  789. void this.onModeChange(true).then(() => {
  790. if (this.modeType == 2) {
  791. if (this.isGridMusic||this.twoFingerType==4) {
  792. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  793. let lastWaterOffset = this.mScrollMap.get('lastWaterArtistScrollOffset') ?? 0
  794. if(this.twoFingerType==4){
  795. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  796. }else{
  797. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  798. }
  799. } else {
  800. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  801. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  802. }
  803. } else if (this.modeType == 3) {
  804. if (this.isGridMusic||this.twoFingerType==4) {
  805. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  806. let lastWaterOffset = this.mScrollMap.get('lastWaterAlBumScrollOffset') ?? 0
  807. if(this.twoFingerType==4){
  808. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  809. }else{
  810. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  811. }
  812. } else {
  813. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  814. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  815. }
  816. }
  817. this.detailBackTransitioning = false
  818. }).catch((error: Error) => {
  819. Logger.error('heanup LocalMusic', `doSwipBack onModeChange error: ${error.message}`)
  820. this.detailBackTransitioning = false
  821. })
  822. return
  823. }
  824. this.mediaLibraryEnterTs = 0
  825. if (this.isHistory || this.isFavMusic) {
  826. this.isHistory = false
  827. this.getSortedFiles(this.currentPath)
  828. return
  829. }
  830. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  831. animateTo({ duration: 555 }, () => {
  832. // 动画闭包内控制Image组件的出现和消失
  833. this.isShowDrawer = !this.isShowDrawer
  834. this.offsetX = 0
  835. })
  836. return
  837. }
  838. //返回上一级歌单的滚动位置
  839. setTimeout(() => {
  840. if (this.modeType == 0) {
  841. if (this.isGridMusic||this.twoFingerType==4) {
  842. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  843. let lastWaterOffset = this.mScrollMap.get('lastWaterDirScrollOffset') ?? 0
  844. if(this.twoFingerType==4){
  845. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  846. }else{
  847. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  848. }
  849. } else {
  850. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  851. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  852. }
  853. }
  854. }, 100)
  855. this.currentPath = Utility.getParentDirectory(this.currentPath)
  856. Logger.info('this.currentPath2 = ' + this.currentPath)
  857. this.getSortedFiles(this.currentPath, false, undefined, undefined, undefined, true)
  858. }
  859. private triggerSwipeBackWithAnimation(): void {
  860. animateTo({ duration: 555 }, () => {
  861. this.doSwipBack()
  862. })
  863. }
  864. // 组件生命周期
  865. aboutToAppear() {
  866. console.info('onecold aboutToAppear sdkApiVersion = '+deviceInfo.sdkApiVersion)
  867. if(ArrayUtil.isNotEmpty(this.videoLocalList)&&this.modeType==0){
  868. this.updateListData(this.videoLocalList)
  869. }
  870. // 初始化 PlaylistTable
  871. this.playlistTable = new PlaylistTable(getContext(this))
  872. this.sonTwoFingerType = PreferencesUtil.getNumberSync('sonTwoFingerType', 3);
  873. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  874. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  875. this.tipPopup = !this.tipPopup
  876. PreferencesUtil.putSync('isFirstTiped',false)
  877. }
  878. this.initSetting()
  879. this.syncEqualizerUi();
  880. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  881. Utility.getAppName(getContext(this)).then((appName: string) => {
  882. this.appName = appName
  883. })
  884. this.packName = AppUtil.getBundleName()
  885. this.tabSelectedIndexes[0] = this.modeType//SegmentButton的索引
  886. this.loadCacheFromStorage(); // 加载文件夹缓存
  887. // 在首页初始化时读取媒体库,艺术家,专辑等缓存数据
  888. this.initLoadCache()
  889. this.mkDownLoadDir()
  890. let eventMusic: emitter.InnerEvent = { eventId: EventConstants.EVENT_AUDIO_OPEN }
  891. // 监听广播事件(打开其他应用处理)
  892. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  893. this.saveVideoDatas([eventData.data?.message], true)
  894. });
  895. //侧滑广播接收时间
  896. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_UPDATE }
  897. // 监听广播事件(手势返回处理)
  898. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  899. this.triggerSwipeBackWithAnimation()
  900. });
  901. //ScanFilePage广播接收时间
  902. let eventScanUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_SCAN_UPDATE }
  903. // 监听ScanFilePage广播事件(更新数据库)
  904. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  905. this.doUpdateData()
  906. });
  907. let eventEqualizerChanged: emitter.InnerEvent = { eventId: EventConstants.EVENT_EQUALIZER_CHANGED }
  908. emitter.on(eventEqualizerChanged, () => {
  909. this.syncEqualizerUi();
  910. if (this.mIjkMediaPlayer) {
  911. const equalizerManager = EqualizerManager.getInstance();
  912. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  913. this.markEqualizerApplied();
  914. }
  915. });
  916. // 监听歌单播放请求事件
  917. let eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY }
  918. emitter.on(eventPlaylistPlay, async (eventData: emitter.EventData) => {
  919. const data = eventData.data as Record<string, Object>
  920. if (!data) {
  921. Logger.error('heanup eventPlaylistPlay: eventData.data is undefined or null')
  922. return
  923. }
  924. // 检查歌单播放数据结构
  925. if (data.playlistId && data.songFilePaths && data.startIndex !== undefined) {
  926. const playlistData: PlaylistEventData = {
  927. playlistId: data.playlistId as string,
  928. playlistName: data.playlistName as string,
  929. songCount: data.songCount as number,
  930. startIndex: data.startIndex as number,
  931. isJump: data.isJump as boolean,
  932. songFilePaths: data.songFilePaths as string[]
  933. }
  934. await this.handlePlaylistPlayRequest(
  935. playlistData.playlistId,
  936. playlistData.playlistName,
  937. playlistData.songFilePaths,
  938. playlistData.startIndex,
  939. playlistData.isJump,
  940. playlistData.songCount
  941. )
  942. return
  943. }
  944. Logger.error('heanup eventPlaylistPlay: 接收到无效的数据结构')
  945. });
  946. let eventRefreshSort: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_REFRESH_SORT }
  947. // 监听广播事件(通用设置配置更新)
  948. emitter.on(eventRefreshSort, (eventData: emitter.EventData) => {
  949. if(this.modeType ==4){
  950. this.doSongListTask()//获取歌单信息
  951. }
  952. });
  953. let eventQueueRefresh: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAY_QUEUE_REFRESH }
  954. emitter.on(eventQueueRefresh, () => {
  955. this.syncWebdavQueueWithoutRestart();
  956. });
  957. let eventSetting: emitter.InnerEvent = { eventId: EventConstants.EVENT_SETTING_UPDATE }
  958. // 监听广播事件(通用设置配置更新)
  959. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  960. this.initSetting()
  961. });
  962. // 监听 WebDAV 元数据更新事件
  963. let eventWebDavMetadata: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED }
  964. emitter.on(eventWebDavMetadata, (eventData: emitter.EventData) => {
  965. const payloads = eventData?.data as WebDavMetadataUpdatePayload[] | undefined;
  966. if (!payloads || payloads.length === 0) {
  967. Logger.info(TAG, 'LocalMusic: WebDav metadata event received but payload empty');
  968. return;
  969. }
  970. Logger.info(TAG, `LocalMusic: WebDav metadata event payload count: ${payloads.length}`);
  971. // 处理每个元数据更新
  972. for (let i = 0; i < payloads.length; i++) {
  973. const payload = payloads[i];
  974. if (!payload || !payload.filePath) {
  975. continue;
  976. }
  977. // 重要:只更新当前正在播放的歌曲
  978. // 如果 filePath 不匹配,说明是其他歌曲的元数据更新,忽略不做处理
  979. if (this.currentSong && this.currentSong.filePath === payload.filePath) {
  980. Logger.info(TAG, `LocalMusic: 更新当前播放歌曲的元数据: ${payload.filePath}`);
  981. if (payload.name && payload.name.length > 0) {
  982. this.name = payload.name;
  983. if (this.currentSong) {
  984. this.currentSong.name = payload.name;
  985. }
  986. }
  987. if (payload.artist && payload.artist.length > 0) {
  988. this.artist = payload.artist;
  989. if (this.currentSong) {
  990. this.currentSong.artist = payload.artist;
  991. }
  992. }
  993. if (payload.pixelMapPath && payload.pixelMapPath.length > 0) {
  994. this.cover = payload.pixelMapPath;
  995. if (this.currentSong) {
  996. this.currentSong.pixelMapPath = payload.pixelMapPath;
  997. }
  998. Logger.info(TAG, `LocalMusic: 封面已更新: ${payload.pixelMapPath}`);
  999. }
  1000. // 同步更新 AppStorage
  1001. AppStorage.setOrCreate('currentSong', this.currentSong);
  1002. } else {
  1003. Logger.info(TAG, `LocalMusic: 跳过非当前播放歌曲的元数据更新: ${payload.filePath}, 当前: ${this.currentSong?.filePath}`);
  1004. }
  1005. }
  1006. });
  1007. // 监听广播事件(通用设置配置更新)
  1008. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  1009. this.doChangeSetting()
  1010. });
  1011. let event: Callback<InterruptEvent> = (event) => {
  1012. // LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  1013. console.info(`heanup onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`)
  1014. this.savePlaybackPosition()
  1015. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  1016. this.pause();
  1017. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  1018. console.info(`heanup onecold audioInterrupt startPlayOrResumePlay: ${JSON.stringify(event)}`)
  1019. this.startPlayOrResumePlay();
  1020. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  1021. console.info(`heanup onecold 与其他应用音频冲突 被截断点 INTERRUPT_HINT_STOP`)
  1022. if(!this.isSameTimePlay){
  1023. this.stop();
  1024. }
  1025. }
  1026. }
  1027. this.mIjkMediaPlayer.on('audioInterrupt', event);
  1028. // 音频设备断连回调处理比如蓝牙耳机断开
  1029. let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  1030. console.info(`onecold Heanup deviceChange event: ${JSON.stringify(event)}`);
  1031. if (event.reason === DeviceChangeReason.REASON_NEW_DEVICE_AVAILABLE) { // 音频设备连接
  1032. } else if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  1033. console.info('heanup onecold 音频设备断开连接, 暂停播放')
  1034. this.pause();
  1035. }
  1036. }
  1037. // 订阅音频设备断开和连接事件
  1038. this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  1039. const eventPause: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAY_PAUSE }
  1040. // 监听广播事件(hicar断开暂停播放)
  1041. emitter.on(eventPause, (eventData: emitter.EventData) => {
  1042. console.info('heanup onecold hicar断开暂停播放, 暂停播放')
  1043. this.pause();
  1044. });
  1045. let audioManager = audio.getAudioManager(); // 需要先创建AudioManager实例。
  1046. let audioRoutingManager = audioManager.getRoutingManager(); // 再调用AudioManager的方法创建AudioRoutingManager实例。
  1047. // 监听蓝牙音响断开音频设备状态变化。
  1048. audioRoutingManager.on('deviceChange', audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (deviceChanged: audio.DeviceChangeAction) => {
  1049. console.info(`onecold device change type : ${deviceChanged.type}`); // 设备连接状态变化,0为连接,1为断开连接。
  1050. console.info(`onecold device descriptor size : ${deviceChanged.deviceDescriptors.length}`);
  1051. console.info(`onecold device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceRole}`); // 设备角色。
  1052. console.info(`onecold device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceType}`);
  1053. // 蓝牙设备类型为8
  1054. const isBluetooth = deviceChanged.deviceDescriptors[0].deviceType === 8;
  1055. if (isBluetooth) {
  1056. if (deviceChanged.type === 0) {
  1057. // 蓝牙连接
  1058. this.isBluetoothConnected = true;
  1059. console.info('onecold 蓝牙设备已连接');
  1060. } else if (deviceChanged.type === 1) {
  1061. // 蓝牙断开
  1062. this.isBluetoothConnected = false;
  1063. this.lastBluetoothLyricLine = '';
  1064. console.info('onecold 蓝牙设备已断开');
  1065. // 恢复原始元数据
  1066. if (this.currentSong) {
  1067. this.avSessionController.restoreOriginalMetadata(
  1068. this.currentSong.name || '',
  1069. this.currentSong.artist || ''
  1070. );
  1071. }
  1072. // 蓝牙断开暂停
  1073. if (this.bluetoothDisconnectPause && deviceChanged.deviceDescriptors[0].deviceRole === 2) {
  1074. console.info('heanup onecold 蓝牙音响断开, 暂停播放');
  1075. this.pause();
  1076. }
  1077. }
  1078. }
  1079. });
  1080. // 有线耳机断开和连接的监听。监听音频设备状态变化。
  1081. audioRoutingManager.on('deviceChange', audio.DeviceFlag.INPUT_DEVICES_FLAG, (deviceChanged: audio.DeviceChangeAction) => {
  1082. console.info('onecold device change type : ' + deviceChanged.type); // 设备连接状态变化,0为连接,1为断开连接。
  1083. // 设备类型 22是USB耳机,带麦克风,3是有线耳机。
  1084. if(deviceChanged.type==1&&
  1085. (deviceChanged.deviceDescriptors[0].deviceType== 22||
  1086. deviceChanged.deviceDescriptors[0].deviceType==3)){
  1087. console.info('heanup onecold 有线耳机断开, 暂停播放')
  1088. this.pause();
  1089. }
  1090. });
  1091. this.makeWorker()
  1092. //折叠屏的屏幕显示模式变化
  1093. display.on('foldDisplayModeChange', (data) => {
  1094. this.doChangeBarHeight()
  1095. });
  1096. display.on('foldStatusChange', (data) => {
  1097. Logger.info('onecold foldStatusChange ')
  1098. });
  1099. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  1100. // 读取 themeMode 并同步 currentColorMode
  1101. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  1102. this.applyThemeMode(this.themeMode)
  1103. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  1104. AppStorage.setOrCreate('themeColor', themeColor);
  1105. this.themeColor = themeColor;
  1106. this.doChangeSetting()
  1107. this.windowClass.on('windowSizeChange', (size: window.Size) => {
  1108. LogUtil.info('onecold windowSizeChange')
  1109. this.doChangeBarHeight()
  1110. let viewWidth = px2vp(size.width);
  1111. let viewHeight = px2vp(size.height);
  1112. if(this.isPhoneLan()){
  1113. this.is_auto_hide_progress = false
  1114. if(this.isHiCar()){
  1115. return
  1116. }
  1117. setTimeout(() => {
  1118. this.is_auto_hide_progress = true
  1119. }, 6000)
  1120. }else{
  1121. this.startAutoHide()
  1122. }
  1123. });
  1124. this.eventHub.on('onStateChange', (fg: boolean) => {
  1125. this.isAppForeground = fg;
  1126. if (fg && this.curState === 'STARTED') {
  1127. this.stopPip();
  1128. this.syncLyricPositionNow();
  1129. }
  1130. });
  1131. //NewIndex的博空调收到eventHub消息控制播放
  1132. this.getUIContext().getHostContext()!.eventHub.on('playOrPause', () => {
  1133. if (ArrayUtil.isNotEmpty(this.songList)) {
  1134. this.playOrPause();
  1135. } else {
  1136. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1137. }
  1138. });
  1139. this.getUIContext().getHostContext()!.eventHub.on('playPrevious', () => {
  1140. if (ArrayUtil.isNotEmpty(this.songList)) {
  1141. this.playPrevious();
  1142. } else {
  1143. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1144. }
  1145. });
  1146. this.getUIContext().getHostContext()!.eventHub.on('playNext', () => {
  1147. if (ArrayUtil.isNotEmpty(this.songList)) {
  1148. this.playNext();
  1149. } else {
  1150. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  1151. }
  1152. });
  1153. this.getUIContext().getHostContext()!.eventHub.on('showPlayerView', () => {
  1154. this.showPlayerView();
  1155. });
  1156. this.getUIContext().getHostContext()!.eventHub.on('openPlayList', () => {
  1157. this.openPlayList();
  1158. });
  1159. }
  1160. //载入媒体库,艺术家,专辑等缓存
  1161. initLoadCache(){
  1162. this.mediaKuCount = PreferencesUtil.getNumberSync('mediaKuCount', 0)
  1163. this.artistCount = PreferencesUtil.getNumberSync('artistCount', 0)
  1164. this.albumCount = PreferencesUtil.getNumberSync('albumCount', 0)
  1165. let cachedListStr:string = PreferencesUtil.getStringSync('mediaKuList', '[]');
  1166. let cachedList = JSON.parse(cachedListStr) as Array<VideoItem>;
  1167. if(ArrayUtil.isNotEmpty(cachedList)){
  1168. this.mediaKuList = cachedList
  1169. if(this.modeType==1){
  1170. this.updateListData(this.mediaKuList)
  1171. }
  1172. }
  1173. let artistListStr:string = PreferencesUtil.getStringSync('artistList', '[]');
  1174. let artistCachedList = JSON.parse(artistListStr) as Array<VideoItem>;
  1175. if(ArrayUtil.isNotEmpty(artistCachedList)){
  1176. this.artistList = artistCachedList
  1177. let artistMapStr:string = PreferencesUtil.getStringSync('artistMap', '[]');
  1178. const parsedArray = JSON.parse(artistMapStr) as [string, VideoItem[]][];
  1179. this.artistMap = new Map(parsedArray);
  1180. // this.artistMap = JSON.parse(artistMapStr) as Map<string, VideoItem[]>;
  1181. if(this.modeType==2){
  1182. this.updateListData(this.artistList)
  1183. }
  1184. }
  1185. let albumListStr:string = PreferencesUtil.getStringSync('albumList', '[]');
  1186. let albumCachedList = JSON.parse(albumListStr) as Array<VideoItem>;
  1187. if(ArrayUtil.isNotEmpty(albumCachedList)){
  1188. this.albumList = albumCachedList
  1189. let albumMapStr:string = PreferencesUtil.getStringSync('albumMap', '[]');
  1190. const parsedArray = JSON.parse(albumMapStr) as [string, VideoItem[]][];
  1191. this.albumMap = new Map(parsedArray);
  1192. if(this.modeType==3){
  1193. this.updateListData(this.albumList)
  1194. }
  1195. }
  1196. }
  1197. startAutoHide() {
  1198. if(this.isHiCar()){
  1199. return
  1200. }
  1201. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  1202. console.info('onecold startAutoHide')
  1203. this.is_auto_hide_progress = false
  1204. setTimeout(() => {
  1205. this.is_auto_hide_progress = true
  1206. }, 6000)
  1207. }
  1208. }
  1209. applyThemeMode(mode: number) {
  1210. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  1211. if (mode === 1) {
  1212. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  1213. } else if (mode === 2) {
  1214. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1215. }
  1216. AppStorage.setOrCreate('currentColorMode', colorMode)
  1217. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  1218. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  1219. AppStorage.setOrCreate('themeMode', mode)
  1220. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1221. // 只有强制浅色/深色时才主动设置
  1222. const context = getContext(this) as common.UIAbilityContext
  1223. context.getApplicationContext().setColorMode(colorMode)
  1224. }
  1225. initSetting() {
  1226. this.isGeKongPlayNext = PreferencesUtil.getBooleanSync('isGeKongPlayNext', false)
  1227. this.bluetoothDisconnectPause = PreferencesUtil.getBooleanSync(SettingPage.BLUETOOTH_DISCONNECT_PAUSE, false)
  1228. this.bluetoothLyricEnabled = PreferencesUtil.getBooleanSync(SettingPage.BLUETOOTH_LYRIC_ENABLED, false)
  1229. this.bluetoothLyricMode = PreferencesUtil.getNumberSync(SettingPage.BLUETOOTH_LYRIC_MODE, 0)
  1230. this.isShowSpectrum = PreferencesUtil.getBooleanSync('isShowSpectrum', true)
  1231. this.spectrumModeIndex = PreferencesUtil.getNumberSync('spectrumModeIndex', 0)
  1232. this.enablePointLight = PreferencesUtil.getBooleanSync('enablePointLight', true)
  1233. AppStorage.setOrCreate('EnablePointLight', this.enablePointLight);
  1234. this.showSimple = PreferencesUtil.getBooleanSync('showSimple', true)
  1235. this.showFindLocation = PreferencesUtil.getBooleanSync('showFindLocation', true)
  1236. this.showZMIndex = PreferencesUtil.getBooleanSync('showZMIndex', false)
  1237. this.autoHideTitle = PreferencesUtil.getBooleanSync('autoHideTitle', true)
  1238. this.isShowPrecious = PreferencesUtil.getBooleanSync('isShowPrecious', false)
  1239. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1240. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  1241. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  1242. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, false)
  1243. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  1244. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  1245. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  1246. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  1247. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  1248. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  1249. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  1250. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  1251. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  1252. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 2)
  1253. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  1254. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  1255. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  1256. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  1257. this.isEnableWordByWordLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_ENABLE_WORD_BY_WORD_LYRIC, true)
  1258. this.syncWordByWordLyricMode()
  1259. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  1260. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  1261. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  1262. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  1263. const volumeBoostPercent = PreferencesUtil.getNumberSync(this.volumeBoostPreferenceKey, 0)
  1264. this.volumeBoostPercent = Math.max(0, Math.min(volumeBoostPercent, this.volumeBoostMaxPercent))
  1265. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  1266. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  1267. this.isPlayPageSwipeNext = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYPAGE_SWIPE_NEXT, true)
  1268. this.volumeSmall = PreferencesUtil.getBooleanSync('volumeSmall', false)
  1269. this.autoParseMusicName = PreferencesUtil.getBooleanSync('autoParseMusicName', true)
  1270. this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
  1271. this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
  1272. this.refreshDirVisibilitySettings()
  1273. this.fastForwardSeconds = PreferencesUtil.getStringSync('fastForwardSeconds', '10')
  1274. this.isShowBackFast = PreferencesUtil.getBooleanSync('isShowBackFast', false)
  1275. this.isCopyFileToDownLoad = PreferencesUtil.getBooleanSync(SettingPage.IS_COPYFILE_TO_DOWNLOAD, false)
  1276. let audioManager = audio.getAudioManager();
  1277. let audioSessionManager: audio.AudioSessionManager = audioManager.getSessionManager();
  1278. if(this.isSameTimePlay){
  1279. //与其他应用同时播放,关键代码
  1280. let strategy: audio.AudioSessionStrategy = {
  1281. concurrencyMode: audio.AudioConcurrencyMode.CONCURRENCY_MIX_WITH_OTHERS
  1282. };
  1283. audioSessionManager.activateAudioSession(strategy).then(() => {
  1284. console.info('onecold Succeeded in doing activateAudioSession.');
  1285. }).catch((err: BusinessError) => {
  1286. console.error(`Failed to activateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1287. });
  1288. }else{
  1289. let isActivated = audioSessionManager.isAudioSessionActivated();
  1290. if(isActivated){
  1291. audioSessionManager.deactivateAudioSession().then(() => {
  1292. console.info('Succeeded in doing deactivateAudioSession.');
  1293. }).catch((err: BusinessError) => {
  1294. console.error(`Failed to deactivateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1295. });
  1296. }
  1297. }
  1298. //如果是hicar连接状态,这些都是false
  1299. if(this.isHiCar()){
  1300. this.autoHideTitle = false
  1301. this.isCoverRectangle= true
  1302. this.columns=4
  1303. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  1304. {
  1305. this.isGridMusic= false//用list不用网格
  1306. this.isCoverTopBig = false
  1307. }
  1308. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  1309. }
  1310. if (this.isSavePlayMode) {
  1311. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  1312. }
  1313. }
  1314. doChangeSetting() {
  1315. this.initSetting()
  1316. this.deleteCache(this.currentPath)
  1317. if (this.modeType === 0) {
  1318. this.getSortedFiles(this.currentPath)
  1319. }
  1320. }
  1321. doChangeBarHeight() {
  1322. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  1323. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  1324. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  1325. this.setBarHeightNormal()
  1326. }
  1327. }
  1328. onPageShow() {
  1329. this.knockController?.immersiveListening();
  1330. app.setImageCacheCount(100);
  1331. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  1332. app.setImageRawDataCacheSize(104857600);
  1333. this.refreshDirVisibilitySettings();
  1334. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  1335. }
  1336. //开启线程查看各个数据库
  1337. makeWorker() {
  1338. setTimeout(() => {
  1339. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  1340. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  1341. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  1342. // workerInstance.postMessage({
  1343. // code: 1,
  1344. // data1: this.context,
  1345. // data2: this.rootPath,
  1346. // data3: this.lockPath,
  1347. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  1348. // data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  1349. // });
  1350. PreferencesUtil.putSync('isFirstApp', false)
  1351. } else {
  1352. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1353. workerInstance.postMessage({ code: 3, data: this.context });
  1354. workerInstance.postMessage({ code: 4, data: this.context });
  1355. this.getHistoryList(false)
  1356. }
  1357. }, 1000)
  1358. workerInstance.onmessage = (e: MessageEvents): void => {
  1359. const message = e.data as LocalMusicWorkerMessage;
  1360. switch (message.code) {
  1361. case 101: //第一次扫描文件夹入库
  1362. ToastUtil.showToast('刷新同步数据库成功!')
  1363. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  1364. this.doAllUpdateData()
  1365. break;
  1366. case 102: //查询媒体库列表
  1367. this.isRefreshing = false
  1368. this.mediaKuList = message.data // 只包含前100条
  1369. const mediaTotalCount: number = message.totalCount ?? this.mediaKuList.length;
  1370. this.mediaKuCount = mediaTotalCount;
  1371. Logger.info(`heanup 查询媒体库列表 缓存数=${this.mediaKuList.length}, 总数=${mediaTotalCount}`)
  1372. Utility.doSortListAscending(this.mediaKuList)
  1373. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  1374. // 媒体库模式下重新加载第一页(分页查询)
  1375. if (this.modeType === 1) {
  1376. this.resetAndLoadFirstPage();
  1377. }
  1378. PreferencesUtil.putSync('mediaKuCount', mediaTotalCount)
  1379. // 只保存前100条记录到缓存中
  1380. PreferencesUtil.putSync('mediaKuList', JSON.stringify(this.mediaKuList));
  1381. break;
  1382. case 103: //收到查询艺术家列表
  1383. this.isRefreshing = false
  1384. this.artistMap = message.data1; // 只包含前60个艺术家的歌曲
  1385. this.artistList = message.data2; // 只包含前100个艺术家
  1386. const artistTotalCount: number = message.totalCount ?? this.artistList.length;
  1387. this.artistCount = artistTotalCount;
  1388. const nextArtistCountMap = new Map(this.artistSongCountMap);
  1389. this.artistMap.forEach((songs, artist) => {
  1390. nextArtistCountMap.set(artist, songs.length);
  1391. });
  1392. this.artistSongCountMap = nextArtistCountMap;
  1393. Logger.info(`heanup 查询艺术家列表 缓存数=${this.artistList.length}, 总数=${artistTotalCount}`)
  1394. PreferencesUtil.putSync('artistCount', artistTotalCount)
  1395. // 艺术家模式下重新加载第一页(分页查询)
  1396. if (this.modeType === 2) {
  1397. this.resetAndLoadFirstPage();
  1398. }
  1399. // 保存前100条艺术家列表
  1400. PreferencesUtil.putSync('artistList', JSON.stringify(this.artistList));
  1401. // 保存前60条艺术家的歌曲Map
  1402. const sortedEntries = Array.from(this.artistMap.entries());
  1403. PreferencesUtil.putSync('artistMap', JSON.stringify(sortedEntries));
  1404. break;
  1405. case 104: //收到查询专辑列表
  1406. this.isRefreshing = false
  1407. this.albumMap = message.data1;
  1408. this.albumList = message.data2
  1409. const albumTotalCount: number = message.totalCount ?? this.albumList.length;
  1410. this.albumCount = albumTotalCount;
  1411. const nextAlbumCountMap = new Map(this.albumSongCountMap);
  1412. this.albumMap.forEach((songs, album) => {
  1413. nextAlbumCountMap.set(album, songs.length);
  1414. });
  1415. this.albumSongCountMap = nextAlbumCountMap;
  1416. Logger.info(`heanup 查询专辑列表 缓存数=${this.albumList.length}, 总数=${albumTotalCount}`)
  1417. // 专辑模式下重新加载第一页(分页查询)
  1418. if (this.modeType === 3) {
  1419. this.resetAndLoadFirstPage();
  1420. }
  1421. //查询完毕在启动是否自动播放
  1422. if (this.isStartAutoPlay&&this.isCanAuto) {
  1423. this.isCanAuto = false
  1424. console.info('onecold startPlayOrResumePlay 757')
  1425. this.startPlayOrResumePlay()
  1426. }
  1427. PreferencesUtil.putSync('albumCount', albumTotalCount)
  1428. // 保存前100条专辑列表(Worker已经只发送了100条)
  1429. PreferencesUtil.putSync('albumList', JSON.stringify(this.albumList));
  1430. // 保存前60条专辑Map(Worker已经只发送了60条)
  1431. const mapArrayAlbum = Array.from(this.albumMap.entries());
  1432. PreferencesUtil.putSync('albumMap', JSON.stringify(mapArrayAlbum));
  1433. break;
  1434. case 105: // 缓存完成后返回的元数据
  1435. this.handleWorkerMetadataPayload(message.data);
  1436. break;
  1437. case 106: // 编辑音乐元数据和封面完成
  1438. this.handleEditMusicResult(message.data);
  1439. break;
  1440. }
  1441. };
  1442. // 在调用terminate后,执行onexit
  1443. workerInstance.onexit = (code) => {
  1444. metadataExtractionInFlight.clear();
  1445. Logger.info(TAG, 'workerInstance 线程已退出,code: ' + code);
  1446. }
  1447. workerInstance.onerror = (err: ErrorEvent) => {
  1448. metadataExtractionInFlight.clear();
  1449. console.error('workerInstance 线程执行发生异常: ' + err.message)
  1450. }
  1451. }
  1452. private handleWorkerMetadataPayload(payload: WorkerMetadataPayload | undefined): void {
  1453. if (!payload || !payload.originFilePath) {
  1454. return;
  1455. }
  1456. metadataExtractionInFlight.delete(payload.originFilePath);
  1457. if (payload.error) {
  1458. Logger.warn(TAG, `缓存文件元数据解析失败: ${payload.error}`);
  1459. return;
  1460. }
  1461. this.applyMetadataToCollections(payload.originFilePath, payload);
  1462. }
  1463. private applyMetadataToCollections(filePath: string, payload: WorkerMetadataPayload): void {
  1464. const targets: Array<VideoItem> = [];
  1465. let mainListUpdated = false;
  1466. let playlistUpdated = false;
  1467. if (this.currentSong && this.currentSong.filePath === filePath) {
  1468. targets.push(this.currentSong);
  1469. }
  1470. const collectFromList = (list?: Array<VideoItem>, markUpdated?: () => void) => {
  1471. if (!list || list.length === 0) {
  1472. return;
  1473. }
  1474. const found = Utility.getItemByFilePath(list, filePath);
  1475. if (found) {
  1476. markUpdated?.();
  1477. targets.push(found);
  1478. }
  1479. };
  1480. collectFromList(this.videoLocalList, () => {
  1481. mainListUpdated = true;
  1482. });
  1483. collectFromList(this.songList, () => {
  1484. playlistUpdated = true;
  1485. });
  1486. collectFromList(this.historyList);
  1487. collectFromList(this.favList);
  1488. const remoteManager = RemoteDriveManager.getInstance();
  1489. collectFromList(remoteManager.webDavSongs);
  1490. const updated = new Set<VideoItem>();
  1491. const remoteMetadataUpdates: Map<string, WebDavMetadataUpdatePayload> = new Map();
  1492. for (let i = 0; i < targets.length; i++) {
  1493. const target = targets[i];
  1494. if (!target || updated.has(target)) {
  1495. continue;
  1496. }
  1497. updated.add(target);
  1498. this.mergeVideoItemWithPayload(target, payload);
  1499. if (isRemoteCloudType(target.type) && StrUtil.isNotEmpty(target.filePath)) {
  1500. remoteMetadataUpdates.set(target.filePath, {
  1501. filePath: target.filePath,
  1502. pixelMapPath: target.pixelMapPath,
  1503. name: target.name,
  1504. artist: target.artist
  1505. });
  1506. }
  1507. }
  1508. if (this.currentSong && this.currentSong.filePath === filePath) {
  1509. this.mergeVideoItemWithPayload(this.currentSong, payload);
  1510. if (payload.name) {
  1511. this.name = payload.name;
  1512. }
  1513. if (payload.artist) {
  1514. this.artist = payload.artist;
  1515. }
  1516. if (payload.pixelMapPath) {
  1517. this.cover = payload.pixelMapPath;
  1518. }
  1519. if (payload.lyricContent) {
  1520. this.applyInlineLyricContent(payload.lyricContent);
  1521. }
  1522. let avSessionDurationMs: number = this.duration;
  1523. if (payload.duration) {
  1524. const durationSeconds = Number(payload.duration);
  1525. if (!Number.isNaN(durationSeconds) && durationSeconds > 0) {
  1526. avSessionDurationMs = durationSeconds * 1000;
  1527. this.duration = avSessionDurationMs;
  1528. this.durationTime = Math.floor(avSessionDurationMs / 1000);
  1529. this.durationStringTime = secondToTime(this.durationTime);
  1530. }
  1531. }
  1532. if (avSessionDurationMs > 0) {
  1533. this.avSessionController.setAVMetadataMusic(this.currentSong, avSessionDurationMs, this.lyricContent);
  1534. }
  1535. this.currentSong = cloneVideoItem(this.currentSong);
  1536. AppStorage.setOrCreate('currentSong', this.currentSong);
  1537. }
  1538. const primaryTarget = targets.length > 0 ? targets[0] : undefined;
  1539. if (primaryTarget) {
  1540. this.persistRemoteMetadataToDb(primaryTarget).catch((error: Error) => {
  1541. Logger.error(TAG, `缓存元数据持久化失败: ${error.message}`);
  1542. });
  1543. }
  1544. if (remoteMetadataUpdates.size > 0) {
  1545. const eventUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
  1546. emitter.emit(eventUpdate, { data: Array.from(remoteMetadataUpdates.values()) });
  1547. }
  1548. this.refreshLazyListViews(mainListUpdated, playlistUpdated);
  1549. }
  1550. private handleEditMusicResult(result: WorkerEditMusicResult): void {
  1551. // 关闭进度条
  1552. DialogHelper.closeDialog(this.loadingDialogId)
  1553. if (result.success) {
  1554. console.log("heanup 编辑信息成功,数据库已同步");
  1555. if (result.coverResult) {
  1556. ToastUtil.showToast('内嵌封面成功');
  1557. }
  1558. ToastUtil.showToast('内嵌音乐标签成功');
  1559. this.isShowMoreView = false;
  1560. this.name = this.titleStr;
  1561. // 同步当前播放的歌曲信息
  1562. if (this.editingItem && this.currentSong && this.editingItem.filePath == this.currentSong.filePath) {
  1563. this.currentSong.name = this.titleStr;
  1564. this.artist = this.artistStr;
  1565. this.currentSong.artist = this.artistStr;
  1566. this.currentSong.album = this.ablumStr;
  1567. this.currentSong.year = this.yearStr;
  1568. this.currentSong.genre = this.genreStr;
  1569. this.currentSong.track = this.trackStr;
  1570. this.currentSong.lyricContent = this.lyricConStr;
  1571. this.currentSong.ALBUMARTIST = this.albumArtistStr;
  1572. this.currentSong.COMPOSER = this.composerStr;
  1573. this.currentSong.LYRICIST = this.lyricistStr;
  1574. this.currentSong.COMMENT = this.commentStr;
  1575. }
  1576. // if (result.needRefreshList && this.modeType == 0) {
  1577. // this.deleteCache(this.currentPath);
  1578. // this.getSortedFiles(this.currentPath);
  1579. // }
  1580. // 同步编辑字段到本地列表
  1581. if (this.editingItem) {
  1582. this.syncEditedFields(this.editingItem);
  1583. this.syncListsAfterEdit(this.editingItem.filePath);
  1584. this.doUpateEditedFields(this.editingItem);
  1585. }
  1586. // 清理临时变量
  1587. this.longItemFilePath = '';
  1588. this.tempLyricContent = '';
  1589. this.isShowEdit = false;
  1590. this.imagePathStr = '';
  1591. } else {
  1592. console.error("heanup 编辑信息失败: " + result.error);
  1593. ToastUtil.showToast('编辑失败: ' + (result.error || '未知错误'));
  1594. // 清理临时变量
  1595. this.longItemFilePath = '';
  1596. this.tempLyricContent = '';
  1597. this.isShowEdit = false;
  1598. this.imagePathStr = '';
  1599. }
  1600. }
  1601. private assignStringMetadata(target: VideoItem, key: keyof VideoItem, value?: string | null, allowEmpty = false): void {
  1602. if (value === undefined || value === null) {
  1603. return;
  1604. }
  1605. const text = value.toString();
  1606. if (!allowEmpty && text.trim().length === 0) {
  1607. return;
  1608. }
  1609. Reflect.set(target, key as string, value);
  1610. }
  1611. private assignNumberMetadata(target: VideoItem, key: keyof VideoItem, value?: number | null): void {
  1612. if (value === undefined || value === null || Number.isNaN(value)) {
  1613. return;
  1614. }
  1615. Reflect.set(target, key as string, value);
  1616. }
  1617. private mergeVideoItemWithPayload(target: VideoItem, payload: WorkerMetadataPayload): void {
  1618. if (!target || !payload) {
  1619. return;
  1620. }
  1621. this.assignStringMetadata(target, 'name', payload.name);
  1622. this.assignStringMetadata(target, 'artist', payload.artist);
  1623. this.assignStringMetadata(target, 'album', payload.album);
  1624. this.assignStringMetadata(target, 'bit_rate', payload.bit_rate);
  1625. this.assignStringMetadata(target, 'duration', payload.duration);
  1626. this.assignStringMetadata(target, 'sampleRate', payload.sampleRate);
  1627. this.assignStringMetadata(target, 'mimeType', payload.mimeType);
  1628. this.assignStringMetadata(target, 'size', payload.size);
  1629. this.assignStringMetadata(target, 'pixelMapPath', payload.pixelMapPath);
  1630. this.assignStringMetadata(target, 'lyricContent', payload.lyricContent, true);
  1631. this.assignStringMetadata(target, 'genre', payload.genre);
  1632. this.assignStringMetadata(target, 'track', payload.track);
  1633. this.assignStringMetadata(target, 'bits_per_raw_sample', payload.bits_per_raw_sample);
  1634. this.assignStringMetadata(target, 'channels', payload.channels);
  1635. this.assignStringMetadata(target, 'channel_layout', payload.channel_layout);
  1636. this.assignStringMetadata(target, 'start_time', payload.start_time);
  1637. this.assignStringMetadata(target, 'year', payload.year);
  1638. this.assignStringMetadata(target, 'disc', payload.disc);
  1639. this.assignStringMetadata(target, 'ALBUMARTIST', payload.ALBUMARTIST);
  1640. this.assignStringMetadata(target, 'COMPOSER', payload.COMPOSER);
  1641. this.assignStringMetadata(target, 'LYRICIST', payload.LYRICIST);
  1642. this.assignStringMetadata(target, 'COMMENT', payload.COMMENT, true);
  1643. this.assignNumberMetadata(target, 'videoSize', payload.videoSize);
  1644. this.assignNumberMetadata(target, 'probe_score', payload.probe_score);
  1645. this.assignNumberMetadata(target, 'nb_streams', payload.nb_streams);
  1646. this.assignNumberMetadata(target, 'nb_programs', payload.nb_programs);
  1647. }
  1648. private mergeVideoItemFromSource(target: VideoItem, source: VideoItem): void {
  1649. if (!target || !source) {
  1650. return;
  1651. }
  1652. this.assignStringMetadata(target, 'name', source.name);
  1653. this.assignStringMetadata(target, 'artist', source.artist);
  1654. this.assignStringMetadata(target, 'album', source.album);
  1655. this.assignStringMetadata(target, 'bit_rate', source.bit_rate);
  1656. this.assignStringMetadata(target, 'duration', source.duration);
  1657. this.assignStringMetadata(target, 'sampleRate', source.sampleRate);
  1658. this.assignStringMetadata(target, 'trackCount', source.trackCount);
  1659. this.assignStringMetadata(target, 'mimeType', source.mimeType);
  1660. this.assignStringMetadata(target, 'size', source.size);
  1661. this.assignStringMetadata(target, 'pixelMapPath', source.pixelMapPath);
  1662. this.assignStringMetadata(target, 'lyricContent', source.lyricContent, true);
  1663. this.assignStringMetadata(target, 'genre', source.genre);
  1664. this.assignStringMetadata(target, 'track', source.track);
  1665. this.assignStringMetadata(target, 'bits_per_raw_sample', source.bits_per_raw_sample);
  1666. this.assignStringMetadata(target, 'channels', source.channels);
  1667. this.assignStringMetadata(target, 'channel_layout', source.channel_layout);
  1668. this.assignStringMetadata(target, 'start_time', source.start_time);
  1669. this.assignStringMetadata(target, 'year', source.year);
  1670. this.assignStringMetadata(target, 'disc', source.disc);
  1671. this.assignStringMetadata(target, 'ALBUMARTIST', source.ALBUMARTIST);
  1672. this.assignStringMetadata(target, 'COMPOSER', source.COMPOSER);
  1673. this.assignStringMetadata(target, 'LYRICIST', source.LYRICIST);
  1674. this.assignStringMetadata(target, 'COMMENT', source.COMMENT, true);
  1675. this.assignNumberMetadata(target, 'videoSize', source.videoSize);
  1676. this.assignNumberMetadata(target, 'probe_score', source.probe_score);
  1677. this.assignNumberMetadata(target, 'nb_streams', source.nb_streams);
  1678. this.assignNumberMetadata(target, 'nb_programs', source.nb_programs);
  1679. if (source.remote_rel_path && StrUtil.isEmpty(target.remote_rel_path)) {
  1680. target.remote_rel_path = source.remote_rel_path;
  1681. }
  1682. }
  1683. private async hydrateRemoteSongFromDb(item: VideoItem | undefined): Promise<void> {
  1684. if (!item || !isRemoteCloudType(item.type)) {
  1685. return;
  1686. }
  1687. const storagePath = item.remote_rel_path || WebDavUrlUtil.toStoragePath(item.filePath);
  1688. if (!storagePath) {
  1689. return;
  1690. }
  1691. try {
  1692. const cached = await this.table.queryVideoByFilePath(storagePath);
  1693. if (!cached) {
  1694. return;
  1695. }
  1696. this.mergeVideoItemFromSource(item, cached);
  1697. if (StrUtil.isEmpty(item.remote_rel_path)) {
  1698. item.remote_rel_path = storagePath;
  1699. }
  1700. if (item === this.currentSong) {
  1701. if (StrUtil.isNotEmpty(item.name)) {
  1702. this.name = item.name;
  1703. }
  1704. if (StrUtil.isNotEmpty(item.artist)) {
  1705. this.artist = item.artist!;
  1706. }
  1707. if (StrUtil.isNotEmpty(item.pixelMapPath)) {
  1708. this.cover = item.pixelMapPath!;
  1709. }
  1710. if (StrUtil.isNotEmpty(item.lyricContent) && StrUtil.isEmpty(this.lyricContent)) {
  1711. this.applyInlineLyricContent(item.lyricContent as string);
  1712. }
  1713. }
  1714. } catch (error) {
  1715. Logger.error(TAG, `hydrateRemoteSongFromDb 失败: ${(error as Error).message}`);
  1716. }
  1717. }
  1718. private applyInlineLyricContent(content: string): void {
  1719. if (StrUtil.isEmpty(content)) {
  1720. return;
  1721. }
  1722. this.lyricContent = content;
  1723. const lines: string[] = content.split('\n').map((line: string) => line.trim());
  1724. const lyric: Lyric = this.parser.parse(lines);
  1725. this.lyricController.setLyric(lyric);
  1726. this.lyricControllerXF.setLyric(lyric);
  1727. this.lyricControllerSingle.setLyric(lyric);
  1728. }
  1729. private extractParentPathFromStoragePath(path: string): string {
  1730. if (!path) {
  1731. return '';
  1732. }
  1733. const lastSlash = path.lastIndexOf('/');
  1734. if (lastSlash <= 0) {
  1735. return '';
  1736. }
  1737. return path.substring(0, lastSlash);
  1738. }
  1739. private resolveRemoteStoragePath(target: VideoItem): string | null {
  1740. if (!target || !isRemoteCloudType(target.type)) {
  1741. return null;
  1742. }
  1743. if (isWebDavType(target.type)) {
  1744. const storagePath = target.remote_rel_path || WebDavUrlUtil.toStoragePath(target.filePath);
  1745. if (storagePath) {
  1746. target.remote_rel_path = storagePath;
  1747. return storagePath;
  1748. }
  1749. return null;
  1750. }
  1751. if (target.remote_rel_path && target.remote_rel_path.length > 0) {
  1752. return target.remote_rel_path;
  1753. }
  1754. return null;
  1755. }
  1756. private async persistRemoteMetadataToDb(target: VideoItem): Promise<void> {
  1757. if (!this.context || !target || !isRemoteCloudType(target.type)) {
  1758. return;
  1759. }
  1760. const storagePath = this.resolveRemoteStoragePath(target);
  1761. if (!storagePath) {
  1762. return;
  1763. }
  1764. const table = new MediaTable(this.context);
  1765. await new Promise<void>((resolve) => {
  1766. table.getRdbStore(this.context as Context, () => resolve());
  1767. });
  1768. const cloneItem = cloneVideoItem(target);
  1769. cloneItem.filePath = storagePath;
  1770. cloneItem.remote_rel_path = storagePath;
  1771. cloneItem.parentPath = this.extractParentPathFromStoragePath(storagePath);
  1772. await table.saveOrUpdateWebDavItem(cloneItem);
  1773. }
  1774. onPageHide() {
  1775. this.knockController?.immersiveDisableListening();
  1776. }
  1777. @State isFirstStartPlay: boolean = false
  1778. private async startFileDeletionWatcher(): Promise<void> {
  1779. if (!this.rootPath) {
  1780. return;
  1781. }
  1782. if (!this.deletionWatcher) {
  1783. this.deletionWatcher = new FileDeletionWatcher(this.context, this.table);
  1784. }
  1785. try {
  1786. await this.deletionWatcher.watchDirectories([
  1787. this.rootPath,
  1788. this.lockPath,
  1789. this.favPath,
  1790. this.historyPath
  1791. ]);
  1792. } catch (error) {
  1793. Logger.error(TAG, `初始化文件删除监听失败: ${(error as Error).message}`);
  1794. }
  1795. }
  1796. //获取download_path
  1797. async mkDownLoadDir() {
  1798. const documentViewPicker = new picker.DocumentViewPicker()
  1799. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  1800. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  1801. PreferencesUtil.putSync('download_path', this.rootPath+'/')
  1802. this.currentPath = this.rootPath
  1803. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  1804. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  1805. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  1806. Logger.info('onecold rootPath = ' + this.rootPath)
  1807. if (!FileUtil.accessSync(this.favPath)) {
  1808. FileUtil.mkdirSync(this.favPath)
  1809. }
  1810. if (!FileUtil.accessSync(this.historyPath)) {
  1811. FileUtil.mkdirSync(this.historyPath)
  1812. }
  1813. // await this.startFileDeletionWatcher();
  1814. this.getSortedFiles(this.rootPath).then(async () => {
  1815. this.isFavMusic = false
  1816. //穿山甲
  1817. // this.loadBannerAd(CSJUtil.getBannerID())
  1818. this.restoreLastPlayContext();
  1819. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  1820. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  1821. if (ArrayUtil.isEmpty(this.songList)) {
  1822. this.songList = this.getCurFileList()
  1823. } else {
  1824. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  1825. }
  1826. if (ArrayUtil.isNotEmpty(this.songList)) {
  1827. this.isFirstStartPlay = true
  1828. this.sonDataSource.pushArrayData(this.songList)
  1829. if (this.currentSong === undefined) {
  1830. this.isFirstStartPlay = false
  1831. this.currentSong = this.songList[0]
  1832. }
  1833. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  1834. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  1835. context: this.context,
  1836. autoParseMusicName: this.autoParseMusicName
  1837. });
  1838. Logger.info(TAG, `WebDAV URL同步构建完成: ${this.videoUrl}`);
  1839. this.name = this.currentSong.name
  1840. this.cover = this.currentSong.pixelMapPath
  1841. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  1842. } else {
  1843. this.name = '空空如也'
  1844. }
  1845. })
  1846. this.getFavList(false)
  1847. }
  1848. getFavList(isFavRefresh: boolean) {
  1849. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  1850. this.favList = result
  1851. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  1852. this.videoLocalList = this.favList
  1853. this.updateListData(this.videoLocalList, true)
  1854. }
  1855. })
  1856. }
  1857. getHistoryList(isRefresh: boolean) {
  1858. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  1859. this.historyList = result
  1860. // for (let i = 0; i < this.historyList.length; i++) {
  1861. //
  1862. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  1863. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  1864. // }
  1865. if (isRefresh) {
  1866. this.videoLocalList = this.historyList
  1867. this.updateListData(this.videoLocalList, true)
  1868. }
  1869. })
  1870. }
  1871. // 组件消失生命周期
  1872. aboutToDisappear() {
  1873. console.info('LifeCycleComponent aboutToDisappear');
  1874. if (this.alphaBetHideTimer) {
  1875. clearTimeout(this.alphaBetHideTimer);
  1876. this.alphaBetHideTimer = 0;
  1877. }
  1878. if (this.alphaBetRebuildTimer) {
  1879. clearTimeout(this.alphaBetRebuildTimer);
  1880. this.alphaBetRebuildTimer = 0;
  1881. }
  1882. if (this.pagingScheduleTimer) {
  1883. clearTimeout(this.pagingScheduleTimer);
  1884. this.pagingScheduleTimer = 0;
  1885. }
  1886. if (this.gridWaterScrollIdleTimer) {
  1887. clearTimeout(this.gridWaterScrollIdleTimer);
  1888. this.gridWaterScrollIdleTimer = 0;
  1889. }
  1890. if (this.listUpdateTimer) {
  1891. clearTimeout(this.listUpdateTimer);
  1892. this.listUpdateTimer = 0;
  1893. }
  1894. if (this.mediaLibraryWarmupPrefetchTimer) {
  1895. clearTimeout(this.mediaLibraryWarmupPrefetchTimer);
  1896. this.mediaLibraryWarmupPrefetchTimer = 0;
  1897. }
  1898. this.clearInitialSeekGuardTimer();
  1899. this.alphaBetBuildVersion++;
  1900. this.gridWaterLastActiveTs = 0;
  1901. this.coverThumbCache.dispose();
  1902. this.coverThumbCacheReady = false;
  1903. this.pendingCoverThumbRefresh = false;
  1904. this.deletionWatcher?.stop();
  1905. this.knockController?.immersiveDisableListening();
  1906. this.curIndex = 0
  1907. this.isAppForeground = false;
  1908. emitter.off(EventConstants.EVENT_AUDIO_OPEN);
  1909. emitter.off(EventConstants.EVENT_SCAN_UPDATE);
  1910. emitter.off(EventConstants.EVENT_SWIPE_BACK_UPDATE);
  1911. emitter.off(EventConstants.EVENT_SETTING_UPDATE);
  1912. emitter.off(EventConstants.EVENT_WEBDAV_METADATA_UPDATED);
  1913. emitter.off(EventConstants.EVENT_EQUALIZER_CHANGED);
  1914. emitter.off(EventConstants.EVENT_PLAY_QUEUE_REFRESH);
  1915. this.mDestroyPage = true;
  1916. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  1917. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  1918. this.stop();
  1919. }
  1920. this.mIjkMediaPlayer.off('audioInterrupt');
  1921. this.mIjkMediaPlayer.off('deviceChange');
  1922. if (workerInstance) {
  1923. workerInstance.terminate();
  1924. }
  1925. this.stopPip();
  1926. this.destroyPipController()
  1927. this.getUIContext().getHostContext()!.eventHub.off('playOrPause');
  1928. this.getUIContext().getHostContext()!.eventHub.off('playPrevious');
  1929. this.getUIContext().getHostContext()!.eventHub.off('playNext');
  1930. this.getUIContext().getHostContext()!.eventHub.off('showPlayerView');
  1931. this.getUIContext().getHostContext()!.eventHub.off('openPlayList');
  1932. this.eventHub.off('onStateChange');
  1933. }
  1934. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean,
  1935. openItem?: VideoItem, immediateListUpdate?: boolean, scrollTopAfterUpdate?: boolean) {
  1936. this.isFavMusic = false
  1937. console.info('onecold getSortedFiles 1 curPath '+curPath)
  1938. if (isWorkerPost) {
  1939. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1940. }
  1941. if (this.modeType !== 0) {
  1942. // 第三方打开场景:非文件夹模式也需要继续执行自动播放
  1943. if (isOpen && destPath) {
  1944. this.openMusic(true, destPath, openItem)
  1945. }
  1946. return
  1947. }
  1948. console.info('onecold getSortedFiles 2')
  1949. this.isCanBack = false
  1950. this.currentPath = curPath
  1951. console.info('onecold getSortedFiles this.currentPath ='+this.currentPath)
  1952. this.titleName = getFileDirName(this.currentPath,this.rootPath)
  1953. if (curPath === this.rootPath) {
  1954. this.rightTopImage = $r('sys.symbol.sort')
  1955. } else {
  1956. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  1957. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  1958. this.rightTopImage = $r('sys.symbol.chevron_left')
  1959. }
  1960. }
  1961. // Get the current file list and calculate its hash
  1962. this.fileList = FileUtil.listFileSync(curPath);
  1963. const currentHash = simpleHash(this.fileList);
  1964. // Check cache
  1965. const cachedValue = this.findCache(curPath);
  1966. Logger.info('onecold cachedValue = ' + cachedValue)
  1967. const cachedHash = this.findStringCache(curPath + '_hash');
  1968. const cachedDirList = this.findCache(curPath + "_dirList");
  1969. if (cachedValue !== undefined&&!this.isRefreshing) {
  1970. // this.videoLocalList = cachedValue;
  1971. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  1972. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  1973. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  1974. }
  1975. this.isRefreshing = false
  1976. this.updateListData(cachedValue, undefined, immediateListUpdate)
  1977. if (scrollTopAfterUpdate) {
  1978. this.scrollToTopForCurrentLayout()
  1979. }
  1980. }
  1981. if (cachedDirList !== undefined) {
  1982. this.dirList = cachedDirList
  1983. }
  1984. //通过当前hash值和缓存hash判断list有没有变化
  1985. if (cachedValue && cachedHash === currentHash) {
  1986. return;
  1987. }
  1988. // this.fileList = FileUtil.listFileSync(curPath)
  1989. let directories: Array<VideoItem> = [];
  1990. let files: Array<VideoItem> = [];
  1991. for (let i = 0; i < this.fileList.length; i++) {
  1992. // console.info(`The name of file: ${this.fileList[i]}`);
  1993. let path = curPath + '/' + this.fileList[i]
  1994. if (FileUtil.isDirectory(path)) {
  1995. let item: VideoItem =
  1996. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  1997. '')
  1998. if (this.isShowDir(item.name)) {
  1999. directories.push(item);
  2000. }
  2001. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2002. // Utility.doSortListAscending(directories)
  2003. } else {
  2004. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  2005. let item: VideoItem =
  2006. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  2007. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  2008. files.push(item);
  2009. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2010. // this.doSortListAscending(files)
  2011. }
  2012. }
  2013. }
  2014. }
  2015. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  2016. if (this.currentPath !== this.lockPath) {
  2017. files = result;
  2018. }
  2019. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  2020. Utility.doSortListAscending(files)
  2021. if (this.currentPath === this.rootPath) {
  2022. this.dirList = directories
  2023. this.addCache(curPath + "_dirList", this.dirList);
  2024. }
  2025. //插入广告先注释掉
  2026. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  2027. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  2028. // directories.push(adItem)
  2029. // }
  2030. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  2031. this.videoLocalList = directories.concat(files);
  2032. this.updateListData(this.videoLocalList, undefined, immediateListUpdate)
  2033. if (scrollTopAfterUpdate) {
  2034. this.scrollToTopForCurrentLayout()
  2035. }
  2036. if (ArrayUtil.isNotEmpty(files)) {
  2037. if (this.currentPath != this.rootPath) {
  2038. if (files) {
  2039. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  2040. }
  2041. }
  2042. // 缓存结果
  2043. this.addCache(curPath, this.videoLocalList);
  2044. await this.saveCacheToStorage(); // 保存缓存至本地存储
  2045. this.addStringCache(curPath + '_hash', currentHash);
  2046. }
  2047. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  2048. for (let i = 0; i < this.videoLocalList.length; i++) {
  2049. console.info(`onecold gengxin 1: ${this.videoLocalList[i].name}`);
  2050. }
  2051. // this.setButtonStatus()
  2052. this.openMusic(isOpen, destPath,openItem)
  2053. this.isRefreshing = false
  2054. });
  2055. }
  2056. //第三方app打开天天静听导入音乐后播放
  2057. openMusic(isOpen?: boolean, destPath?: string,openItem?:VideoItem){
  2058. if (isOpen&&destPath) {
  2059. if (destPath === undefined) {
  2060. // 处理 destPath 为 undefined 的情况
  2061. return
  2062. }
  2063. if (destPath.endsWith('.lrc')) {
  2064. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  2065. if (StrUtil.isNotEmpty(this.videoUrl)) {
  2066. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  2067. this.initLyric(lyricPath);
  2068. }
  2069. return
  2070. }
  2071. if(openItem){
  2072. this.doPlay(openItem,0,false,true)
  2073. // this.isShowPlay = true
  2074. this.setShowPlayTrue()
  2075. }
  2076. }
  2077. }
  2078. //扫描文件夹入库
  2079. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  2080. const files = FileUtil.listFileSync(curPath);
  2081. let mediaItems: VideoItem[] = [];
  2082. Logger.info('onecold scanDirectory start ')
  2083. for (const file of files) {
  2084. const fPath = `${curPath}/${file}`;
  2085. if (fPath === this.lockPath) {
  2086. Logger.info(`Skipping locked path: ${fPath}`);
  2087. continue;
  2088. }
  2089. if (FileUtil.isDirectory(fPath)) {
  2090. // Recursively scan subdirectories
  2091. const subDirItems = await this.scanDirectory(fPath);
  2092. mediaItems = mediaItems.concat(subDirItems);
  2093. } else {
  2094. Logger.info('onecold scanDirectory filePath = ' + fPath)
  2095. // Process media files
  2096. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  2097. let mediaItem: VideoItem =
  2098. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2099. mediaItems.push(mediaItem);
  2100. this.table.insert(mediaItem, (id: number) => {
  2101. });
  2102. }
  2103. }
  2104. }
  2105. return mediaItems;
  2106. }
  2107. updateListData(mList: Array<VideoItem>, noSort?: boolean, immediate?: boolean) {
  2108. this.isShowTitleBar = true
  2109. const shouldAnimate = !immediate
  2110. if (this.listUpdateTimer) {
  2111. clearTimeout(this.listUpdateTimer)
  2112. this.listUpdateTimer = 0
  2113. }
  2114. const updateVersion = ++this.listUpdateVersion
  2115. if (shouldAnimate) {
  2116. this.getUIContext().animateTo({ duration: 666 }, () => {
  2117. this.opacityItem = 0.5;
  2118. });
  2119. }
  2120. const applyListData = () => {
  2121. if (updateVersion !== this.listUpdateVersion) {
  2122. return
  2123. }
  2124. this.videoLocalList = mList;
  2125. if (!noSort) {
  2126. if (this.modeType === 0 || this.modeType === 1) {
  2127. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  2128. this.doSortType(this.sortType)
  2129. }
  2130. }
  2131. this.dataSource.pushArrayData(this.videoLocalList)
  2132. if (shouldAnimate) {
  2133. this.getUIContext().animateTo({ duration: 666 }, () => {
  2134. this.opacityItem = 1;
  2135. });
  2136. } else {
  2137. this.opacityItem = 1;
  2138. }
  2139. this.setButtonStatus()
  2140. //添加到字母索引表
  2141. this.markAlphaBetDirty()
  2142. };
  2143. if (immediate) {
  2144. applyListData();
  2145. return;
  2146. }
  2147. this.listUpdateTimer = setTimeout(() => {
  2148. this.listUpdateTimer = 0
  2149. applyListData();
  2150. }, 200);
  2151. }
  2152. getCurFileList(): Array<VideoItem> {
  2153. if(this.isSearchMode){
  2154. return this.filteredList
  2155. }
  2156. let files: Array<VideoItem> = [];
  2157. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2158. for (let i = 0; i < this.videoLocalList.length; i++) {
  2159. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  2160. files.push(this.videoLocalList[i]);
  2161. }
  2162. }
  2163. }
  2164. return files
  2165. }
  2166. setButtonStatus() {
  2167. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2168. this.isZero = false
  2169. } else {
  2170. this.isZero = true
  2171. }
  2172. if (this.currentPath !== this.rootPath &&
  2173. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  2174. this.isHasDir = true //不为空,说明有子文件夹
  2175. } else {
  2176. this.isHasDir = false
  2177. }
  2178. }
  2179. private getPlayListDisplayCount(): number {
  2180. if (this.playQueueScope === 'history') {
  2181. return this.historyList.length;
  2182. }
  2183. if (this.playQueueScope === 'fav') {
  2184. return this.favList.length;
  2185. }
  2186. if (this.playQueueScope === 'playlist') {
  2187. // 检测是否是流媒体播放(Navidrome/Jellyfin/Emby/AudioStation/Plex/道理鱼等)
  2188. // 如果是,优先返回服务端总数
  2189. const navidromeTotalCount = getNavidromeTotalCount();
  2190. Logger.info('heanup getPlayListDisplayCount', `playQueueScope=playlist, navidromeTotalCount=${navidromeTotalCount}, currentSong=${this.currentSong?.name}, type=${this.currentSong?.type}`);
  2191. if (navidromeTotalCount > 0 && this.currentSong && (
  2192. isNavidromeType(this.currentSong.type) ||
  2193. isJellyfinType(this.currentSong.type) ||
  2194. isEmbyType(this.currentSong.type) ||
  2195. isAudioStationType(this.currentSong.type) ||
  2196. isPlexType(this.currentSong.type) ||
  2197. isDaoLiYuType(this.currentSong.type)
  2198. )) {
  2199. Logger.info('heanup getPlayListDisplayCount', `返回服务端总数: ${navidromeTotalCount}`);
  2200. return navidromeTotalCount;
  2201. }
  2202. Logger.info('heanup getPlayListDisplayCount', `返回 currentSongList.length: ${this.currentSongList.length}`);
  2203. return this.currentSongList.length;
  2204. }
  2205. if (this.playQueueScope === 'view' && this.modeType === 1 && this.totalCount > 0) {
  2206. return this.totalCount;
  2207. }
  2208. Logger.info('heanup getPlayListDisplayCount', `返回 songList.length: ${this.songList.length}, playQueueScope=${this.playQueueScope}`);
  2209. return this.songList.length;
  2210. }
  2211. private restoreLastPlayContext(): void {
  2212. const scope = PreferencesUtil.getStringSync('LastPlayQueueScope', 'view') as string;
  2213. if (scope === 'history' || scope === 'fav' || scope === 'playlist' || scope === 'single') {
  2214. this.playQueueScope = scope;
  2215. } else {
  2216. this.playQueueScope = 'view';
  2217. }
  2218. const lastModeType = PreferencesUtil.getNumberSync('LastPlayModeType', this.modeType);
  2219. const lastTotalCount = PreferencesUtil.getNumberSync('LastPlayTotalCount', 0);
  2220. if (lastModeType === 1 && this.totalCount === 0 && lastTotalCount > 0) {
  2221. this.totalCount = lastTotalCount;
  2222. }
  2223. }
  2224. private async hydrateFullMediaPlayListIfNeeded(isSonList:boolean = true): Promise<void> {
  2225. if (this.isHydratingPlayList) {
  2226. return;
  2227. }
  2228. if (this.playQueueScope !== 'view' || this.modeType !== 1) {
  2229. return;
  2230. }
  2231. if (this.totalCount === 0 || this.songList.length >= this.totalCount) {
  2232. return;
  2233. }
  2234. this.isHydratingPlayList = true;
  2235. try {
  2236. const fullList: VideoItem[] = [];
  2237. let pageIndex = 0;
  2238. let hasMore = true;
  2239. while (hasMore) {
  2240. const result = await this.table.queryMediaLibraryPaged({
  2241. pageIndex,
  2242. pageSize: this.pageSize,
  2243. sortType: this.sortType,
  2244. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  2245. isShowFileName: this.isShowFileName
  2246. });
  2247. if (result.items.length === 0) {
  2248. break;
  2249. }
  2250. fullList.push(...result.items);
  2251. hasMore = result.hasMore;
  2252. pageIndex += 1;
  2253. if (fullList.length >= result.totalCount) {
  2254. hasMore = false;
  2255. }
  2256. }
  2257. if (fullList.length > 0) {
  2258. if(isSonList){
  2259. this.songList = fullList;
  2260. this.sonDataSource.pushArrayData(this.songList);
  2261. }else{
  2262. this.videoLocalList = fullList;
  2263. this.dataSource.pushArrayData(this.videoLocalList);
  2264. }
  2265. }
  2266. } finally {
  2267. this.isHydratingPlayList = false;
  2268. }
  2269. }
  2270. @Builder
  2271. SortMenuBuilder() {
  2272. Menu() {
  2273. MenuItem({
  2274. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.person')),
  2275. content: "按艺术家",
  2276. builder: this.SubSortBuilder(SortMode.ByArtist),
  2277. symbolEndIcon: this.isSortTypeInRange(SortMode.ByArtist) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2278. })
  2279. MenuItem({
  2280. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat_size_square')),
  2281. content: "按专辑",
  2282. builder: this.SubSortBuilder(SortMode.ByAlbum),
  2283. symbolEndIcon: this.isSortTypeInRange(SortMode.ByAlbum) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2284. })
  2285. MenuItem({
  2286. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat')),
  2287. content: "按名称",
  2288. builder: this.SubSortBuilder(SortMode.ByName),
  2289. symbolEndIcon: this.isSortTypeInRange(SortMode.ByName) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2290. })
  2291. MenuItem({
  2292. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2293. content: $r('app.string.sort_by_time'),
  2294. builder: this.SubSortBuilder(SortMode.ByTime),
  2295. symbolEndIcon: this.isSortTypeInRange(SortMode.ByTime) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2296. })
  2297. MenuItem({
  2298. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  2299. content: '按碟片音轨号',
  2300. builder: this.SubSortBuilder(SortMode.ByDiscTrack),
  2301. symbolEndIcon: this.isSortTypeInRange(SortMode.ByDiscTrack) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2302. })
  2303. .visibility((this.modeType==0||(this.modeType==2&&this.isCanBack)||
  2304. (this.modeType==3&&this.isCanBack))?Visibility.Visible:Visibility.None)
  2305. }.attributeModifier(new MenuModifier())
  2306. }
  2307. @Builder
  2308. SortMenuForArtistAblumBuilder() {
  2309. Menu() {
  2310. MenuItem({
  2311. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat')),
  2312. content: "按名称",
  2313. builder: this.SubSortBuilder(SortMode.ByName),
  2314. symbolEndIcon: this.isSortTypeInRange(SortMode.ByName) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2315. })
  2316. MenuItem({
  2317. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2318. content: '按数量',
  2319. builder: this.SubSortBuilder(SortMode.ByCount),
  2320. symbolEndIcon: this.isSortTypeInRange(SortMode.ByCount) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2321. })
  2322. }.attributeModifier(new MenuModifier())
  2323. }
  2324. @Builder SubSortBuilder(sortType: number){
  2325. Menu(){
  2326. MenuItem({
  2327. content: "升序",
  2328. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_up')),
  2329. symbolEndIcon: this.sortType === sortType ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2330. })
  2331. .onClick(async () => {
  2332. await this.doSortType(sortType)
  2333. })
  2334. MenuItem({
  2335. content: "降序",
  2336. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_down')),
  2337. symbolEndIcon: this.sortType === sortType + 1 ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2338. })
  2339. .onClick(async () => {
  2340. await this.doSortType(sortType + 1) // 降序的sortType = 升序的sortType + 1
  2341. })
  2342. }
  2343. }
  2344. async doSortType(index: number): Promise<void> {
  2345. Logger.info('heanup LocalMusic', `doSortType: 切换排序方式 sortType=${index}, mode=${this.modeType}, isCanBack=${this.isCanBack}`);
  2346. this.sortType = index;
  2347. this.saveSortTypeForCurrentMode(index);
  2348. // 详情页模式(modeType=2/3 且 isCanBack=true): 重新查询当前项目的歌曲
  2349. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  2350. await this.reloadCurrentDetailSongs();
  2351. } else {
  2352. // 分页模式下,排序需要重新从数据库查询
  2353. await this.resetAndLoadFirstPage();
  2354. }
  2355. }
  2356. /**
  2357. * 重新加载当前详情页(专辑/艺术家)的歌曲数据
  2358. * 用于详情页切换排序方式时重新查询并排序
  2359. */
  2360. private async reloadCurrentDetailSongs(): Promise<void> {
  2361. Logger.info('heanup LocalMusic', `reloadCurrentDetailSongs: modeType=${this.modeType}, titleName=${this.titleName}, sortType=${this.sortType}`);
  2362. try {
  2363. if (this.modeType === 2) {
  2364. // 艺术家详情页: 重新查询该艺术家的歌曲
  2365. const mList = await this.table.querySongsByArtist(this.titleName, this.sortType, this.isShowFileName);
  2366. if (ArrayUtil.isNotEmpty(mList)) {
  2367. // 使用带排序类型的缓存键
  2368. const cacheKey = `${this.titleName}_sort_${this.sortType}`;
  2369. this.artistMap.set(cacheKey, mList);
  2370. this.totalCount = mList.length;
  2371. // 使用 noSort=true 避免在 updateListData 中重新排序导致死循环
  2372. this.updateListData(mList, true);
  2373. Logger.info('heanup LocalMusic', `reloadCurrentDetailSongs: 艺术家详情页重新加载完成, 歌曲数=${mList.length}`);
  2374. }
  2375. } else if (this.modeType === 3) {
  2376. // 专辑详情页: 重新查询该专辑的歌曲
  2377. const albumList = await this.table.querySongsByAlbum(this.titleName, this.sortType, this.isShowFileName);
  2378. if (ArrayUtil.isNotEmpty(albumList)) {
  2379. // 使用带排序类型的缓存键
  2380. const cacheKey = `${this.titleName}_sort_${this.sortType}`;
  2381. this.albumMap.set(cacheKey, albumList);
  2382. this.totalCount = albumList.length;
  2383. // 使用 noSort=true 避免在 updateListData 中重新排序导致死循环
  2384. this.updateListData(albumList, true);
  2385. Logger.info('heanup LocalMusic', `reloadCurrentDetailSongs: 专辑详情页重新加载完成, 歌曲数=${albumList.length}`);
  2386. }
  2387. }
  2388. } catch (err) {
  2389. const error = err as Error;
  2390. Logger.error('heanup LocalMusic', `reloadCurrentDetailSongs error: ${error.message}`);
  2391. ToastUtil.showToast('重新加载数据失败');
  2392. }
  2393. }
  2394. /**
  2395. * 根据当前模式保存排序类型到不同的存储键
  2396. * 区分列表页和详情页的排序设置
  2397. */
  2398. private saveSortTypeForCurrentMode(sortType: number): void {
  2399. let storageKey = SettingPage.SORT_TYPE;
  2400. if (this.modeType === 2) {
  2401. // 艺术家模式
  2402. if (this.isCanBack) {
  2403. storageKey = 'SORT_TYPE_ARTIST_DETAIL'; // 艺术家详情页排序
  2404. } else {
  2405. storageKey = 'SORT_TYPE_ARTIST'; // 艺术家列表页排序
  2406. }
  2407. } else if (this.modeType === 3) {
  2408. // 专辑模式
  2409. if (this.isCanBack) {
  2410. storageKey = 'SORT_TYPE_ALBUM_DETAIL'; // 专辑详情页排序
  2411. } else {
  2412. storageKey = 'SORT_TYPE_ALBUM'; // 专辑列表页排序
  2413. }
  2414. } else {
  2415. storageKey = SettingPage.SORT_TYPE;
  2416. }
  2417. PreferencesUtil.putSync(storageKey, sortType);
  2418. Logger.info('heanup LocalMusic', `saveSortTypeForCurrentMode: mode=${this.modeType}, isCanBack=${this.isCanBack}, sortType=${sortType}, key=${storageKey}`);
  2419. }
  2420. /**
  2421. * 根据当前模式加载排序类型
  2422. * 区分列表页和详情页的排序设置
  2423. */
  2424. private loadSortTypeForCurrentMode(): number {
  2425. let storageKey = SettingPage.SORT_TYPE;
  2426. let defaultSortType = 4;
  2427. if (this.modeType === 2) {
  2428. // 艺术家模式
  2429. if (this.isCanBack) {
  2430. storageKey = 'SORT_TYPE_ARTIST_DETAIL'; // 艺术家详情页排序
  2431. defaultSortType = 4; // 详情页默认按名称升序
  2432. } else {
  2433. storageKey = 'SORT_TYPE_ARTIST'; // 艺术家列表页排序
  2434. defaultSortType = 9; // 列表页默认按数量降序
  2435. }
  2436. } else if (this.modeType === 3) {
  2437. // 专辑模式
  2438. if (this.isCanBack) {
  2439. storageKey = 'SORT_TYPE_ALBUM_DETAIL'; // 专辑详情页排序
  2440. defaultSortType = 4; // 详情页默认按名称升序
  2441. } else {
  2442. storageKey = 'SORT_TYPE_ALBUM'; // 专辑列表页排序
  2443. defaultSortType = 9; // 列表页默认按数量降序
  2444. }
  2445. }
  2446. return PreferencesUtil.getNumberSync(storageKey, defaultSortType);
  2447. }
  2448. /**
  2449. * 检查当前sortType是否在指定排序类型的范围内
  2450. * 用于判断是否显示打勾图标
  2451. * @param baseSortType 基础排序类型(升序的值)
  2452. * @returns 如果当前sortType是该排序类型的升序或降序,返回true
  2453. */
  2454. private isSortTypeInRange(baseSortType: number): boolean {
  2455. return this.sortType === baseSortType || this.sortType === baseSortType + 1;
  2456. }
  2457. showSheelDialog() {
  2458. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  2459. // this.showTips()
  2460. // return
  2461. // }
  2462. this.showAddDialog()
  2463. }
  2464. showAddDialog() {
  2465. if (this.modeType === 2 || this.modeType === 3) {
  2466. return
  2467. }
  2468. DialogHelper.showActionSheetDialog({
  2469. title: "请选择添加方式(建议歌词文件一起导入)",
  2470. sheets: [
  2471. { value: "新建文件夹", fontColor: $r('app.color.text_color') },
  2472. { value: "手动导入", fontColor: $r('app.color.text_color') },
  2473. { value: "自动导入", fontColor: $r('app.color.text_color') },
  2474. { value: "全选导入", fontColor: $r('app.color.text_color') },
  2475. ],
  2476. maskColor: Color.Transparent,
  2477. backgroundColor: $r('app.color.bg_card'),
  2478. transition: AnimationHelper.transitionInDown(555),
  2479. onAction: (index) => {
  2480. switch (index) {
  2481. case 0:
  2482. if (this.modeType === 0) {
  2483. this.showMkDialog()
  2484. } else {
  2485. ToastUtil.showToast('请切换到首页才能新建文件夹!')
  2486. }
  2487. break;
  2488. case 1:
  2489. this.callFilePickerSelectFile()
  2490. break;
  2491. case 2:
  2492. this.showTips()
  2493. break;
  2494. case 3:
  2495. this.goSelectMusic()
  2496. break;
  2497. }
  2498. }
  2499. })
  2500. }
  2501. //拉起音频
  2502. goSelectMusic() {
  2503. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  2504. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  2505. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  2506. ) {
  2507. ToastUtil.showToast('暂时不支持该设备')
  2508. return
  2509. }
  2510. try {
  2511. let documentSelectOptions = new picker.DocumentSelectOptions();
  2512. documentSelectOptions.authMode = true
  2513. documentSelectOptions.multiAuthMode = true
  2514. if( deviceInfo.sdkApiVersion>=21){//如果api大于21 ,可以支持1w首歌以上
  2515. documentSelectOptions.maxSelectNumber = 20000
  2516. }
  2517. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  2518. let documentPicker = new picker.DocumentViewPicker(this.context);
  2519. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  2520. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  2521. this.saveVideoDatas(documentSelectResult)
  2522. }
  2523. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  2524. JSON.stringify(documentSelectResult));
  2525. }).catch((err: BusinessError) => {
  2526. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  2527. });
  2528. } catch (error) {
  2529. let err: BusinessError = error as BusinessError;
  2530. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2531. }
  2532. }
  2533. async showTips() {
  2534. try {
  2535. this.getUIContext().getPromptAction().showDialog({
  2536. title: '导入指南',
  2537. message:'用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  2538. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  2539. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  2540. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后去文件扫描一下。\n',
  2541. buttons: [
  2542. {
  2543. text: '知道了',
  2544. color: '#000000'
  2545. },
  2546. ]
  2547. }, (err, data) => {
  2548. if (err) {
  2549. console.error('showDialog err: ' + err);
  2550. return;
  2551. }
  2552. console.info('showDialog success callback, click button: ' + data.index);
  2553. });
  2554. } catch (error) {
  2555. let message = (error as BusinessError).message;
  2556. let code = (error as BusinessError).code;
  2557. console.error(`showDialog args error code is ${code}, message is ${message}`);
  2558. };
  2559. }
  2560. showMkDialog() {
  2561. DialogHelper.showTextInputDialog({
  2562. title: '新建歌单',
  2563. maskColor: Color.Transparent,
  2564. text: '',
  2565. transition: AnimationHelper.transitionInDown(666),
  2566. onChange: (text) => {
  2567. console.error("onChange: " + text);
  2568. },
  2569. onAction: (action, dialogId, content) => {
  2570. // ToastUtil.showToast('content = ' +content)
  2571. if (action == DialogAction.TWO) {
  2572. const newName = content
  2573. const newPath = this.currentPath + '/' + newName
  2574. FileUtil.mkdir(newPath, true).then(() => {
  2575. this.cache.delete(this.currentPath); // 删除目标路径缓存
  2576. this.getSortedFiles(this.currentPath)
  2577. }).catch((error: BusinessError) => {
  2578. console.error(error.message);
  2579. });
  2580. }
  2581. }
  2582. })
  2583. }
  2584. @State progress: number = 0;
  2585. async saveVideoDatas(uris:string[],isOpen?:boolean){
  2586. if (ArrayUtil.isEmpty(uris)) {
  2587. return;
  2588. }
  2589. console.info('onecold this.isCopyFileToDownLoad = ' + this.isCopyFileToDownLoad);
  2590. if(this.isCopyFileToDownLoad||this.currentPath==this.lockPath||isOpen){
  2591. this.saveVideoDatasToDownLoad(uris,isOpen)
  2592. return
  2593. }
  2594. // 初始化进度条
  2595. this.progress = 0;
  2596. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  2597. progress: this.progress,
  2598. backCancel: false,
  2599. autoCancel: false,
  2600. loadColor: $r('app.color.title_bar_bg'),
  2601. fontColor: $r('app.color.title_bar_bg')
  2602. });
  2603. // 计算处理总数用于进度计算
  2604. const totalItems = uris.length;
  2605. let processedItems = 0;
  2606. for (let i = 0; i < uris.length; i++) {
  2607. let filePath = uris[i];
  2608. try {
  2609. if (this.currentPath !== this.lockPath) { // 判断不是私密音乐,才入库
  2610. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2611. let mediaItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context,
  2612. filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2613. console.info('onecold saveVideoDatas filePath = ' + filePath)
  2614. if (!filePath.includes(this.rootPath)) {
  2615. console.info('onecold saveVideoDatas mediaItem.parentPath111 = ' + mediaItem.parentPath)
  2616. mediaItem.parentPath = this.currentPath;
  2617. }
  2618. console.info('onecold saveVideoDatas mediaItem.parentPath = ' + mediaItem.parentPath)
  2619. this.table.insert(mediaItem, (id: number) => {
  2620. // 插入完成回调
  2621. });
  2622. }
  2623. }
  2624. // 更新进度
  2625. processedItems++;
  2626. this.progress = Math.floor((processedItems / totalItems) * 100);
  2627. DialogHelper.updateLoading(this.loadingProgressDialogId,` 正在处理 ${this.progress}%`, this.progress);
  2628. } catch (error) {
  2629. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2630. // 即使出错也更新进度
  2631. processedItems++;
  2632. this.progress = Math.floor((processedItems / totalItems) * 100);
  2633. DialogHelper.updateLoading(this.loadingProgressDialogId,` 正在处理 ${this.progress}%`, this.progress);
  2634. }
  2635. }
  2636. // 关闭进度条
  2637. DialogHelper.closeDialog(this.loadingProgressDialogId)
  2638. this.isZero = false
  2639. // 删除目标路径缓存
  2640. setTimeout(() => {
  2641. this.cache.delete(this.currentPath);
  2642. this.getSortedFiles(this.currentPath,false,uris[0],isOpen)
  2643. this.setButtonStatus()
  2644. }, 500);
  2645. }
  2646. async saveVideoDatasToDownLoad(uris: string[], isOpen?: boolean) {
  2647. if (ArrayUtil.isEmpty(uris)) {
  2648. return;
  2649. }
  2650. let newUris: string[] = [];
  2651. this.progress = 0
  2652. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  2653. progress: this.progress,
  2654. backCancel: false,
  2655. autoCancel: false,
  2656. loadColor: this.themeColor,
  2657. fontColor: this.themeColor
  2658. });
  2659. // 计算所有文件的总大小
  2660. let totalSize = 0;
  2661. for (let uri of uris) {
  2662. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  2663. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  2664. await fileIo.close(sourceFile.fd);
  2665. }
  2666. let totalRead = 0;
  2667. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  2668. Logger.info(TAG, 'destPath uri: ' + destPath);
  2669. for (let i = 0; i < uris.length; i++) {
  2670. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  2671. Logger.info(TAG, 'filePath uri: ' + filePath);
  2672. newUris.push(filePath);
  2673. try {
  2674. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  2675. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  2676. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  2677. const buffer = new ArrayBuffer(buffSize);
  2678. let len = await fileIo.read(sourceFile.fd, buffer);
  2679. while (len > 0) {
  2680. await fileIo.write(destFile.fd, buffer.slice(0, len));
  2681. totalRead += len;
  2682. // 计算总进度
  2683. this.progress = Math.floor((totalRead / totalSize) * 100);
  2684. DialogHelper.updateLoading( this.loadingProgressDialogId,`正在导入 ${this.progress}%`, this.progress);
  2685. len = await fileIo.read(sourceFile.fd, buffer);
  2686. }
  2687. await fileIo.close(sourceFile.fd);
  2688. await fileIo.close(destFile.fd);
  2689. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  2690. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2691. let mediaItem: VideoItem =
  2692. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2693. this.table.insert(mediaItem, (id: number) => {
  2694. // 删除目标路径缓存
  2695. this.cache.delete(this.currentPath);
  2696. this.getSortedFiles(this.currentPath, true, destPath, isOpen,mediaItem)
  2697. });
  2698. }
  2699. }
  2700. } catch (error) {
  2701. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2702. }
  2703. }
  2704. DialogHelper.closeDialog(this.loadingProgressDialogId);
  2705. this.isZero = false
  2706. Logger.info(TAG, 'scan select video result:' + newUris)
  2707. }
  2708. //拉起音频
  2709. // goSelectMusic(){
  2710. //
  2711. // try {
  2712. // let audioSelectOptions = new picker.AudioSelectOptions();
  2713. // let audioPicker = new picker.AudioViewPicker(this.context);
  2714. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  2715. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  2716. // this.saveVideoDatas(audioSelectResult)
  2717. // }
  2718. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  2719. // }).catch((err: BusinessError) => {
  2720. //
  2721. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  2722. // });
  2723. // } catch (error) {
  2724. // let err: BusinessError = error as BusinessError;
  2725. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2726. // }
  2727. //
  2728. //
  2729. //
  2730. // }
  2731. async goSelectImage(item: VideoItem): Promise<string | undefined> {
  2732. if (!item) {
  2733. return undefined;
  2734. }
  2735. try {
  2736. let selectUris: Array<string> = [];
  2737. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  2738. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  2739. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  2740. photoSelectOptions.maxSelectNumber = 1;
  2741. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  2742. selectUris = photoSelectResult.photoUris;
  2743. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  2744. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  2745. console.info('file fd: ' + file.fd);
  2746. let name = await MD5.digestSync(this.videoUrl)+'.jpg'
  2747. let imagePath = this.context.filesDir + FileUtil.separator + name
  2748. imagePath = fileUri.getUriFromPath(imagePath)
  2749. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  2750. fileIo.copyFileSync(file.fd, file2.fd)
  2751. fileIo.closeSync(file);
  2752. fileIo.closeSync(file2);
  2753. if (item.filePath == this.currentSong?.filePath) {
  2754. this.cover = imagePath
  2755. }
  2756. if (item) {
  2757. item.pixelMapPath = imagePath
  2758. }
  2759. if (isRemoteCloudType(item.type)) {
  2760. return FileUtil.getFilePath(imagePath);
  2761. }
  2762. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  2763. if (success) {
  2764. this.doUpdateData()
  2765. console.log("onecold 更新音乐封面成功,数据库已同步");
  2766. } else {
  2767. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  2768. }
  2769. });
  2770. LogUtil.debug("onecold this.cover =" + this.cover)
  2771. return FileUtil.getFilePath(imagePath); // Return the image path here
  2772. } catch (err) {
  2773. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  2774. return undefined;
  2775. }
  2776. }
  2777. private async pickCoverImageToSandbox(): Promise<string | undefined> {
  2778. try {
  2779. const photoPicker = new photoAccessHelper.PhotoViewPicker();
  2780. const photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  2781. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  2782. photoSelectOptions.maxSelectNumber = 1;
  2783. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  2784. const selectUris = photoSelectResult.photoUris;
  2785. if (!selectUris || selectUris.length === 0) {
  2786. return undefined;
  2787. }
  2788. const coverDir = this.context.filesDir + FileUtil.separator + 'ttmusic_cover';
  2789. if (!FileUtil.accessSync(coverDir)) {
  2790. FileUtil.mkdirSync(coverDir);
  2791. }
  2792. const sourceUri = selectUris[0];
  2793. const sourceName = FileUtil.getFileName(sourceUri) || '';
  2794. let suffix = '.jpg';
  2795. const dotIndex = sourceName.lastIndexOf('.');
  2796. if (dotIndex >= 0) {
  2797. suffix = sourceName.substring(dotIndex);
  2798. }
  2799. const targetName = `${Date.now()}_${await MD5.digestSync(sourceUri)}${suffix}`;
  2800. const targetPath = coverDir + FileUtil.separator + targetName;
  2801. const sourceFile = fileIo.openSync(sourceUri, fileIo.OpenMode.READ_ONLY);
  2802. const targetFile = fileIo.openSync(targetPath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
  2803. fileIo.copyFileSync(sourceFile.fd, targetFile.fd);
  2804. fileIo.closeSync(sourceFile.fd);
  2805. fileIo.closeSync(targetFile.fd);
  2806. return fileUri.getUriFromPath(targetPath);
  2807. } catch (error) {
  2808. const err = error as BusinessError;
  2809. Logger.error(TAG, `pickCoverImageToSandbox failed, code: ${err.code}, message: ${err.message}`);
  2810. return undefined;
  2811. }
  2812. }
  2813. private async replaceCurrentSongCoverByAlbum(): Promise<void> {
  2814. if (!this.currentSong || StrUtil.isEmpty(this.currentSong.filePath)) {
  2815. ToastUtil.showToast('当前歌曲无效');
  2816. return;
  2817. }
  2818. if (this.currentSong.type !== CommonConstants.TYPE_LOCAL) {
  2819. ToastUtil.showToast('仅支持本地歌曲更换封面');
  2820. return;
  2821. }
  2822. const sandboxCoverUri = await this.pickCoverImageToSandbox();
  2823. if (StrUtil.isEmpty(sandboxCoverUri)) {
  2824. return;
  2825. }
  2826. this.loadingDialogId = DialogHelper.showLoadingDialog();
  2827. try {
  2828. const task = new taskpool.Task(
  2829. replaceLocalMusicCoverTask,
  2830. this.context,
  2831. this.currentSong.filePath,
  2832. FileUtil.getFilePath(sandboxCoverUri!)
  2833. );
  2834. const result = await taskpool.execute(task, taskpool.Priority.HIGH) as boolean;
  2835. if (!result) {
  2836. ToastUtil.showToast('更换封面失败');
  2837. return;
  2838. }
  2839. this.cover = sandboxCoverUri;
  2840. this.currentSong.pixelMapPath = sandboxCoverUri;
  2841. await this.doUpateEditedFields(this.currentSong);
  2842. ToastUtil.showToast('更换封面成功');
  2843. } catch (error) {
  2844. Logger.error(TAG, `replaceCurrentSongCoverByAlbum failed: ${JSON.stringify(error)}`);
  2845. ToastUtil.showToast('更换封面失败');
  2846. } finally {
  2847. DialogHelper.closeDialog(this.loadingDialogId);
  2848. }
  2849. }
  2850. // 拉起picker选择文件管理器
  2851. async callFilePickerSelectFile(): Promise<void> {
  2852. try {
  2853. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  2854. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  2855. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  2856. } else {
  2857. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  2858. }
  2859. let documentPicker = new picker.DocumentViewPicker();
  2860. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  2861. Logger.info(TAG,
  2862. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  2863. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  2864. this.saveVideoDatas(DocumentSelectResult)
  2865. }
  2866. }).catch((err: BusinessError) => {
  2867. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  2868. });
  2869. } catch (err) {
  2870. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  2871. }
  2872. }
  2873. //重命名的对话框
  2874. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  2875. if(!item.filePath.includes(this.packName)){
  2876. ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限重命名')
  2877. return
  2878. }
  2879. DialogHelper.showTextInputDialog({
  2880. title: '重命名',
  2881. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  2882. maskColor: Color.Transparent,
  2883. backgroundColor: Color.Grey,
  2884. transition: AnimationHelper.transitionInDown(666),
  2885. onChange: (text) => {
  2886. console.error("onChange: " + text);
  2887. },
  2888. onAction: (action, dialogId, content) => {
  2889. // ToastUtil.showToast('content = ' +content)
  2890. if (action == DialogAction.TWO) {
  2891. const newName = content
  2892. const newPath = this.currentPath + '/' + newName
  2893. console.log("onecold item = " + item.type);
  2894. this.doReName(index, newName, filePath, newPath, item)
  2895. }
  2896. }
  2897. })
  2898. }
  2899. //剪切 移动到另个文件夹的对话框
  2900. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  2901. Logger.info('onecold showCutDialog')
  2902. let mList: Array<string> = []
  2903. let rPath = this.rootPath
  2904. if (isCurrent) {
  2905. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2906. rPath = this.currentPath
  2907. } else {
  2908. mList = Utility.getNameList(this.dirList);
  2909. rPath = this.rootPath
  2910. }
  2911. let dataBean = new BubbleBean()
  2912. dataBean.data = mList
  2913. dataBean.color = this.themeColor
  2914. dataBean.onItemClick = (i) => {
  2915. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  2916. Logger.info('newPath = ' + newPath)
  2917. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  2918. ToastUtil.showToast('移动成功')
  2919. this.table.deleteData(item, () => {
  2920. });
  2921. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2922. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2923. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2924. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2925. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2926. this.table.insert(newItem, (id: number) => {
  2927. //加入数据库
  2928. });
  2929. }
  2930. this.cache.delete(this.currentPath); // 删除原路径缓存
  2931. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  2932. this.getSortedFiles(this.currentPath, true)
  2933. }).catch((error: BusinessError) => {
  2934. console.error(error.message);
  2935. });
  2936. XPopup.dismissTop()
  2937. }
  2938. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  2939. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  2940. popupPosition = PopupPosition.TOP
  2941. }
  2942. if (index <= 3) {
  2943. popupPosition = PopupPosition.BOTTOM
  2944. }
  2945. let pup: XPopup
  2946. if (this.isDarkMode) {
  2947. pup = XPopup.Builder()
  2948. .setPopupPosition(popupPosition)
  2949. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  2950. .setBackgroundColor(Color.Black)
  2951. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2952. .show()
  2953. } else {
  2954. pup = XPopup.Builder()
  2955. .setPopupPosition(popupPosition)
  2956. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  2957. .setBackgroundColor(Color.White)
  2958. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2959. .show()
  2960. }
  2961. }
  2962. //复制 到另个文件夹的对话框
  2963. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  2964. Logger.info('onecoldv showCopyDialog')
  2965. let mList: Array<string> = []
  2966. let rPath = this.rootPath
  2967. if (isCurrent) {
  2968. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2969. rPath = this.currentPath
  2970. } else {
  2971. mList = Utility.getNameList(this.dirList);
  2972. rPath = this.rootPath
  2973. }
  2974. let dataBean = new BubbleBean()
  2975. dataBean.data = mList
  2976. dataBean.isCopy = true
  2977. dataBean.color = this.themeColor
  2978. dataBean.onItemClick = (i) => {
  2979. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  2980. Logger.info('newPath = ' + newPath)
  2981. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  2982. ToastUtil.showToast('复制成功')
  2983. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  2984. this.getSortedFiles(this.currentPath)
  2985. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2986. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2987. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2988. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2989. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2990. this.table.insert(newItem, (id: number) => {
  2991. //加入数据库
  2992. });
  2993. }
  2994. }).catch((error: BusinessError) => {
  2995. console.error(error.message);
  2996. });
  2997. XPopup.dismissTop()
  2998. }
  2999. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  3000. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  3001. popupPosition = PopupPosition.TOP
  3002. }
  3003. if (index <= 3) {
  3004. popupPosition = PopupPosition.BOTTOM
  3005. }
  3006. let pup: XPopup
  3007. if (this.isDarkMode) {
  3008. pup = XPopup.Builder()
  3009. .setPopupPosition(popupPosition)
  3010. .atView(id)
  3011. .setMaxHeight('60%')
  3012. .setBackgroundColor(Color.Black)
  3013. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3014. .show();
  3015. } else {
  3016. pup = XPopup.Builder()
  3017. .setPopupPosition(popupPosition)
  3018. .atView(id)
  3019. .setMaxHeight('60%')
  3020. .setBackgroundColor(Color.White)
  3021. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3022. .show();
  3023. }
  3024. }
  3025. //重命名索引index的视频
  3026. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  3027. FileUtil.rename(oldPath, newPath).then(async () => {
  3028. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  3029. if (info.type === CommonConstants.TYPE_IS_DIR) {
  3030. //如果是文件夹先删除源数据,再添加新数据
  3031. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  3032. if (success) {
  3033. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  3034. } else {
  3035. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  3036. }
  3037. });
  3038. this.scanDirectory(newPath)
  3039. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  3040. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  3041. if (success) {
  3042. console.log(" onecold 重命名成功,数据库已同步");
  3043. } else {
  3044. console.error(" onecold 重命名数据库失败原因: " + error);
  3045. }
  3046. });
  3047. }
  3048. let mediaItem: VideoItem =
  3049. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3050. this.videoLocalList[index] = mediaItem;
  3051. }
  3052. this.cache.delete(this.currentPath)
  3053. this.getSortedFiles(this.currentPath, true)
  3054. }).catch((error: BusinessError) => {
  3055. console.error(error.message);
  3056. });
  3057. }
  3058. build() {
  3059. Stack() {
  3060. this.ContentBuild()
  3061. Stack() {
  3062. Column()
  3063. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  3064. height: '95%',
  3065. dragBar: true,
  3066. showClose: true,
  3067. blurStyle: BlurStyle.Thin,
  3068. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3069. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  3070. title: {
  3071. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  3072. + `(${this.getPlayListDisplayCount()}首)`
  3073. }
  3074. })
  3075. }
  3076. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  3077. modalTransition:ModalTransition.DEFAULT,
  3078. onWillDisappear: () => {
  3079. this.setShowPlayFalse()
  3080. },
  3081. })
  3082. }
  3083. .alignContent(Alignment.Bottom)
  3084. .width('100%')
  3085. .height('100%')
  3086. }
  3087. @Builder
  3088. ContentBuild() {
  3089. Scroll() {
  3090. Column() {
  3091. Stack() {
  3092. //libraryname加上去后onKeyEvent监听不了,因为目前的解决方案是上面的XComponent,去掉libraryname
  3093. XComponent({ id: 'for_onKeyEvent',type: XComponentType.SURFACE,
  3094. controller: this.xcomponentController })
  3095. .onLoad(async (event?: object) => {
  3096. })
  3097. .focusable(true)
  3098. .height(0)
  3099. .focusOnTouch(true)
  3100. .defaultFocus(true) // 自动获取键盘焦点
  3101. .onKeyEvent((event?: KeyEvent) => {
  3102. console.info('onecold点击 onKeyEvent')
  3103. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  3104. if (!event || event.type !== KeyType.Down) {
  3105. return;
  3106. }
  3107. console.info('onecold点击 onKeyEvent event.keyCode: ' + event.keyCode)
  3108. //空格键 Space key controls pause/play
  3109. if (event.keyCode === KeyCode.KEYCODE_SPACE|| event.keyCode === KeyCode.KEYCODE_MEDIA_PLAY_PAUSE) {
  3110. this.playOrPause()
  3111. }
  3112. if (event.keyCode === KeyCode.KEYCODE_DPAD_UP) {
  3113. this.playPrevious()
  3114. }
  3115. if (event.keyCode === KeyCode.KEYCODE_DPAD_DOWN) {
  3116. this.playNext()
  3117. }
  3118. // Right-click to fast forward
  3119. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  3120. this.fastForward()
  3121. }
  3122. // Left-click to rewind
  3123. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  3124. this.backForward()
  3125. }
  3126. })
  3127. Column() {
  3128. XComponent({
  3129. id: 'xcomponentId',
  3130. type: 'surface',
  3131. libraryname: 'ijkplayer_napi',
  3132. controller: this.xcomponentController
  3133. })
  3134. .onLoad((event?: object) => {
  3135. if (!!event) {
  3136. this.initDelayPlay(event);
  3137. }
  3138. })
  3139. .onDestroy(() => {
  3140. })
  3141. .width('100%')// .width(this.videoWidth)
  3142. .aspectRatio(this.videoAspectRatio)
  3143. }
  3144. .aspectRatio(this.videoAspectRatio)
  3145. .justifyContent(FlexAlign.Center)
  3146. .backgroundColor(Color.Transparent)
  3147. .visibility(Visibility.Hidden)
  3148. .height(CommonConstants.FULL_PERCENT)
  3149. .width(CommonConstants.FULL_PERCENT)
  3150. .bindSheet($$this.isABSheet, this.ABLoopSheet(), {
  3151. height:this.isLandscape?'80%': '43%',
  3152. dragBar: true,
  3153. showClose: true,
  3154. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  3155. blurStyle:BlurStyle.Thin,
  3156. backgroundColor:Color.Transparent,
  3157. title: { title: 'AB循环' }
  3158. })
  3159. Stack() {
  3160. Column() {
  3161. if(this.twoFingerType==4){
  3162. this.getWaterView()
  3163. }else{
  3164. if(this.isGridMusic){
  3165. this.getGridView()
  3166. }else {
  3167. this.getListView()
  3168. }
  3169. }
  3170. if (this.modeType ==0||this.modeType==4) {
  3171. Column() {
  3172. emptyView(this.themeColor)
  3173. }
  3174. .padding({ right:6 })
  3175. .onClick(()=>{
  3176. this.asyncCurrentPathOnlyFile()
  3177. })
  3178. .alignItems(HorizontalAlign.Center)
  3179. .position({ top: 200 })
  3180. .justifyContent(FlexAlign.Center)
  3181. .opacity(this.isZero ? 1 : 0)
  3182. .visibility(this.isZero&&!this.isLoadingPage && !this.isFavMusic && !this.isHistory
  3183. ? Visibility.Visible : Visibility.None)
  3184. .animation({
  3185. duration: 500,
  3186. curve: Curve.Friction // 可选动画曲线
  3187. })
  3188. .width('100%')
  3189. }
  3190. }
  3191. .layoutWeight(1)
  3192. .height('100%')
  3193. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  3194. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  3195. .onDrop((event?: DragEvent) => {
  3196. try {
  3197. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  3198. if (dragData !== undefined) {
  3199. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  3200. if (records.length > 0) {
  3201. for (let i = 0; i < records.length; i++) {
  3202. let types = records[i].getTypes();
  3203. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  3204. const fileUriUds =
  3205. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  3206. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  3207. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  3208. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  3209. this.targetFile = fileUriUds.oriUri;
  3210. this.saveVideoDatas([this.targetFile])
  3211. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  3212. }
  3213. }
  3214. }
  3215. } else {
  3216. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  3217. }
  3218. } else {
  3219. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  3220. }
  3221. } catch (error) {
  3222. const err = error as BusinessError;
  3223. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  3224. }
  3225. })
  3226. // 右侧居中的字母表索引
  3227. this.indexBuilder()
  3228. this.topTitleBar()
  3229. }
  3230. .alignContent(Alignment.Top)
  3231. .layoutWeight(1)
  3232. .height('100%')
  3233. Row() {
  3234. Button(this.isAllSelected ? '反选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  3235. .width(45)
  3236. .height(45)
  3237. .fontSize(10)
  3238. .margin({ top: 10, bottom: 10, right: 6 })
  3239. .backgroundColor(this.themeColor)
  3240. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3241. .onClick(() => {
  3242. if (this.isAllSelected) {
  3243. // 全不选
  3244. this.selectedFiles = [];
  3245. } else {
  3246. // 全选
  3247. this.selectedFiles = [...this.getCurFileList()];
  3248. }
  3249. this.isAllSelected = !this.isAllSelected;
  3250. })
  3251. Button('内嵌标签', { type: ButtonType.Capsule, stateEffect: true })
  3252. .width(72)
  3253. .height(45)
  3254. .fontSize(10)
  3255. .margin({ top: 10, bottom: 10, right: 6 })
  3256. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3257. .backgroundColor(this.themeColor)
  3258. .bindContentCover($$this.isOneKeyTags, this.TagsContentCoverBuilder(), {
  3259. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3260. })
  3261. .onClick(() => {
  3262. // if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  3263. this.isOneKeyTags = !this.isOneKeyTags
  3264. // }else{
  3265. // ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限批量内嵌标签,导入的时候请勾选复制一份。')
  3266. // }
  3267. })
  3268. Button('合并', { type: ButtonType.Circle, stateEffect: true })
  3269. .width(45)
  3270. .height(45)
  3271. .fontSize(10)
  3272. .margin({ top: 10, bottom: 10, right: 6 })
  3273. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3274. .backgroundColor(this.themeColor)
  3275. .bindContentCover($$this.isMergeAudio, this.MergeAudioBuilder(), {
  3276. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3277. })
  3278. .onClick(() => {
  3279. if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  3280. this.isMergeAudio = !this.isMergeAudio
  3281. }else{
  3282. ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限合并')
  3283. }
  3284. })
  3285. Button('+歌单', { type: ButtonType.Circle, stateEffect: true })
  3286. .width(45)
  3287. .height(45)
  3288. .fontSize(10)
  3289. .margin({ top: 10, bottom: 10, right: 6 })
  3290. .backgroundColor(this.themeColor)
  3291. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3292. .onClick(async () => {
  3293. this.longItemFilePath = ''
  3294. await this.openAddToPlaylistDialog(this.selectedFiles)
  3295. })
  3296. // Button('乱码', { type: ButtonType.Circle, stateEffect: true })
  3297. // .width(45)
  3298. // .height(45)
  3299. // .fontSize(10)
  3300. // .margin({ top: 10, bottom: 10, right: 6 })
  3301. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3302. // .backgroundColor(this.themeColor)
  3303. // .bindContentCover($$this.isFixMessy, this.FixMessyViewBuilder(), {
  3304. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3305. // })
  3306. // .onClick(() => {
  3307. // this.isFixMessy = !this.isFixMessy
  3308. // })
  3309. // Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  3310. // .width('35%')
  3311. // .height(60)
  3312. // .id('music_cut')
  3313. // .margin({ top: 10, bottom: 10, right: 6 })
  3314. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3315. // .backgroundColor(this.themeColor)
  3316. // .onClick(() => {
  3317. // this.showCutDialogForMultipleFiles(false, 'music_cut')
  3318. // })
  3319. //
  3320. // Button('移动', { type: ButtonType.Circle, stateEffect: true })
  3321. // .width('35%')
  3322. // .height(60)
  3323. // .id('music_cut_current')
  3324. // .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  3325. // .margin({ top: 10, bottom: 10, right: 6 })
  3326. // .backgroundColor(this.themeColor)
  3327. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3328. // .onClick(() => {
  3329. //
  3330. // this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  3331. // })
  3332. // Button('复制', { type: ButtonType.Circle, stateEffect: true })
  3333. // .width('35%')
  3334. // .height(60)
  3335. // .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  3336. // .margin({ top: 10, bottom: 10, right: 6 })
  3337. // .backgroundColor(this.themeColor)
  3338. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3339. // .onClick(() => {
  3340. // this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  3341. // })
  3342. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  3343. .width(45)
  3344. .height(45)
  3345. .fontSize(10)
  3346. .margin({ top: 10, bottom: 10, right: 6 })
  3347. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  3348. .backgroundColor(this.themeColor)
  3349. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3350. .onClick(() => {
  3351. this.showWarnIsDelete()
  3352. })
  3353. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  3354. .width(45)
  3355. .height(45)
  3356. .fontSize(10)
  3357. .margin({ top: 10, bottom: 10, right: 6 })
  3358. .backgroundColor(this.themeColor)
  3359. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3360. .onClick(() => {
  3361. this.selectedFiles = [];
  3362. this.isAllSelected = false
  3363. this.isMultiSelect = false
  3364. })
  3365. }
  3366. .width('100%')
  3367. .justifyContent(FlexAlign.Center)
  3368. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  3369. .opacity(this.isMultiSelect ? 1 : 0)
  3370. .animation({
  3371. duration: 666,
  3372. curve: 'ease-in-out' // 可选动画曲线
  3373. })
  3374. .position({ bottom: 20 }) // 将 Row 固定在底部
  3375. }
  3376. .width('100%')
  3377. .height('100%')
  3378. .alignContent(Alignment.Top)
  3379. }
  3380. .width('100%')
  3381. .height('100%')
  3382. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  3383. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  3384. .backgroundImagePosition(Alignment.Center)
  3385. .backdropBlur(this.blurValue)
  3386. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  3387. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  3388. }
  3389. }
  3390. //字母表索引
  3391. @Builder
  3392. indexBuilder(){
  3393. Column({space: 5}){
  3394. if(this.showZMIndex&&this.enableShowAlphabet){
  3395. if(this.isShowAlphaBet&&!(this.modeType==2&&!this.isCanBack)
  3396. &&!(this.modeType==3&&!this.isCanBack)&&(this.sortType==4||this.sortType==5)){
  3397. AlphabetIndexer({arrayValue: this.alphaBet,selected: this.selectAlphaBetIndex})
  3398. .attributeModifier(this.alphaBetStyle)
  3399. .usingPopup(this.isTouchingAlphaBet)
  3400. .onAreaChange((old_value,new_value)=>{
  3401. this.alphabetHeight = new_value.height as number
  3402. })
  3403. .popupPosition({
  3404. x: 40,
  3405. y: this.alphabetHeight / 2
  3406. })
  3407. .onSelect((index: number) => {
  3408. void this.onSelectIndexItem(this.alphaBet[index])
  3409. })
  3410. .onTouch((event: TouchEvent) =>{
  3411. this.showAlphabetIndex()
  3412. if(event.type === TouchType.Up || event.type === TouchType.Cancel){
  3413. this.isTouchingAlphaBet = false
  3414. this.hideAlphabetIndexAfterDelay(1500)
  3415. }else{
  3416. this.isTouchingAlphaBet = true
  3417. }
  3418. })
  3419. .transition(
  3420. TransitionEffect.translate({x: 10})
  3421. .combine(TransitionEffect.opacity(0.1))
  3422. .animation({
  3423. duration: 150,
  3424. curve: Curve.EaseInOut,
  3425. })
  3426. )
  3427. }
  3428. }
  3429. if(this.showFindLocation){
  3430. if(!(this.showZMIndex&&this.enableShowAlphabet)){
  3431. Blank()
  3432. .layoutWeight(1)
  3433. }
  3434. PointLightDefaultButton({
  3435. isSysBol:true,
  3436. pointColor:Color.Gray,
  3437. imageResource:$r('sys.symbol.local_fill'),
  3438. isPx: false,
  3439. builderHeight: 30,
  3440. builderWidth: 30,
  3441. })
  3442. .onClick(() =>{
  3443. void this.locateCurrentSong();
  3444. })
  3445. .clickEffect({level:ClickEffectLevel.LIGHT,scale: 0.5})
  3446. .margin({
  3447. bottom: this.bottomSafeHeight+100,right:10
  3448. })
  3449. }
  3450. }
  3451. .padding({
  3452. bottom: 0
  3453. })
  3454. .margin({right:5})
  3455. .position({x:'92%'})
  3456. .height('100%')
  3457. .justifyContent(FlexAlign.Center)
  3458. .bindSheet($$this.isEqualizerSheet, this.EqualizerSheet(), {
  3459. height: '100%',
  3460. dragBar: true,
  3461. showClose: true,
  3462. preferType: SheetType.CENTER ,
  3463. blurStyle: BlurStyle.Thin,
  3464. title: { title: '均衡器' },
  3465. onDisappear: () => {
  3466. this.isEqualizerSheet = false
  3467. }
  3468. })
  3469. }
  3470. async onSelectIndexItem(letter: string) {
  3471. await this.ensureFullListForAlphabetIndex();
  3472. const findTargetIndex = (): number => {
  3473. const songs = this.videoLocalList;
  3474. for (let i = 0; i < songs.length; i++) {
  3475. const song = songs[i];
  3476. let text = this.isShowFileName ? song.fileName :
  3477. (song.type != CommonConstants.TYPE_IS_DIR && song.pyStr) ? song.pyStr : song.name;
  3478. if (this.sortType === 0 || this.sortType == 1) {
  3479. text = song.artist;
  3480. } else if (this.sortType === 2 || this.sortType == 3) {
  3481. text = song.album;
  3482. }
  3483. if (text) {
  3484. const firstPinyin = getFirstLetter(text);
  3485. if (firstPinyin && firstPinyin === letter) {
  3486. return i;
  3487. }
  3488. }
  3489. }
  3490. return -1;
  3491. };
  3492. const targetIndex = findTargetIndex();
  3493. if (targetIndex !== -1) {
  3494. if (this.isGridMusic || this.twoFingerType == 4) {
  3495. this.scroller.scrollToIndex(targetIndex, false);
  3496. } else {
  3497. this.listScroller.scrollToIndex(targetIndex);
  3498. }
  3499. }
  3500. }
  3501. private showAlphabetIndex(): void {
  3502. this.isShowAlphaBet = true;
  3503. if (this.alphaBetHideTimer) {
  3504. clearTimeout(this.alphaBetHideTimer);
  3505. this.alphaBetHideTimer = 0;
  3506. }
  3507. }
  3508. private hideAlphabetIndexAfterDelay(delayMs: number): void {
  3509. if (this.alphaBetHideTimer) {
  3510. clearTimeout(this.alphaBetHideTimer);
  3511. }
  3512. this.alphaBetHideTimer = setTimeout(() => {
  3513. if (!this.isTouchingAlphaBet) {
  3514. this.isShowAlphaBet = false;
  3515. }
  3516. this.alphaBetHideTimer = 0;
  3517. }, delayMs) as number;
  3518. }
  3519. private scheduleAlphaBetRebuild(delayMs: number = 120): void {
  3520. if (!this.showZMIndex) {
  3521. return;
  3522. }
  3523. if (this.alphaBetRebuildTimer) {
  3524. clearTimeout(this.alphaBetRebuildTimer);
  3525. }
  3526. this.alphaBetRebuildTimer = setTimeout(() => {
  3527. this.alphaBetRebuildTimer = 0;
  3528. if (this.isScrolling) {
  3529. this.alphaBetDirty = true;
  3530. return;
  3531. }
  3532. this.alphaBetDirty = false;
  3533. void this.setAlphaBet();
  3534. }, delayMs) as number;
  3535. }
  3536. private markAlphaBetDirty(): void {
  3537. if (!this.showZMIndex) {
  3538. return;
  3539. }
  3540. if (this.isMediaLibraryWarmupWindow()) {
  3541. this.alphaBetDirty = true;
  3542. this.scheduleAlphaBetRebuild(900);
  3543. return;
  3544. }
  3545. this.alphaBetDirty = true;
  3546. if (!this.isScrolling) {
  3547. this.scheduleAlphaBetRebuild(80);
  3548. }
  3549. }
  3550. private async ensureFullListForAlphabetIndex(): Promise<void> {
  3551. if (this.isLoadingPage) {
  3552. return;
  3553. }
  3554. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  3555. return;
  3556. }
  3557. if (this.totalCount === 0 || this.videoLocalList.length >= this.totalCount) {
  3558. return;
  3559. }
  3560. if (this.modeType !== 0 && this.modeType !== 1) {
  3561. return;
  3562. }
  3563. this.isLoadingPage = true;
  3564. try {
  3565. const options: PageQueryOptions = {
  3566. pageIndex: 0,
  3567. pageSize: this.totalCount,
  3568. sortType: this.sortType,
  3569. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  3570. isShowFileName: this.isShowFileName
  3571. };
  3572. if (this.modeType === 0) {
  3573. options.parentPath = this.currentPath;
  3574. }
  3575. let result: PageQueryResult;
  3576. if (this.modeType === 0) {
  3577. result = await this.table.queryByParentPathPaged(options);
  3578. if (!this.isSearchMode) {
  3579. const directories: VideoItem[] = await this.loadDirectories(this.currentPath);
  3580. result.items = [...directories, ...result.items];
  3581. result.totalCount += directories.length;
  3582. }
  3583. } else {
  3584. result = await this.table.queryMediaLibraryPaged(options);
  3585. }
  3586. this.videoLocalList = result.items;
  3587. this.dataSource.pushArrayData(this.videoLocalList);
  3588. this.pageCache.clear();
  3589. this.pageHasMoreCache.clear();
  3590. this.pageTotalCountCache.clear();
  3591. this.prefetchingPages.clear();
  3592. this.currentPage = 0;
  3593. this.totalCount = result.totalCount;
  3594. this.hasMoreData = false;
  3595. this.lastScrollTriggerPage = -1;
  3596. this.lastVisibleEndIndex = -1;
  3597. this.isPagingTransition = false;
  3598. if (this.pagingScheduleTimer) {
  3599. clearTimeout(this.pagingScheduleTimer);
  3600. this.pagingScheduleTimer = 0;
  3601. }
  3602. if (this.modeType === 1) {
  3603. this.mediaKuCount = result.totalCount;
  3604. }
  3605. this.setButtonStatus();
  3606. this.markAlphaBetDirty();
  3607. } catch (err) {
  3608. const error = err as Error;
  3609. Logger.warn('heanup LocalMusic', `ensureFullListForAlphabetIndex error: ${error.message}`);
  3610. } finally {
  3611. this.isLoadingPage = false;
  3612. }
  3613. }
  3614. // 找到对应字母表的索引
  3615. findAlphaBetIndex(song: VideoItem):number{
  3616. let text = this.isShowFileName?song.fileName:
  3617. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  3618. if(this.sortType === 0||this.sortType==1){
  3619. text = song.artist
  3620. }else if(this.sortType === 2||this.sortType==3){
  3621. text = song.album
  3622. }
  3623. if(text){
  3624. let firstLetter = getFirstLetter(text)
  3625. for(let i=0;i<this.alphaBet.length;i++){
  3626. if(this.alphaBet[i] === firstLetter){
  3627. return i
  3628. }
  3629. }
  3630. }
  3631. return 0
  3632. }
  3633. private buildAlphaTaskItems(songs: Array<VideoItem>): Array<AlphaTaskItem> {
  3634. const items: Array<AlphaTaskItem> = []
  3635. for (const song of songs) {
  3636. items.push({
  3637. type: song.type,
  3638. name: song.name,
  3639. pyStr: song.pyStr,
  3640. fileName: song.fileName,
  3641. artist: song.artist,
  3642. album: song.album
  3643. })
  3644. }
  3645. return items
  3646. }
  3647. private async buildAlphaBetByTask(songs: Array<VideoItem>, version: number): Promise<void> {
  3648. const taskItems = this.buildAlphaTaskItems(songs)
  3649. const task = new taskpool.Task(buildAlphabetIndexTask, taskItems, this.sortType, this.isShowFileName)
  3650. const result = await taskpool.execute(task, taskpool.Priority.MEDIUM) as Array<string>
  3651. if (version !== this.alphaBetBuildVersion) {
  3652. return
  3653. }
  3654. this.alphaBet = result
  3655. if (this.videoLocalList.length > 0) {
  3656. this.selectAlphaBetIndex = 0
  3657. }
  3658. }
  3659. async setAlphaBet(){
  3660. if(!this.showZMIndex){
  3661. return
  3662. }
  3663. if (this.modeType === 1 && this.totalCount > this.videoLocalList.length) {
  3664. await this.refreshAlphaBetFromMediaLibrary()
  3665. return
  3666. }
  3667. try {
  3668. const songs = this.videoLocalList
  3669. if (songs.length > 40000) {
  3670. this.alphaBet = []
  3671. return
  3672. }
  3673. const version = ++this.alphaBetBuildVersion
  3674. await this.buildAlphaBetByTask(songs, version)
  3675. } catch (e) {
  3676. console.error('testTag','排序字母表出错',JSON.stringify(e))
  3677. }
  3678. }
  3679. private async refreshAlphaBetFromMediaLibrary(): Promise<void> {
  3680. if (this.totalCount <= 0) {
  3681. return
  3682. }
  3683. if (this.totalCount > 40000) {
  3684. this.alphaBet = []
  3685. return
  3686. }
  3687. const keyword = this.isSearchMode ? this.searchText : ''
  3688. const cacheKey = `${this.modeType}-${this.sortType}-${this.isShowFileName}-${keyword}-${this.totalCount}`
  3689. if (this.alphaBetCacheKey === cacheKey && this.alphaBet.length > 0) {
  3690. return
  3691. }
  3692. const result = await this.table.queryMediaLibraryPaged({
  3693. pageIndex: 0,
  3694. pageSize: this.totalCount,
  3695. sortType: this.sortType,
  3696. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  3697. isShowFileName: this.isShowFileName
  3698. })
  3699. const version = ++this.alphaBetBuildVersion
  3700. await this.buildAlphaBetByTask(result.items, version)
  3701. this.alphaBetCacheKey = cacheKey
  3702. }
  3703. @Builder
  3704. topTitleBar(){
  3705. Column() {
  3706. Row({ space: 15 }) {
  3707. if (!this.isSearchMode ) {
  3708. //左侧滑动按钮
  3709. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3710. SymbolGlyph(this.rightTopImage)
  3711. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3712. }
  3713. .attributeModifier(new ButtonFancyModifier(40, 40))
  3714. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3715. .animation({ duration: 300, curve: Curve.Ease })
  3716. .onClick(() => {
  3717. this.triggerSwipeBackWithAnimation()
  3718. })
  3719. .attributeModifier(new ShadowModifier())
  3720. .zIndex(0)
  3721. }else{
  3722. //左侧搜索返回按钮
  3723. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3724. SymbolGlyph($r('sys.symbol.chevron_left'))
  3725. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3726. }
  3727. .attributeModifier(new ButtonFancyModifier(40, 40))
  3728. .margin({bottom:5})
  3729. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3730. .animation({ duration: 300, curve: Curve.Ease })
  3731. .onClick(() => {
  3732. this.isSearchMode = false
  3733. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  3734. this.searchText = ''
  3735. this.getSortedFiles(this.currentPath)
  3736. return
  3737. }
  3738. this.onSearchInput('')
  3739. })
  3740. .attributeModifier(new ShadowModifier())
  3741. .zIndex(0)
  3742. }
  3743. if (!this.isSearchMode) {
  3744. Text(this.modeType==1?`${this.titleName}(${this.mediaKuCount}首)`:this.titleName)
  3745. .margin({left:3,right:10})
  3746. .fontColor($r('app.color.text_color'))
  3747. .fontSize(this.twoFingerType==3?17:16)
  3748. .maxLines(1)
  3749. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3750. .layoutWeight(1)
  3751. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3752. }
  3753. //搜索框
  3754. Search({ controller: this.searchController,value: this.searchText, placeholder: '搜索标题、艺术家...' })
  3755. .searchButton('搜索',{fontColor:this.themeColor})
  3756. .searchIcon({
  3757. src: $r('sys.media.ohos_ic_public_search_filled')
  3758. })
  3759. .cancelButton({
  3760. style: CancelButtonStyle.CONSTANT,
  3761. icon: {
  3762. src: $r('sys.media.ohos_ic_public_cancel_filled')
  3763. }
  3764. })
  3765. .layoutWeight(1)
  3766. .height(40)
  3767. .maxLength(20)
  3768. .backgroundColor(this.isDarkMode?Color.Black:'#F5F5F5')
  3769. .placeholderColor(Color.Grey)
  3770. .placeholderFont({ size: 14, weight: 400 })
  3771. .textFont({ size: 14, weight: 400 })
  3772. .onSubmit((value: string) => {
  3773. console.log('onecold onSubmit ='+value)
  3774. this.searchController.stopEditing()
  3775. if(this.modeType==0){
  3776. this.modeType =1//如果是首页 切换到媒体库搜索
  3777. }
  3778. this.onSearchInput(this.searchText);
  3779. })
  3780. .onChange((value: string) => {
  3781. console.log('onecold onChange ='+value)
  3782. if(this.modeType==0){
  3783. this.modeType =1//如果是首页 切换到媒体库搜索
  3784. }
  3785. this.onSearchInput(value);
  3786. })
  3787. .visibility(this.isSearchMode?Visibility.Visible:Visibility.None)
  3788. .animation({ duration: 300, curve: Curve.Ease })
  3789. //搜索按钮
  3790. if (!this.isSearchMode) {
  3791. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3792. SymbolGlyph($r('sys.symbol.magnifyingglass'))
  3793. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3794. }
  3795. .attributeModifier(new ButtonFancyModifier(40, 40))
  3796. .animation({ duration: 300, curve: Curve.Ease })
  3797. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3798. .attributeModifier(new ShadowModifier())
  3799. .zIndex(0)
  3800. .onClick(()=>{
  3801. this.isSearchMode = true
  3802. })
  3803. //排序按钮
  3804. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3805. SymbolGlyph($r('sys.symbol.list_number'))
  3806. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3807. }
  3808. .attributeModifier(new ButtonFancyModifier(40, 40))
  3809. .animation({ duration: 300, curve: Curve.Ease })
  3810. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3811. .bindMenu((this.modeType==2&&!this.isCanBack)||(this.modeType==3&&!this.isCanBack)
  3812. ?this.SortMenuForArtistAblumBuilder:this.SortMenuBuilder)
  3813. .attributeModifier(new ShadowModifier())
  3814. .zIndex(0)
  3815. //添加按钮
  3816. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3817. SymbolGlyph($r('sys.symbol.plus'))
  3818. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3819. }
  3820. .attributeModifier(new ButtonFancyModifier(40, 40))
  3821. .animation({ duration: 300, curve: Curve.Ease })
  3822. .visibility(this.modeType==0||this.modeType==1?Visibility.Visible:Visibility.None)
  3823. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3824. .bindSheet($$this.showAddSheet, this.addSheet(), {
  3825. height: SheetSize.FIT_CONTENT,
  3826. dragBar: true,
  3827. showClose: true,
  3828. preferType: SheetType.CENTER ,
  3829. title: {
  3830. title: '导入音乐'
  3831. }
  3832. })
  3833. .onClick(() => {
  3834. this.showAddSheet = !this.showAddSheet;
  3835. })
  3836. .attributeModifier(new ShadowModifier())
  3837. .zIndex(0)
  3838. }
  3839. }
  3840. }
  3841. .padding({ top: this.topSafeHeight+10, left: 10, right: 10 })
  3842. .width('100%')
  3843. .translate({
  3844. x: 0,
  3845. y: (this.isShowTitleBar || !this.autoHideTitle) ? 0 : -80
  3846. })
  3847. .opacity((this.isShowTitleBar || !this.autoHideTitle) ? 1 : 0)
  3848. .animation({
  3849. duration: 240,
  3850. curve: Curve.EaseInOut
  3851. })
  3852. }
  3853. @Builder
  3854. addSheet() {
  3855. Scroll() {
  3856. Column() {
  3857. Column() {
  3858. Row() {
  3859. SymbolGlyph($r('sys.symbol.info_circle'))
  3860. .fontSize(22)
  3861. .fontColor([this.themeColor])
  3862. .alignSelf(ItemAlign.Center)
  3863. .margin({ left: 8 })
  3864. Text('导入音乐复制到DownLoad目录')
  3865. .margin({ left: 8 })
  3866. .fontSize(14)
  3867. .fontColor($r('app.color.text_color'))
  3868. .fontWeight(480)
  3869. .layoutWeight(1)
  3870. Toggle({ type: ToggleType.Switch, isOn: this.isCopyFileToDownLoad })
  3871. .selectedColor(this.themeColor)
  3872. .switchPointColor(Color.White)
  3873. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  3874. .margin({ right: 2 })
  3875. .onChange((checked: boolean) => {
  3876. this.isCopyFileToDownLoad = checked;
  3877. PreferencesUtil.put(SettingPage.IS_COPYFILE_TO_DOWNLOAD, this.isCopyFileToDownLoad)
  3878. })
  3879. .width(50)
  3880. .height(30);
  3881. }
  3882. .height(72)
  3883. .padding({ left:8,right:8 })
  3884. }
  3885. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3886. .backgroundColor($r('app.color.start_window_background'))
  3887. .borderRadius(15)
  3888. .width('85%')
  3889. .margin({
  3890. top: 10,
  3891. bottom: 10
  3892. })
  3893. .padding(0)
  3894. .border({
  3895. color: Color.White,
  3896. width: 1.8
  3897. })
  3898. Menu() {
  3899. MenuItem({
  3900. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder_badge_plus')),
  3901. content: "新建文件夹"
  3902. })
  3903. .backgroundColor($r('app.color.silvery'))
  3904. .border({
  3905. width: { bottom: 1 },
  3906. color: '#12ec5c87'
  3907. })
  3908. .margin(10)
  3909. .height(60)
  3910. .padding({left:15,right:15})
  3911. .onClick(async () => {
  3912. this.showMkDialog()
  3913. this.showAddSheet = !this.showAddSheet
  3914. })
  3915. MenuItem({
  3916. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder')),
  3917. content: $r('app.string.import_from_files')
  3918. })
  3919. .padding({left:15,right:15})
  3920. .backgroundColor($r('app.color.silvery'))
  3921. .border({
  3922. width: { bottom: 1 },
  3923. color: '#12ec5c87'
  3924. })
  3925. .margin(10)
  3926. .height(60)
  3927. .onClick(async () => {
  3928. this.callFilePickerSelectFile()
  3929. this.showAddSheet = !this.showAddSheet
  3930. })
  3931. MenuItem({
  3932. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square')),
  3933. content: '全选导入'
  3934. // content: '从下载文件夹导入(路径:Download/' +
  3935. // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
  3936. })
  3937. .padding({left:15,right:15})
  3938. .backgroundColor($r('app.color.silvery'))
  3939. .border({
  3940. width: { bottom: 1 },
  3941. color: '#12ec5c87'
  3942. })
  3943. .margin(10)
  3944. .height(60)
  3945. .onClick(async () => {
  3946. this.goSelectMusic()
  3947. this.showAddSheet = !this.showAddSheet
  3948. })
  3949. MenuItem({
  3950. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.save')),
  3951. content: '自动导入教程'
  3952. })
  3953. .padding({left:15,right:15})
  3954. .backgroundColor($r('app.color.silvery'))
  3955. .border({
  3956. width: { bottom: 1 },
  3957. color: '#12ec5c87'
  3958. })
  3959. .margin(10)
  3960. .height(60)
  3961. .onClick(async () => {
  3962. this.showTips()
  3963. this.showAddSheet = !this.showAddSheet
  3964. })
  3965. MenuItem({
  3966. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.questionmark_circle')),
  3967. content: '导入疑问'
  3968. })
  3969. .height(60)
  3970. .padding({left:15,right:15})
  3971. .backgroundColor($r('app.color.silvery'))
  3972. .border({
  3973. width: { bottom: 1 },
  3974. color: '#12ec5c87'
  3975. })
  3976. .margin(10)
  3977. .onClick(async () => {
  3978. this.showProblomTips()
  3979. this.showAddSheet = !this.showAddSheet
  3980. })
  3981. }.attributeModifier(new MenuModifier())
  3982. .margin({bottom:30})
  3983. .width('90%')
  3984. .borderRadius(15)
  3985. }
  3986. .layoutWeight(1)
  3987. }
  3988. }
  3989. async showProblomTips() {
  3990. try {
  3991. this.getUIContext().getPromptAction().showDialog({
  3992. title: '导入疑问',
  3993. message:'为什么有些歌曲导入成功后,内嵌标签或者其他功能不能用?:\n\n1、由于鸿蒙系统的安全策略,文件权限不够,请将文件移动到Download/天天静听目录下。' +
  3994. '这样内嵌标签功能就没有权限问题。\n\n2、导入可以也选择不复制,这样可以省略空间。\n\n',
  3995. buttons: [
  3996. {
  3997. text: '知道了',
  3998. color: '#000000'
  3999. },
  4000. ]
  4001. }, (err, data) => {
  4002. if (err) {
  4003. console.error('showDialog err: ' + err);
  4004. return;
  4005. }
  4006. console.info('showDialog success callback, click button: ' + data.index);
  4007. });
  4008. } catch (error) {
  4009. let message = (error as BusinessError).message;
  4010. let code = (error as BusinessError).code;
  4011. console.error(`showDialog args error code is ${code}, message is ${message}`);
  4012. };
  4013. }
  4014. @Builder
  4015. TagsContentCoverBuilder() {
  4016. Scroll() {
  4017. Column() {
  4018. TagsContentCover(
  4019. {
  4020. selectedFiles:this.selectedFiles,
  4021. isOneKeyTags:this.isOneKeyTags,
  4022. onSeePath:(path:string)=>{
  4023. this.modeType = 0
  4024. this.deleteCache(path)
  4025. this.getSortedFiles(path)
  4026. },
  4027. onTagsResult:(result: boolean,deleteCache_path?:string)=>{
  4028. this.isMultiSelect = false
  4029. if(result){//如果嵌入成功,更新数据
  4030. this.listRefreshKey++
  4031. setTimeout(()=>{
  4032. this.doUpdateData()
  4033. },500)
  4034. }
  4035. console.info('onecold onTagsResult deleteCache_path =' +deleteCache_path)
  4036. if(deleteCache_path){
  4037. this.deleteCache(deleteCache_path)
  4038. }
  4039. }
  4040. }
  4041. )
  4042. }
  4043. }
  4044. .width('100%')
  4045. .height('100%')
  4046. }
  4047. @Builder
  4048. FixMessyViewBuilder() {
  4049. Scroll() {
  4050. Column() {
  4051. FixMessyView(
  4052. {
  4053. selectedFiles:this.selectedFiles,
  4054. isFixMessy:this.isFixMessy,
  4055. onFixResult:(result: boolean)=>{
  4056. this.isMultiSelect = false
  4057. if(result){//如果嵌入成功,更新数据
  4058. this.deleteCache(this.currentPath)
  4059. this.doUpdateData()
  4060. }
  4061. }
  4062. }
  4063. )
  4064. }
  4065. }
  4066. .width('100%')
  4067. .height('100%')
  4068. }
  4069. //剪辑音频
  4070. @Builder
  4071. EditAudioBuilder(item:VideoItem) {
  4072. Scroll() {
  4073. Column() {
  4074. EditAudio(
  4075. {
  4076. mVideoItem:item,
  4077. currentPath:this.currentPath,
  4078. videoUrl:this.videoUrl,
  4079. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4080. currentTime:this.currentTime,
  4081. progressValue:this.progressValue,
  4082. onBack:()=>{
  4083. this.isEditAudio = !this.isEditAudio
  4084. },
  4085. onSeeOutputPath:(outPutPath:string)=>{
  4086. this.isEditAudio = !this.isEditAudio
  4087. this.longItemFilePath = ''
  4088. this.modeType = 0
  4089. this.isShowFileName = true
  4090. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4091. },
  4092. onPlayOrPause:()=>{
  4093. if(this.videoUrl==item.filePath){
  4094. this.playOrPause()
  4095. }else{//如果不是当前播放的,则播放该文件
  4096. this.videoUrl==item.filePath
  4097. this.doPlay(item,0,false,true)
  4098. }
  4099. },
  4100. onSliderChange:(value:number)=>{
  4101. if(this.videoUrl!=item.filePath){
  4102. this.videoUrl==item.filePath
  4103. return
  4104. }
  4105. this.isSeekTo = true;
  4106. this.mDestroyPage = false;
  4107. this.showLoadIng();
  4108. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  4109. let seekValue = value * (this.getActiveDuration() / 100);
  4110. this.seekTo(seekValue + "");
  4111. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  4112. this.isSeekTo = false;
  4113. },
  4114. onResult:(result: boolean,outPath:string)=>{
  4115. if(result){//如果剪辑成功,更新数据
  4116. this.doUpdateData()
  4117. }else{
  4118. ToastUtil.showToast('剪辑失败')
  4119. }
  4120. }
  4121. }
  4122. )
  4123. }
  4124. }
  4125. .width('100%')
  4126. .height('100%')
  4127. }
  4128. //提取伴奏
  4129. @Builder
  4130. ConverterBuilder(item:VideoItem) {
  4131. Scroll() {
  4132. Column() {
  4133. AudioFormatConverter(
  4134. {
  4135. mVideoItem:item,
  4136. videoUrl:this.videoUrl,
  4137. currentPath:this.currentPath,
  4138. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4139. currentTime:this.currentTime,
  4140. progressValue:this.progressValue,
  4141. onBack:()=>{
  4142. this.isConverter = !this.isConverter
  4143. this.longItemFilePath = ''
  4144. },
  4145. onPlayOrPause:()=>{
  4146. if(this.videoUrl==item.filePath){
  4147. this.playOrPause()
  4148. }else{//如果不是当前播放的,则播放该文件
  4149. this.videoUrl==item.filePath
  4150. this.doPlay(item,0,false,true)
  4151. }
  4152. },
  4153. onSeeOutputPath:(outPutPath:string)=>{
  4154. this.isConverter = !this.isConverter
  4155. this.longItemFilePath = ''
  4156. this.modeType = 0
  4157. this.isShowFileName = true
  4158. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4159. },
  4160. onSliderChange:(value:number)=>{
  4161. if(this.videoUrl!=item.filePath){
  4162. this.videoUrl==item.filePath
  4163. return
  4164. }
  4165. this.isSeekTo = true;
  4166. this.mDestroyPage = false;
  4167. this.showLoadIng();
  4168. let seekValue = value * (this.getActiveDuration() / 100);
  4169. this.seekTo(seekValue + "");
  4170. this.isSeekTo = false;
  4171. },
  4172. onResult:(result: boolean,outPath:string)=>{
  4173. if(result){//如果成功,更新数据
  4174. this.doUpdateData()
  4175. }else{
  4176. ToastUtil.showToast('格式转化失败')
  4177. }
  4178. }
  4179. }
  4180. )
  4181. }
  4182. }
  4183. .width('100%')
  4184. .height('100%')
  4185. }
  4186. //提取伴奏
  4187. @Builder
  4188. ExtractAccBuilder(item:VideoItem) {
  4189. Scroll() {
  4190. Column() {
  4191. ExtractAccompaniment(
  4192. {
  4193. mVideoItem:item,
  4194. currentPath:this.currentPath,
  4195. videoUrl:this.videoUrl,
  4196. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4197. currentTime:this.currentTime,
  4198. progressValue:this.progressValue,
  4199. onBack:()=>{
  4200. this.isExtractAcc = !this.isExtractAcc
  4201. this.longItemFilePath = ''
  4202. },
  4203. onPlayOrPause:()=>{
  4204. if(this.videoUrl==item.filePath){
  4205. this.playOrPause()
  4206. }else{//如果不是当前播放的,则播放该文件
  4207. this.videoUrl==item.filePath
  4208. this.doPlay(item,0,false,true)
  4209. }
  4210. },
  4211. onSeeOutputPath:(outPutPath:string)=>{
  4212. this.isExtractAcc = !this.isExtractAcc
  4213. this.longItemFilePath = ''
  4214. this.modeType = 0
  4215. this.isShowFileName = true
  4216. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4217. },
  4218. onSliderChange:(value:number)=>{
  4219. if(this.videoUrl!=item.filePath){
  4220. this.videoUrl==item.filePath
  4221. return
  4222. }
  4223. this.isSeekTo = true;
  4224. this.mDestroyPage = false;
  4225. this.showLoadIng();
  4226. let seekValue = value * (this.getActiveDuration() / 100);
  4227. this.seekTo(seekValue + "");
  4228. this.isSeekTo = false;
  4229. },
  4230. onResult:(result: boolean,outPath:string)=>{
  4231. if(result){//如果成功,更新数据
  4232. this.doUpdateData()
  4233. }else{
  4234. ToastUtil.showToast('提取伴奏失败')
  4235. }
  4236. }
  4237. }
  4238. )
  4239. }
  4240. }
  4241. .width('100%')
  4242. .height('100%')
  4243. }
  4244. //AI人声分离
  4245. @Builder
  4246. AiBuilder(item:VideoItem) {
  4247. Scroll() {
  4248. Column() {
  4249. AIVoiceSeparation(
  4250. {
  4251. mVideoItem:item,
  4252. videoUrl:this.videoUrl,
  4253. currentPath:this.currentPath,
  4254. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4255. currentTime:this.currentTime,
  4256. progressValue:this.progressValue,
  4257. onBack:()=>{
  4258. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  4259. this.longItemFilePath = ''
  4260. },
  4261. onPlayOrPause:()=>{
  4262. if(this.videoUrl==item.filePath||this.isPlaying){
  4263. this.playOrPause()
  4264. }else{//如果不是当前播放的,则播放该文件
  4265. this.videoUrl==item.filePath
  4266. this.doPlay(item,0,false,true)
  4267. }
  4268. },
  4269. onPlayPath:(path:string)=>{
  4270. this.videoUrl==path
  4271. const itemP = Utility.getItemByFilePath(this.videoLocalList,path)
  4272. if(itemP)
  4273. this.doPlay(itemP,0,false,true)
  4274. },
  4275. onSeeOutputPath:(outPutPath:string)=>{
  4276. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  4277. this.longItemFilePath = ''
  4278. this.modeType = 0
  4279. this.isShowFileName = true
  4280. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4281. },
  4282. onSliderChange:(value:number)=>{
  4283. if(this.videoUrl!=item.filePath){
  4284. this.videoUrl==item.filePath
  4285. return
  4286. }
  4287. this.isSeekTo = true;
  4288. this.mDestroyPage = false;
  4289. this.showLoadIng();
  4290. let seekValue = value * (this.getActiveDuration() / 100);
  4291. this.seekTo(seekValue + "");
  4292. this.isSeekTo = false;
  4293. },
  4294. onResult:(result: boolean,outPath:string)=>{
  4295. if(result){//如果成功,更新数据
  4296. this.doUpdateData()
  4297. }else{
  4298. ToastUtil.showToast('Ai人声分离失败')
  4299. }
  4300. }
  4301. }
  4302. )
  4303. }
  4304. }
  4305. .width('100%')
  4306. .height('100%')
  4307. }
  4308. //变速变调
  4309. @Builder
  4310. ChangeToneBuilder(item:VideoItem) {
  4311. Scroll() {
  4312. Column() {
  4313. ChangeTone(
  4314. {
  4315. mVideoItem:item,
  4316. currentPath:this.currentPath,
  4317. videoUrl:this.videoUrl,
  4318. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4319. currentTime:this.currentTime,
  4320. progressValue:this.progressValue,
  4321. onBack:()=>{
  4322. this.isChangeTone = !this.isChangeTone
  4323. this.longItemFilePath = ''
  4324. },
  4325. onPlayOrPause:()=>{
  4326. if(this.videoUrl==item.filePath){
  4327. this.playOrPause()
  4328. }else{//如果不是当前播放的,则播放该文件
  4329. this.videoUrl==item.filePath
  4330. this.doPlay(item,0,false,true)
  4331. }
  4332. },
  4333. onSeeOutputPath:(outPutPath:string)=>{
  4334. this.isChangeTone = !this.isChangeTone
  4335. this.longItemFilePath = ''
  4336. this.modeType = 0
  4337. this.isShowFileName = true
  4338. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4339. },
  4340. onSliderChange:(value:number)=>{
  4341. if(this.videoUrl!=item.filePath){
  4342. this.videoUrl==item.filePath
  4343. return
  4344. }
  4345. this.isSeekTo = true;
  4346. this.mDestroyPage = false;
  4347. this.showLoadIng();
  4348. let seekValue = value * (this.getActiveDuration() / 100);
  4349. this.seekTo(seekValue + "");
  4350. this.isSeekTo = false;
  4351. },
  4352. onResult:(result: boolean,outPath:string)=>{
  4353. if(result){//如果成功,更新数据
  4354. this.doUpdateData()
  4355. }else{
  4356. ToastUtil.showToast('变速变调失败')
  4357. }
  4358. }
  4359. }
  4360. )
  4361. }
  4362. }
  4363. .width('100%')
  4364. .height('100%')
  4365. }
  4366. //提取视频中的音频
  4367. @Builder
  4368. extractAudioFromVideoBuilder(item:VideoItem) {
  4369. Scroll() {
  4370. Column() {
  4371. ExtractAudioFromVideo(
  4372. {
  4373. mVideoItem:item,
  4374. currentPath:this.currentPath,
  4375. videoUrl:this.videoUrl,
  4376. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4377. currentTime:this.currentTime,
  4378. progressValue:this.progressValue,
  4379. onBack:()=>{
  4380. this.isExtractAudio = !this.isExtractAudio
  4381. this.longItemFilePath = ''
  4382. },
  4383. onPlayOrPause:()=>{
  4384. if(this.videoUrl==item.filePath){
  4385. this.playOrPause()
  4386. }else{//如果不是当前播放的,则播放该文件
  4387. this.videoUrl==item.filePath
  4388. this.doPlay(item,0,false,true)
  4389. }
  4390. },
  4391. onSeeOutputPath:(outPutPath:string)=>{
  4392. this.isExtractAudio = !this.isExtractAudio
  4393. this.longItemFilePath = ''
  4394. this.modeType = 0
  4395. this.isShowFileName = true
  4396. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4397. },
  4398. onSliderChange:(value:number)=>{
  4399. if(this.videoUrl!=item.filePath){
  4400. this.videoUrl==item.filePath
  4401. return
  4402. }
  4403. this.isSeekTo = true;
  4404. this.mDestroyPage = false;
  4405. this.showLoadIng();
  4406. let seekValue = value * (this.getActiveDuration() / 100);
  4407. this.seekTo(seekValue + "");
  4408. this.isSeekTo = false;
  4409. },
  4410. onResult:(result: boolean,outPath:string)=>{
  4411. if(result){//如果成功,更新数据
  4412. this.doUpdateData()
  4413. }else{
  4414. ToastUtil.showToast('提取音频失败')
  4415. }
  4416. }
  4417. }
  4418. )
  4419. }
  4420. }
  4421. .width('100%')
  4422. .height('100%')
  4423. }
  4424. //合并音频
  4425. @Builder
  4426. MergeAudioBuilder() {
  4427. Scroll() {
  4428. Column() {
  4429. MergeAudio(
  4430. {
  4431. videoUrl:this.videoUrl,
  4432. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4433. currentPath:this.currentPath,
  4434. selectedFiles:this.selectedFiles,
  4435. currentTime:this.currentTime,
  4436. progressValue:this.progressValue,
  4437. onBack:()=>{
  4438. this.isMergeAudio = !this.isMergeAudio
  4439. this.longItemFilePath = ''
  4440. },
  4441. // onPlayPath:(path:string)=>{
  4442. // if(this.videoUrl==item.filePath){
  4443. // this.playOrPause()
  4444. // }else{//如果不是当前播放的,则播放该文件
  4445. // this.videoUrl==item.filePath
  4446. // this.doPlay(item,0,false,true)
  4447. // }
  4448. //
  4449. // },
  4450. onSeeOutputPath:(outPutPath:string)=>{
  4451. this.isMergeAudio = !this.isMergeAudio
  4452. this.longItemFilePath = ''
  4453. this.modeType = 0
  4454. this.isShowFileName = true
  4455. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4456. },
  4457. onResult:(result: boolean,outPath:string)=>{
  4458. if(result){//如果成功,更新数据
  4459. this.doUpdateData()
  4460. }else{
  4461. if(this.selectedFiles.length>=3){
  4462. ToastUtil.showToast('合并数量太多导致失败')
  4463. }else{
  4464. ToastUtil.showToast('合并失败')
  4465. }
  4466. }
  4467. }
  4468. }
  4469. )
  4470. }
  4471. }
  4472. .width('100%')
  4473. .height('100%')
  4474. }
  4475. asyncCurrentPathData() {
  4476. if (this.modeType == 0) {
  4477. workerInstance.postMessage({
  4478. code: 1,
  4479. data1: this.context,
  4480. data2: this.currentPath,
  4481. data3: this.lockPath,
  4482. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  4483. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  4484. });
  4485. }
  4486. }
  4487. // 处理文件选择的函数
  4488. handleFileSelection(item: VideoItem, checked: boolean) {
  4489. if (checked) {
  4490. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  4491. this.selectedFiles.push(item);
  4492. }
  4493. } else {
  4494. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  4495. if (index > -1) {
  4496. this.selectedFiles.splice(index, 1);
  4497. }
  4498. }
  4499. }
  4500. private deleteComponentId: number = 0
  4501. //多选删除文件
  4502. showWarnIsDelete(){
  4503. this.getUIContext().getPromptAction().openCustomDialog({
  4504. builder: () => {
  4505. this.deleteComptentBuilder()
  4506. },
  4507. isModal:true,
  4508. showInSubWindow:false,
  4509. maskColor: Color.Transparent,
  4510. dialogTransition: // 设置弹窗内容显示的过渡效果
  4511. TransitionEffect.translate({ x: 0, y: 290, z: 0 })
  4512. .animation({ duration: 600, curve: Curve.Smooth }),
  4513. maskTransition: // 设置蒙层显示的过渡效果
  4514. TransitionEffect.opacity(0)
  4515. .animation({ duration: 600, curve: Curve.Smooth })
  4516. }).then((dialogId: number) => {
  4517. this.deleteComponentId = dialogId
  4518. })
  4519. .catch((error: BusinessError) => {
  4520. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  4521. })
  4522. }
  4523. @Builder
  4524. deleteComptentBuilder(){
  4525. DeleteComptent({
  4526. selectedFiles:this.selectedFiles,
  4527. isPlaylistMode: this.modeType == 4,
  4528. playlistId: this.currentSongListID,
  4529. onCancel:()=>{
  4530. this.isMultiSelect = false
  4531. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  4532. },
  4533. onDeleteResult:(result: boolean)=>{
  4534. this.isMultiSelect = false
  4535. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  4536. if(result){//如果删除成功,更新数据
  4537. this.selectedFiles = [];
  4538. this.isAllSelected = false
  4539. if (this.modeType == 4) {
  4540. this.doSongListTask()
  4541. } else {
  4542. this.cache.delete(this.currentPath);
  4543. this.getSortedFiles(this.currentPath, true);
  4544. }
  4545. }
  4546. }
  4547. })
  4548. }
  4549. //多选移动文件
  4550. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  4551. Logger.info('onecold showCutDialogForMultipleFiles')
  4552. let mList: Array<string> = []
  4553. let rPath = this.rootPath
  4554. if (isCurrent) {
  4555. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  4556. rPath = this.currentPath
  4557. } else {
  4558. mList = Utility.getNameList(this.dirList);
  4559. rPath = this.rootPath
  4560. }
  4561. let dataBean = new BubbleBean();
  4562. dataBean.data = mList;
  4563. dataBean.color = this.themeColor
  4564. dataBean.onItemClick = (i) => {
  4565. const newDirPath = rPath + '/' + mList[i];
  4566. // Logger.info('newDirPath = ' + newDirPath)
  4567. this.selectedFiles.forEach((item) => {
  4568. const newPath = newDirPath + '/' + item.fileName;
  4569. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  4570. ToastUtil.showToast('移动成功');
  4571. this.table.deleteData(item, () => {
  4572. this.cache.delete(this.currentPath); // 删除原路径缓存
  4573. this.cache.delete(newDirPath); // 删除目标路径缓存
  4574. this.getSortedFiles(this.currentPath, true);
  4575. });
  4576. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  4577. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  4578. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  4579. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  4580. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  4581. this.table.insert(newItem, (id: number) => {
  4582. //加入数据库
  4583. });
  4584. }
  4585. }).catch((error: Error) => {
  4586. console.error(error.message);
  4587. });
  4588. });
  4589. this.isMultiSelect = false
  4590. this.selectedFiles = [];
  4591. this.isAllSelected = false
  4592. XPopup.dismissTop();
  4593. };
  4594. let pup: XPopup
  4595. if (this.isDarkMode) {
  4596. pup = XPopup.Builder()
  4597. .setPopupPosition(PopupPosition.TOP)
  4598. .atView(viewId)
  4599. .setBackgroundColor(Color.Black)
  4600. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4601. .show();
  4602. } else {
  4603. pup = XPopup.Builder()
  4604. .setPopupPosition(PopupPosition.TOP)
  4605. .atView(viewId)
  4606. .setBackgroundColor(Color.White)
  4607. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4608. .show();
  4609. }
  4610. }
  4611. /**
  4612. * 加载所有歌单
  4613. */
  4614. async loadAllPlaylists() {
  4615. try {
  4616. this.allPlaylists = await this.playlistTable?.queryAllPlaylists()!
  4617. LogUtil.info('heanup Loaded playlists: ' + this.allPlaylists.length)
  4618. } catch (error) {
  4619. LogUtil.error('heaunp Failed to load playlists: ' + error.message)
  4620. }
  4621. }
  4622. /**
  4623. * 显示添加到歌单对话框
  4624. */
  4625. async openAddToPlaylistDialog(items: VideoItem | VideoItem[]) {
  4626. const songs = Array.isArray(items) ? items : [items]
  4627. const musicItems = songs.filter(song => song.type !== CommonConstants.TYPE_IS_DIR)
  4628. if (musicItems.length === 0) {
  4629. ToastUtil.showToast('请选择要添加的歌曲')
  4630. return
  4631. }
  4632. // 加载最新的歌单列表
  4633. await this.loadAllPlaylists()
  4634. showAddToPlaylistDialog(
  4635. musicItems,
  4636. this.allPlaylists,
  4637. async (playlistId: string) => {
  4638. // 添加歌曲到歌单
  4639. const success = await this.playlistTable?.addSongsToPlaylist(playlistId,
  4640. musicItems.map(song => song.filePath))
  4641. if (success) {
  4642. const count = musicItems.length
  4643. ToastUtil.showToast(count > 1 ? `已添加 ${count} 首歌曲` : '已添加到歌单')
  4644. // 重新加载歌单列表
  4645. await this.loadAllPlaylists()
  4646. } else {
  4647. ToastUtil.showToast(musicItems.length > 1 ? '选中的歌曲已在该歌单中' : '歌曲已在该歌单中')
  4648. }
  4649. this.longItemFilePath = ''
  4650. if (this.isMultiSelect) {
  4651. this.isMultiSelect = false
  4652. this.isAllSelected = false
  4653. this.selectedFiles = []
  4654. }
  4655. },
  4656. () => {
  4657. LogUtil.info('取消添加到歌单')
  4658. },
  4659. () => {
  4660. // 创建新歌单
  4661. showCreatePlaylistDialog(
  4662. async (name: string, description: string, coverPath?: string) => {
  4663. const success = await this.playlistTable?.createPlaylist(name, description, coverPath)
  4664. if (success) {
  4665. ToastUtil.showToast('歌单创建成功')
  4666. // 重新加载歌单列表并打开添加对话框
  4667. await this.loadAllPlaylists()
  4668. await this.openAddToPlaylistDialog(musicItems)
  4669. } else {
  4670. ToastUtil.showToast('歌单创建失败')
  4671. }
  4672. },
  4673. () => {
  4674. // 取消创建歌单
  4675. }
  4676. )
  4677. }
  4678. )
  4679. }
  4680. private syncFavStateLocal(item: VideoItem, isFav: number): void {
  4681. const nextFavList = [...this.favList];
  4682. const favIndex = nextFavList.findIndex((favItem: VideoItem) => favItem.filePath === item.filePath);
  4683. if (isFav === 1) {
  4684. if (favIndex >= 0) {
  4685. nextFavList[favIndex].isFav = 1;
  4686. } else {
  4687. const favItem = cloneVideoItem(item);
  4688. favItem.isFav = 1;
  4689. nextFavList.push(favItem);
  4690. }
  4691. } else if (favIndex >= 0) {
  4692. nextFavList.splice(favIndex, 1);
  4693. }
  4694. this.favList = nextFavList;
  4695. item.isFav = isFav;
  4696. if (this.currentSong && this.currentSong.filePath === item.filePath) {
  4697. this.currentSong.isFav = isFav;
  4698. this.isFac = isFav === 1;
  4699. }
  4700. }
  4701. doFav(item: VideoItem) {
  4702. LogUtil.info('onecold doFav isFav=' + item.isFav)
  4703. let isFav = 0
  4704. if (Utility.getIsFav(this.favList, item)) {
  4705. isFav = 0
  4706. } else {
  4707. isFav = 1
  4708. }
  4709. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  4710. if (result) {
  4711. this.syncFavStateLocal(item, isFav);
  4712. if (isFav === 1) {
  4713. ToastUtil.showToast('收藏成功');
  4714. } else {
  4715. ToastUtil.showToast('取消收藏成功');
  4716. }
  4717. this.deleteCache(this.currentPath)
  4718. this.getFavList(false)
  4719. if (this.modeType === 0 && !this.isFavMusic) {
  4720. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  4721. this.getSortedFiles(this.currentPath)
  4722. }
  4723. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  4724. workerInstance.postMessage({ code: 3, data: this.context });
  4725. workerInstance.postMessage({ code: 4, data: this.context });
  4726. }
  4727. })
  4728. }
  4729. //多选复制文件
  4730. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  4731. console.log('onecold showCopyDialogForMultipleFiles');
  4732. let mList: Array<string> = []
  4733. let rPath = this.rootPath
  4734. if (isCurrent) {
  4735. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  4736. rPath = this.currentPath
  4737. } else {
  4738. mList = Utility.getNameList(this.dirList);
  4739. rPath = this.rootPath
  4740. }
  4741. let dataBean = new BubbleBean();
  4742. dataBean.data = mList;
  4743. dataBean.isCopy = true
  4744. dataBean.color = this.themeColor
  4745. dataBean.onItemClick = (i) => {
  4746. const newDirPath = rPath + '/' + mList[i];
  4747. // Logger.info('newDirPath = ' + newDirPath)
  4748. this.selectedFiles.forEach((item) => {
  4749. const newPath = newDirPath + '/' + item.fileName;
  4750. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  4751. ToastUtil.showToast('复制成功');
  4752. this.cache.delete(newDirPath); // 删除目标路径缓存
  4753. this.getSortedFiles(this.currentPath);
  4754. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  4755. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  4756. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  4757. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  4758. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  4759. this.table.insert(newItem, (id: number) => {
  4760. //加入数据库
  4761. });
  4762. }
  4763. }).catch((error: Error) => {
  4764. console.error(error.message);
  4765. });
  4766. });
  4767. this.isMultiSelect = false
  4768. this.selectedFiles = [];
  4769. this.isAllSelected = false
  4770. XPopup.dismissTop();
  4771. };
  4772. let pup: XPopup
  4773. if (this.isDarkMode) {
  4774. pup = XPopup.Builder()
  4775. .setPopupPosition(PopupPosition.TOP)
  4776. .atView(viewId)
  4777. .setBackgroundColor(Color.Black)
  4778. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4779. .show();
  4780. } else {
  4781. pup = XPopup.Builder()
  4782. .setPopupPosition(PopupPosition.TOP)
  4783. .atView(viewId)
  4784. .setBackgroundColor(Color.White)
  4785. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4786. .show();
  4787. }
  4788. }
  4789. @Builder
  4790. private DirItem(item: VideoItem, index?: number) {
  4791. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  4792. Row() {
  4793. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ?
  4794. this.getListImageSource(item, index ?? -1, this.coverThumbVersion) :
  4795. $r('app.media.music_group'))
  4796. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4797. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4798. .fillColor(this.themeColor)// .fontSize(33)
  4799. .alt($r('app.media.music_group'))
  4800. .borderRadius(this.isCoverRectangle?9:'100%')
  4801. .clip(true)
  4802. .shadow({
  4803. radius: 2,
  4804. type: ShadowType.BLUR,
  4805. color: 'on_primary'
  4806. })
  4807. .sourceSize({width:38, height:38})
  4808. .margin({ left: 20, top: 8, bottom: 8 })
  4809. Column() {
  4810. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  4811. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4812. .maxLines(1)// .width('88%')
  4813. .textOverflow({ overflow: TextOverflow.Ellipsis })//列表模式固定省略,避免滚动跑马灯开销
  4814. .margin({ left: 10, right: 20 })
  4815. .fontColor($r('app.color.text_color'))
  4816. Row() {
  4817. Text(`${this.getArtistSongCount(item.name)}首`)
  4818. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4819. .padding({ top: 8 })
  4820. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  4821. .fontColor($r('app.color.text_color'))
  4822. .margin({ left: 10 })
  4823. Text(`${this.getAlbumSongCount(item.name)}首`)
  4824. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4825. .padding({ top: 8 })
  4826. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  4827. .fontColor($r('app.color.text_color'))
  4828. .margin({ left: 10 })
  4829. Blank()
  4830. }
  4831. }
  4832. .height('100%')
  4833. .layoutWeight(1)
  4834. .justifyContent(FlexAlign.Center)
  4835. .alignItems(HorizontalAlign.Start)
  4836. Blank()
  4837. Image($r('app.media.arrow_right'))
  4838. .height(25)
  4839. .alignSelf(ItemAlign.Center)
  4840. .id(item.filePath)
  4841. .visibility(this.isShowAlphaBet?Visibility.None:Visibility.Visible)
  4842. }
  4843. }
  4844. .backgroundColor(Color.Transparent)
  4845. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  4846. .width('98%')
  4847. .reuseId('dir_item')
  4848. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  4849. .opacity(this.opacityItem) // 绑定透明度
  4850. }
  4851. private refreshDirVisibilitySettings(): void {
  4852. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  4853. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  4854. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  4855. }
  4856. isShowDir(dirName: string) {
  4857. if (dirName === undefined) {
  4858. return true
  4859. }
  4860. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  4861. return this.isShowSimi
  4862. }
  4863. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  4864. return this.isShowFAV
  4865. }
  4866. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  4867. return this.isShowHistory
  4868. }
  4869. return true
  4870. }
  4871. @State opacityItem: number = 1; // 控制透明度的状态变量
  4872. @Builder
  4873. private MusicItem(item: VideoItem, index?: number) {
  4874. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  4875. Row() {
  4876. Stack() {
  4877. Image(this.getListImageSource(item, index ?? -1, this.coverThumbVersion))
  4878. .fillColor(this.themeColor)
  4879. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4880. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4881. .alt($r('app.media.alt'))
  4882. .borderRadius(this.isCoverRectangle?9:'100%')
  4883. .clip(true)
  4884. .draggable(false)
  4885. .sourceSize({width:38, height:38})
  4886. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4887. // .autoResize(true) // 重采样,可减少内存占用
  4888. .opacity(this.opacityItem)// 绑定透明度
  4889. .margin({ left: 20 })
  4890. .shadow({
  4891. radius: this.isScrolling ? 0 : 10,
  4892. type: ShadowType.BLUR,
  4893. color: 'on_primary'
  4894. })
  4895. .onClick(()=>{
  4896. if (this.isMultiSelect) {
  4897. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  4898. this.handleFileSelection(item, !isChecked);
  4899. } else {
  4900. this.doPlay(item,index)
  4901. this.setShowPlayTrue()
  4902. }
  4903. })
  4904. }
  4905. Column() {
  4906. Column() {
  4907. Text(this.isShowFileName?item.fileName :item.name)
  4908. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4909. .maxLines(1)
  4910. .textOverflow({ overflow: this.isLongNameRoLL&&!this.isScrolling?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4911. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4912. $r('app.color.text_color'))
  4913. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4914. .padding({right:25})
  4915. .bindPopup(this.longItemFilePath === item.filePath, {
  4916. builder: this.MenuBuilder(item,index,item.filePath),
  4917. placement: Placement.Top,
  4918. // autoCancel: true,
  4919. mask: {color:'#33000000'},
  4920. // popupColor: Color.Yellow,
  4921. enableArrow: false,//是否显示箭头
  4922. showInSubWindow: false,
  4923. onStateChange: (e) => {
  4924. if (!e.isVisible) {
  4925. this.longItemFilePath = ''
  4926. this.tempLyricContent = ''
  4927. }
  4928. }
  4929. })
  4930. Row() {
  4931. Column(){
  4932. Text(item.md5Str?.includes('Lossless')?
  4933. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  4934. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  4935. .padding({ top: 3,right:6,left:6,bottom:3 })
  4936. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4937. $r('app.color.text_color'))
  4938. .fontWeight(500)
  4939. .borderRadius(12)
  4940. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  4941. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4942. .backgroundColor('#FFC107')
  4943. }
  4944. .padding({ top: 8 })
  4945. Text(StrUtil.isEmpty(item.artist) ? item.duration
  4946. :this.twoFingerType==2? item.artist +' ' + item.duration
  4947. : item.artist + ' ' + item?.duration)
  4948. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4949. .padding({ top: 8 ,right:25})
  4950. .visibility(this.isShowFileName?Visibility.None:Visibility.Visible)
  4951. .maxLines(1)
  4952. .textOverflow({ overflow: TextOverflow.Ellipsis })//列表模式固定省略
  4953. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4954. Color.Gray)
  4955. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4956. Blank()
  4957. Text(this.isShowFileName?item.duration:item.size)
  4958. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4959. .padding({ top: 8 })
  4960. .maxLines(1)
  4961. .visibility(this.isShowFileName?Visibility.Visible:StrUtil.isEmpty(item.artist)
  4962. ? Visibility.Visible : Visibility.None)
  4963. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4964. Color.Gray)
  4965. .margin({ left: StrUtil.isEmpty(item.artist) ?0:10 })
  4966. }
  4967. }
  4968. .height('100%')
  4969. .width('100%')
  4970. .margin({ right: 10 })
  4971. .justifyContent(FlexAlign.Center)
  4972. .alignItems(HorizontalAlign.Start)
  4973. }
  4974. .height('100%')
  4975. .margin({ left: 5 })
  4976. .layoutWeight(1)
  4977. Column() {
  4978. Checkbox({ name: 'checkbox' + index })
  4979. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  4980. .selectedColor(this.themeColor)
  4981. .shape(CheckBoxShape.CIRCLE)
  4982. .opacity(this.isMultiSelect ? 1 : 0)
  4983. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  4984. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  4985. .margin({ left: 20, top: 8, bottom: 8,right:18 })
  4986. .width(22)
  4987. .height(22)
  4988. ImageAnimator()
  4989. .images(this.imagesF)// 动画数组
  4990. .duration(1000)// 持续
  4991. .state(this.animationState)// 动画状态
  4992. .fillMode(FillMode.Forwards)
  4993. .width(18)
  4994. .margin({ right: 20, top: 8, bottom: 8 })
  4995. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  4996. Visibility.None)
  4997. .height(18)
  4998. .iterations(-1) // 播放次数
  4999. }
  5000. }
  5001. }
  5002. .gesture(LongPressGesture()
  5003. .onAction(async () => {
  5004. //如果是专辑和艺术家的首页,不能长按
  5005. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  5006. return
  5007. //如果是我的收藏 最近播放等也不能长按
  5008. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5009. item.name === LocalMusic.STR_HISTORY_MUSIC
  5010. )
  5011. return
  5012. this.longItemFilePath = item.filePath
  5013. this.tempLyricContent = await this.getLyricContent(item)
  5014. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  5015. })
  5016. .onActionEnd((event: GestureEvent) => {
  5017. }))
  5018. .backgroundColor(Color.Transparent)
  5019. .width('100%')
  5020. .reuseId('file_item')
  5021. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  5022. }
  5023. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  5024. @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
  5025. buttons: [{ text: '文件夹' }, { text: '媒体库' },{ text: '艺术家' }, { text: '专辑' }],
  5026. direction: Direction.Ltr,
  5027. buttonPadding:{top:12,bottom:12},
  5028. backgroundColor: Color.Transparent,
  5029. fontSize:14,
  5030. selectedFontSize:15,
  5031. selectedFontColor:Color.White,
  5032. selectedBackgroundColor: this.themeColor,
  5033. localizedTextPadding: {
  5034. end: LengthMetrics.vp(20),
  5035. start: LengthMetrics.vp(20)
  5036. }
  5037. })
  5038. @State @Watch('capsuleSelectedIndexesChanged')tabSelectedIndexes: number[] = [0]
  5039. //当胶囊按钮的选择发生变化时调用此函数
  5040. capsuleSelectedIndexesChanged() {
  5041. this.modeType = this.tabSelectedIndexes[0]
  5042. }
  5043. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  5044. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  5045. isShowCoverHeader() {
  5046. if (!this.isShowHeader) {
  5047. return false
  5048. }
  5049. if (this.modeType == 0) {
  5050. if (this.isHistory || this.isFavMusic) {
  5051. return true
  5052. }
  5053. if (this.currentPath != this.rootPath) {
  5054. return true
  5055. }
  5056. }
  5057. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  5058. }
  5059. getCoverTitleBg(): ResourceStr | image.PixelMap {
  5060. if (this.isCustomizeBg) {
  5061. return ('rgba(255,255,255,0.2)')
  5062. }
  5063. if (this.isDarkMode) {
  5064. return $r('app.color.user_center_card_background')
  5065. }
  5066. return this.currentTitleCover
  5067. }
  5068. // 第二步:popup构造器定义弹框内容
  5069. @Builder popupBuilder() {
  5070. Column({ space: 2 }) {
  5071. Text('友情提示:双指缩放可以放大缩小列表')
  5072. .fontSize(12)
  5073. .fontWeight(FontWeight.Regular)
  5074. .fontColor($r('app.color.text_color'))
  5075. }
  5076. .justifyContent(FlexAlign.SpaceAround)
  5077. .width(220)
  5078. .height(55)
  5079. .padding(15)
  5080. }
  5081. //搜索功能的实现
  5082. @State searchText: string = ''; // 用户输入内容
  5083. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  5084. @State isSearchMode: boolean = false
  5085. // 实时搜索逻辑(带防抖)
  5086. private async onSearchInput(value: string): Promise<void> {
  5087. this.searchText = value.trim();
  5088. Logger.info('heanup LocalMusic', `onSearchInput: keyword="${this.searchText}", mode=${this.modeType}`);
  5089. // 新增条件判断:空输入时退出搜索模式
  5090. if (this.searchText === '') {
  5091. this.isSearchMode = false;
  5092. // 重新加载第一页(不带搜索条件)
  5093. await this.resetAndLoadFirstPage();
  5094. return;
  5095. }
  5096. // 进入搜索模式
  5097. if (!this.isSearchMode) {
  5098. this.isSearchMode = true;
  5099. }
  5100. // 使用数据库分页查询(带搜索条件)
  5101. await this.resetAndLoadFirstPage();
  5102. }
  5103. @State dragItem: number = -1
  5104. @State scaleItem: number = -1
  5105. @State neighborItem: number = -1
  5106. @State neighborScale: number = -1
  5107. @State offsetY: number = 0
  5108. private dragRefOffset: number = 0
  5109. private ITEM_INTV: number = 78
  5110. scaleSelect(item: number): number {
  5111. if (this.scaleItem === item) {
  5112. return 1.05
  5113. } else if (this.neighborItem === item) {
  5114. return this.neighborScale
  5115. } else {
  5116. return 1
  5117. }
  5118. }
  5119. itemMove(index: number, newIndex: number): void {
  5120. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  5121. return;
  5122. }
  5123. let tmp = this.videoLocalList.splice(index, 1);
  5124. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  5125. this.dataSource.pushArrayData(this.videoLocalList)
  5126. if(this.modeType==4&&this.playlistTable){
  5127. updateAllSongsSortOrder(this.playlistTable, this.videoLocalList,this.currentSongListID)
  5128. }
  5129. }
  5130. //瀑布流布局 支持双指缩放
  5131. @State columns: number = 2;
  5132. @State waterFlowScale: number = 1;
  5133. @State imageScale: number = 1;
  5134. @State waterFlowOpacity: number = 1;
  5135. @State waterFlowSnapshot: image.PixelMap | undefined = undefined;
  5136. private columnChanged: boolean = false;
  5137. private oldColumn: number = this.columns;
  5138. private pinchTime: number = 0;
  5139. // 根据缩放阈值改变列数,触发WaterFlow重新布局
  5140. changeColumns(scale: number): void {
  5141. if (scale > (this.columns / (this.columns - 0.5)) && this.columns > 1) {
  5142. this.columns--;
  5143. this.columnChanged = true;
  5144. } else if (scale < 1 && this.columns < 4) {
  5145. this.columns++;
  5146. this.columnChanged = true;
  5147. }
  5148. }
  5149. @Builder
  5150. getWaterView(){
  5151. Scroll(this.scroller) {
  5152. Column() {
  5153. Blank().height(this.topSafeHeight + 55)
  5154. WaterFlow({
  5155. scroller:this.waterScroller,
  5156. layoutMode: WaterFlowLayoutMode.SLIDING_WINDOW
  5157. }) {
  5158. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5159. FlowItem() {
  5160. this.MusicWaterCardItem(item,index)
  5161. }
  5162. .width('100%')
  5163. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  5164. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  5165. {
  5166. preview: MenuPreviewMode.IMAGE
  5167. })
  5168. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  5169. {
  5170. preview: MenuPreviewMode.IMAGE
  5171. })
  5172. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5173. }
  5174. // .columnsTemplate('repeat(auto-fit, 160)')
  5175. .id('waterflow') // 设置id用于截图
  5176. .columnsTemplate('1fr '.repeat(this.columns)) // 动态生成列模板,如:'1fr 1fr 1fr'表示3列等宽
  5177. .columnsGap(12) // 列间距
  5178. .rowsGap(this.columns >= 4 ? 8 : (this.columns == 3 ? 10 : 14)) // 行间距
  5179. .cachedCount(this.columns >= 4 ? 2 : (this.columns == 3 ? 3 : 4))
  5180. .padding({bottom:this.bottomBarHeight+10})
  5181. .scrollBar(BarState.Off)
  5182. // .fadingEdge(true, { fadingEdgeLength: LengthMetrics.vp(38) })
  5183. // 效果:只有向上或者向下滑动到顶部时才会有弹簧回弹效果
  5184. .edgeEffect(EdgeEffect.None)
  5185. .width('90%')
  5186. .height('100%')
  5187. .opacity(this.waterFlowOpacity)
  5188. .scale({
  5189. x: this.waterFlowScale,
  5190. y: this.waterFlowScale,
  5191. centerX: 0,
  5192. centerY: 0
  5193. })
  5194. .onReachEnd(() => {
  5195. if(this.modeType === 4 )
  5196. return;
  5197. // 触底加载下一页
  5198. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  5199. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  5200. return;
  5201. }
  5202. if (this.hasMoreData && !this.isLoadingPage && !this.isPagingTransition) {
  5203. this.scheduleLoadNextPage();
  5204. }
  5205. })
  5206. .onAppear(() => {
  5207. this.scroller.scrollEdge(Edge.Top)
  5208. })
  5209. .nestedScroll({
  5210. scrollForward: NestedScrollMode.PARENT_FIRST,
  5211. scrollBackward: NestedScrollMode.SELF_FIRST
  5212. })
  5213. .priorityGesture(
  5214. PinchGesture()
  5215. .onActionStart((event: GestureEvent) => {
  5216. // 双指捏合手势识别成功时截图
  5217. this.pinchTime = event.timestamp;
  5218. this.columnChanged = false;
  5219. this.oldColumn = this.columns;
  5220. this.getUIContext().getComponentSnapshot().get('waterflow', (error: Error, pixmap: image.PixelMap) => {
  5221. if (error) {
  5222. console.info('error:' + JSON.stringify(error));
  5223. return;
  5224. }
  5225. this.waterFlowSnapshot = pixmap;
  5226. if ((this.oldColumn === 1 ) && event.scale > 1|| (this.oldColumn === 4 && event.scale < 1)) {
  5227. console.info("onecold onActionStart oldColumn:" + this.oldColumn)
  5228. if (this.oldColumn ===4) {
  5229. this.twoFingerType =3
  5230. this.isGridMusic = true
  5231. }else if (this.oldColumn ===1) {
  5232. this.twoFingerType =1
  5233. this.isGridMusic = false
  5234. }
  5235. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  5236. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5237. return;
  5238. }
  5239. })
  5240. })
  5241. .onActionUpdate((event: GestureEvent) => {
  5242. // 手势更新:处理缩放逻辑和视觉效果
  5243. // 边界限制:防止超出列数范围时继续缩放
  5244. if ((this.oldColumn === 1 && event.scale > 1) || (this.oldColumn === 4 && event.scale < 1)) {
  5245. return;
  5246. }
  5247. // 节流处理:避免过于频繁的更新,提升性能
  5248. if (event.timestamp - this.pinchTime < 10000000) {
  5249. return;
  5250. }
  5251. this.pinchTime = event.timestamp;
  5252. this.waterFlowScale = event.scale;
  5253. this.imageScale = event.scale;
  5254. // 根据缩放比例设置WaterFlow透明度
  5255. this.waterFlowOpacity = (this.waterFlowScale > 1) ? (this.waterFlowScale - 1) : (1 - this.waterFlowScale);
  5256. this.waterFlowOpacity *= 3;
  5257. if (!this.columnChanged) {
  5258. this.changeColumns(event.scale);
  5259. }
  5260. // 列数改变后的缩放比例调整:避免出现空白区域
  5261. if (this.columnChanged) {
  5262. this.waterFlowScale = this.imageScale * this.columns / this.oldColumn;
  5263. // 限制缩放范围,确保视觉效果自然
  5264. if (event.scale < 1) {
  5265. this.waterFlowScale = this.waterFlowScale > 1 ? this.waterFlowScale : 1;
  5266. } else {
  5267. this.waterFlowScale = this.waterFlowScale < 1 ? this.waterFlowScale : 1;
  5268. }
  5269. }
  5270. })
  5271. .onActionEnd((event: GestureEvent) => {
  5272. // 手势结束:执行归位动画并保存状态
  5273. // 执行归位动画:平滑过渡到正常状态
  5274. this.getUIContext()?.animateTo({ duration: 300 }, () => {
  5275. this.waterFlowScale = 1;
  5276. this.waterFlowOpacity = 1;
  5277. })
  5278. // 持久化保存当前列数:下次启动时恢复
  5279. PreferencesUtil.putSync('lastColumns', this.columns);
  5280. })
  5281. )
  5282. .onScrollFrameBegin((offset: number) => {
  5283. this.markGridWaterScrollingActive()
  5284. // 获取当前滚动偏移量
  5285. const currentOffsetY = this.waterScroller.currentOffset().yOffset;
  5286. this.tryTriggerLoadForWaterByOffset(currentOffsetY)
  5287. this.updateTitleBarByScrollOffset(currentOffsetY)
  5288. return { offsetRemain: offset };
  5289. })
  5290. }
  5291. }
  5292. .scrollBar(BarState.Off)
  5293. }
  5294. //瀑布流卡片布局
  5295. @Builder
  5296. private MusicWaterCardItem(item: VideoItem, index: number) {
  5297. Button({ type: ButtonType.Normal, stateEffect: false }) {
  5298. Stack() {
  5299. Column() {
  5300. Image(this.getGridWaterImageSource(item, index, true, this.coverThumbVersion))
  5301. .backgroundImageSize(ImageSize.Auto)
  5302. .borderRadius({
  5303. topLeft: 12,
  5304. topRight : 12,
  5305. bottomLeft: 0,
  5306. bottomRight: 0
  5307. })
  5308. .draggable(false)// 禁止长按手势拖动
  5309. .autoResize(true) // 重采样,可减少内存占用
  5310. .sourceSize({
  5311. width: this.getCoverThumbTargetSize(true),
  5312. height: this.getCoverThumbTargetSize(true)
  5313. })
  5314. .width('100%')
  5315. .height('auto')
  5316. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  5317. .objectFit(ImageFit.Cover)
  5318. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  5319. height: '99%' ,
  5320. dragBar: true,
  5321. onDisappear: () => {
  5322. this.longItemFilePath = '';
  5323. this.tempLyricContent = ''
  5324. },
  5325. showClose: true,
  5326. preferType: SheetType.CENTER ,
  5327. title: { title: '编辑标签' }
  5328. })
  5329. .draggable(false)
  5330. .opacity(this.opacityItem)// 绑定透明度
  5331. .margin({
  5332. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5333. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5334. })
  5335. Column() {
  5336. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  5337. .fontSize(this.columns == 4 ||this.columns==3? 12 : this.columns == 2 ? 15 : 18)
  5338. .maxLines(1)
  5339. .fontWeight(FontWeight.Bold)
  5340. .textOverflow({ overflow: this.isLongNameRoLL&&!this.isScrolling?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5341. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  5342. height: '95%',
  5343. dragBar: true,
  5344. showClose: true,
  5345. onDisappear: () => {
  5346. this.longItemFilePathDetail = '';
  5347. },
  5348. blurStyle:BlurStyle.Thin,
  5349. backgroundColor:Color.Transparent,
  5350. preferType: SheetType.CENTER ,
  5351. title: { title: '详情' }
  5352. })
  5353. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5354. $r('app.color.text_color'))
  5355. Column() {
  5356. Text(`${this.getArtistSongCount(item.name)}首`)
  5357. .fontSize(11)
  5358. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  5359. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5360. .fontColor($r('app.color.text_color'))
  5361. Text(`${this.getAlbumSongCount(item.name)}首`)
  5362. .fontSize(11)
  5363. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  5364. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5365. .fontColor($r('app.color.text_color'))
  5366. Row(){
  5367. Column(){
  5368. Text(item.md5Str?.includes('Lossless')?
  5369. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5370. .fontSize(this.columns == 4 ||this.columns==3? 8 : this.columns == 2 ? 9 : 11)
  5371. .padding({ top: 3,right:6,left:6,bottom:3 })
  5372. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5373. $r('app.color.text_color'))
  5374. .fontWeight(500)
  5375. .borderRadius(12)
  5376. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5377. .backgroundColor('#FFC107')
  5378. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  5379. }
  5380. .margin({ top: 2 ,right:6})
  5381. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  5382. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  5383. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  5384. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 13)
  5385. .maxLines(1)
  5386. .textOverflow({ overflow: TextOverflow.Ellipsis })//瀑布流固定省略
  5387. .margin({ top: 2})
  5388. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  5389. || item.type == CommonConstants.TYPE_IS_ALBUM
  5390. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5391. .fontWeight(FontWeight.Medium)
  5392. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5393. $r('app.color.text_color'))
  5394. }
  5395. }
  5396. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  5397. }
  5398. .height(this.columns == 4 ||this.columns==3? item.type==CommonConstants.TYPE_IS_DIR?30:40
  5399. : this.columns == 2 ? (item.type==CommonConstants.TYPE_IS_DIR?38:48) :
  5400. (item.type==CommonConstants.TYPE_IS_DIR?48:58))
  5401. .width('100%')
  5402. .justifyContent(FlexAlign.Center)
  5403. .margin({
  5404. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5405. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5406. })
  5407. }
  5408. .width('100%')
  5409. .borderRadius(12)
  5410. .backgroundColor(this.isDarkMode ? '#141414' : '#F7F7F7')
  5411. Checkbox({ name: 'checkbox' + index })
  5412. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  5413. .selectedColor(this.themeColor)
  5414. .shape(CheckBoxShape.CIRCLE)
  5415. .opacity(this.isMultiSelect ? 1 : 0)
  5416. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  5417. Visibility.None)
  5418. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5419. .margin({ left: 20, top: 8, bottom: 8 })
  5420. .width(38)
  5421. .height(38)
  5422. }
  5423. }
  5424. .backgroundColor(Color.Transparent)
  5425. .width('100%')
  5426. .height('auto')
  5427. .padding({top:2})
  5428. .shadow({
  5429. radius: this.isScrolling ? 0 : 8,
  5430. type: ShadowType.BLUR,
  5431. color: 'on_primary'
  5432. })
  5433. .reuseId('card_item')
  5434. .onClick(() => {
  5435. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5436. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5437. this.handleFileSelection(item, !isChecked);
  5438. } else {
  5439. this.doPlay(item, index)
  5440. }
  5441. })
  5442. }
  5443. // Grid布局的开始
  5444. private dragRefOffSetX: number = 0;
  5445. private dragRefOffSetY: number = 0;
  5446. private FIX_VP_X: number = 180;
  5447. private FIX_VP_Y: number = 84;
  5448. isDraggable(index: number): boolean {
  5449. return index >= 0;
  5450. }
  5451. getRowEnd(item: number) {
  5452. if (item.toString() === '0') {
  5453. return 1;
  5454. } else {
  5455. return 0;
  5456. }
  5457. }
  5458. isInLeft(index: number) {
  5459. return index % 2 == 0;
  5460. }
  5461. down(index: number): void {
  5462. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  5463. return;
  5464. }
  5465. this.offsetY -= this.FIX_VP_Y;
  5466. this.dragRefOffSetY += this.FIX_VP_Y;
  5467. this.itemMove(index, index + 1);
  5468. }
  5469. up(index: number): void {
  5470. if (!this.isDraggable(index - 2)) {
  5471. return;
  5472. }
  5473. this.offsetY += this.FIX_VP_Y;
  5474. this.dragRefOffSetY -= this.FIX_VP_Y;
  5475. this.itemMove(index, index - 1);
  5476. }
  5477. left(index: number): void {
  5478. if (this.isInLeft(index)) {
  5479. return;
  5480. }
  5481. if (!this.isDraggable(index - 1)) {
  5482. return;
  5483. }
  5484. this.offsetX += this.FIX_VP_X;
  5485. this.dragRefOffSetX -= this.FIX_VP_X;
  5486. this.itemMove(index, index - 1)
  5487. }
  5488. right(index: number): void {
  5489. if (!this.isInLeft(index)) {
  5490. return;
  5491. }
  5492. if (!this.isDraggable(index + 1)) {
  5493. return;
  5494. }
  5495. this.offsetX -= this.FIX_VP_X;
  5496. this.dragRefOffSetX += this.FIX_VP_X;
  5497. this.itemMove(index, index + 1)
  5498. }
  5499. private scroller: Scroller = new Scroller();
  5500. private waterScroller: Scroller = new Scroller();
  5501. private startIndex: number = 0
  5502. private endIndex: number = 0
  5503. @State scaleValue: number = 1
  5504. @State pinchValue: number = 1
  5505. layoutOptionsForHeader: GridLayoutOptions = {
  5506. regularSize: [1, 1], // 只支持[1, 1]
  5507. irregularIndexes: [0], // 索引为0的GridItem占用一行
  5508. };
  5509. @Builder
  5510. getGridView() {
  5511. Grid(this.scroller, this.layoutOptionsForHeader) {
  5512. GridItem() {
  5513. Column(){
  5514. Blank().height(this.topSafeHeight + 45)
  5515. }
  5516. }
  5517. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5518. GridItem() {
  5519. Stack() {
  5520. this.MusicItemGrid(item, index)
  5521. }
  5522. }
  5523. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  5524. {
  5525. preview: MenuPreviewMode.IMAGE
  5526. })
  5527. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  5528. {
  5529. preview: MenuPreviewMode.IMAGE
  5530. })
  5531. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.9, y: 0.9 }).animation({ duration: 300 }),
  5532. // TransitionEffect.scale({ x: 0, y: 0 })))
  5533. .clickEffect({ level: ClickEffectLevel.LIGHT })
  5534. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  5535. .zIndex(this.dragItem === index ? 1 : 0)
  5536. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  5537. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5538. }
  5539. .width('94%')
  5540. .height('100%')
  5541. .editMode(true)
  5542. .padding({bottom:this.bottomBarHeight+this.bottomSafeHeight+10})
  5543. .reuseId('grid_item')
  5544. .layoutWeight(1)
  5545. .scrollBar(BarState.Off)
  5546. .supportAnimation(false)
  5547. .onReachEnd(() => {
  5548. if(this.modeType === 4 )
  5549. return;
  5550. // 触底加载下一页
  5551. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  5552. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  5553. return;
  5554. }
  5555. if (this.hasMoreData && !this.isLoadingPage && !this.isPagingTransition) {
  5556. this.scheduleLoadNextPage();
  5557. }
  5558. })
  5559. .cachedCount(this.twoFingerType==1?1:this.twoFingerType==2?2:2)
  5560. .columnsTemplate(
  5561. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  5562. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  5563. )
  5564. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  5565. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  5566. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  5567. .gesture(PinchGesture({ fingers: 2 })
  5568. .onActionEnd((event: GestureEvent) => {
  5569. this.setGridTwoFingers()
  5570. })
  5571. .onActionUpdate(e => {
  5572. this.scaleValue = this.pinchValue * e.scale
  5573. })
  5574. .onActionStart(e => {
  5575. }))
  5576. .enableScrollInteraction(true)
  5577. .onScrollIndex((start: number, end: number) => {
  5578. this.startIndex = start
  5579. this.endIndex = end
  5580. this.gridVisibleStart = start
  5581. this.gridVisibleEnd = end
  5582. this.lastVisibleEndIndex = end
  5583. this.warmupGridWaterVisibleThumbs(start, end, false)
  5584. const now = Date.now()
  5585. const pagingDelta = this.gridScrollLastPagingEnd >= 0 ? Math.abs(end - this.gridScrollLastPagingEnd) : 999
  5586. if (pagingDelta >= 2 || now - this.gridScrollPagingCheckAt >= 40) {
  5587. this.gridScrollPagingCheckAt = now
  5588. this.gridScrollLastPagingEnd = end
  5589. this.tryTriggerLoadNextPageByScroll(end)
  5590. }
  5591. })
  5592. .onScrollFrameBegin((offset: number) => {
  5593. this.markGridWaterScrollingActive()
  5594. const currentOffsetY = this.scroller.currentOffset().yOffset;
  5595. this.updateTitleBarByScrollOffset(currentOffsetY)
  5596. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  5597. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  5598. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  5599. if (this.isScrollHide) {
  5600. this.setBarHeightHide2(offset)
  5601. } else {
  5602. this.setBarHeightNormal()
  5603. }
  5604. } else {
  5605. this.setBarHeightHide(offset)
  5606. }
  5607. return { offsetRemain: offset };
  5608. })
  5609. }
  5610. @State targetFile: string = '';
  5611. setGridTwoFingers() {
  5612. this.pinchValue = this.scaleValue;
  5613. Logger.info('this.pinchValue = ' + this.pinchValue);
  5614. if (this.pinchValue >= 1) {
  5615. this.twoFingerType++
  5616. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  5617. if(this.twoFingerType >= 4){
  5618. this.twoFingerType = 4//切换成瀑布流
  5619. this.columns = 4
  5620. }
  5621. } else {
  5622. this.twoFingerType--
  5623. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  5624. if (this.twoFingerType < 1) {
  5625. this.twoFingerType = 3
  5626. this.isGridMusic = false
  5627. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5628. }
  5629. }
  5630. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  5631. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5632. this.pinchValue = 1;
  5633. this.scaleValue = 1;
  5634. }
  5635. @State longItemFilePath: string = ''
  5636. @State tempLyricContent: string = ''
  5637. @State editingItem: VideoItem | null = null
  5638. @Builder
  5639. private MusicItemGrid(item: VideoItem, index: number) {
  5640. Button({ type: ButtonType.Normal, stateEffect: false }) {
  5641. Stack() {
  5642. Column() {
  5643. Image(this.getGridWaterImageSource(item, index, false, this.coverThumbVersion))
  5644. .height(this.getGridHeight())
  5645. .width(this.getGridWight())
  5646. .draggable(false)
  5647. .autoResize(true) // 重采样,可减少内存占用
  5648. .sourceSize({
  5649. width: this.getCoverThumbTargetSize(false),
  5650. height: this.getCoverThumbTargetSize(false)
  5651. })
  5652. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  5653. .clip(true)
  5654. .borderRadius({
  5655. topLeft: 12,
  5656. topRight: 12,
  5657. bottomLeft: 0,
  5658. bottomRight: 0
  5659. })
  5660. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  5661. height: '99%' ,
  5662. dragBar: true,
  5663. onDisappear: () => {
  5664. this.longItemFilePath = '';
  5665. this.tempLyricContent = ''
  5666. },
  5667. showClose: true,
  5668. preferType: SheetType.CENTER ,
  5669. title: { title: '编辑标签' }
  5670. })
  5671. .draggable(false)
  5672. .opacity(this.opacityItem)// 绑定透明度
  5673. .margin({
  5674. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5675. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5676. })
  5677. Column() {
  5678. Text(this.isShowFileName&&this.modeType !== 2&&this.modeType !== 3&&
  5679. item.type!=CommonConstants.TYPE_IS_DIR?item.fileName :item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  5680. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5681. .maxLines(1)
  5682. .fontWeight(FontWeight.Bold)
  5683. .textOverflow({ overflow: this.isLongNameRoLL&&!this.isScrolling?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5684. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  5685. height: '100%',
  5686. dragBar: true,
  5687. showClose: true,
  5688. onDisappear: () => {
  5689. this.longItemFilePathDetail = '';
  5690. },
  5691. blurStyle:BlurStyle.Thin,
  5692. backgroundColor:Color.Transparent,
  5693. preferType: SheetType.CENTER ,
  5694. title: { title: '详情' }
  5695. })
  5696. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5697. $r('app.color.text_color'))
  5698. Column() {
  5699. Text(`${this.getArtistSongCount(item.name)}首`)
  5700. .fontSize(11)
  5701. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  5702. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5703. .fontColor($r('app.color.text_color'))
  5704. Text(`${this.getAlbumSongCount(item.name)}首`)
  5705. .fontSize(11)
  5706. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  5707. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5708. .fontColor($r('app.color.text_color'))
  5709. Row(){
  5710. Column(){
  5711. Text(item.md5Str?.includes('Lossless')?
  5712. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5713. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  5714. .padding({ top: 3,right:6,left:6,bottom:3 })
  5715. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5716. $r('app.color.text_color'))
  5717. .fontWeight(500)
  5718. .borderRadius(12)
  5719. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5720. .backgroundColor('#FFC107')
  5721. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  5722. }
  5723. .margin({ top: 2 ,right:6})
  5724. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  5725. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  5726. Text(this.isShowFileName?item.duration:StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  5727. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  5728. .maxLines(1)
  5729. .textOverflow({ overflow: TextOverflow.Ellipsis })//Grid固定省略
  5730. .margin({ top: 2})
  5731. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  5732. || item.type == CommonConstants.TYPE_IS_ALBUM
  5733. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5734. .fontWeight(FontWeight.Medium)
  5735. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5736. $r('app.color.text_color'))
  5737. }
  5738. }
  5739. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  5740. }
  5741. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  5742. .width(this.getGridWight())
  5743. .justifyContent(FlexAlign.Center)
  5744. .margin({
  5745. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5746. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5747. })
  5748. }
  5749. .width(this.getGridWight())
  5750. .borderRadius(12)
  5751. .backgroundColor(this.isDarkMode ? '#141414' : '#F7F7F7')
  5752. Checkbox({ name: 'checkbox' + index })
  5753. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  5754. .selectedColor(this.themeColor)
  5755. .shape(CheckBoxShape.CIRCLE)
  5756. .opacity(this.isMultiSelect ? 1 : 0)
  5757. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  5758. Visibility.None)
  5759. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5760. .margin({ left: 20, top: 8, bottom: 8 })
  5761. .width(38)
  5762. .height(38)
  5763. }
  5764. }
  5765. .backgroundColor(Color.Transparent)
  5766. .width('100%')
  5767. .padding({ top: 15 })
  5768. .height(this.getGridAllHeight())
  5769. .onClick(() => {
  5770. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5771. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5772. this.handleFileSelection(item, !isChecked);
  5773. } else {
  5774. this.doPlay(item, index)
  5775. }
  5776. })
  5777. }
  5778. getGridAllHeight() {
  5779. let heightG = 222
  5780. switch (this.twoFingerType) {
  5781. case 1:
  5782. heightG = 143
  5783. break;
  5784. case 2:
  5785. heightG = 178
  5786. break;
  5787. case 3:
  5788. heightG = 222
  5789. break;
  5790. }
  5791. return heightG
  5792. }
  5793. getGridHeight() {
  5794. let heightG = 150
  5795. switch (this.twoFingerType) {
  5796. case 1:
  5797. heightG = 80
  5798. break;
  5799. case 2:
  5800. heightG = 110
  5801. break;
  5802. case 3:
  5803. heightG = 150
  5804. break;
  5805. }
  5806. return heightG
  5807. }
  5808. getGridWight() {
  5809. let wightG = 158
  5810. switch (this.twoFingerType) {
  5811. case 1:
  5812. wightG = 80
  5813. break;
  5814. case 2:
  5815. wightG = 110
  5816. break;
  5817. case 3:
  5818. wightG = 158
  5819. break;
  5820. }
  5821. return wightG
  5822. }
  5823. @State isShowDetail:boolean = false
  5824. @State longItemFilePathDetail:string =''
  5825. @Builder
  5826. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  5827. if(
  5828. ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  5829. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5830. item.name === LocalMusic.STR_HISTORY_MUSIC)
  5831. ){
  5832. //如果是专辑和艺术家的首页,不能长按
  5833. //如果是我的收藏 最近播放等也不能长按
  5834. }else{
  5835. Scroll() {
  5836. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  5837. Menu() {
  5838. MenuItem({
  5839. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  5840. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  5841. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  5842. })
  5843. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5844. .onClick(() => {
  5845. if (item) {
  5846. this.doFav(item)
  5847. }
  5848. this.longItemFilePath = ''
  5849. })
  5850. MenuItem({
  5851. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  5852. content: '下一首播放'
  5853. })
  5854. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5855. .onClick(() => {
  5856. this.addToNextPlay(item);
  5857. this.longItemFilePath = ''
  5858. })
  5859. MenuItem({
  5860. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  5861. content: '添加到歌单'
  5862. })
  5863. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5864. .onClick(async () => {
  5865. this.longItemFilePath = ''
  5866. await this.openAddToPlaylistDialog(item)
  5867. })
  5868. MenuItem({
  5869. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  5870. content: '编辑标签'
  5871. })
  5872. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  5873. height: '99%',
  5874. dragBar: true,
  5875. showClose: true,
  5876. preferType: SheetType.CENTER ,
  5877. title: { title: '编辑标签' }
  5878. })
  5879. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5880. .onClick(async() => {
  5881. this.initEditFields(item)
  5882. this.tempLyricContent = await this.getLyricContent(item);
  5883. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  5884. this.lyricConStr = this.tempLyricContent
  5885. }
  5886. if(this.isGridMusic||this.twoFingerType==4){
  5887. this.longItemFilePath = item.filePath
  5888. }else{
  5889. this.isShowEdit = !this.isShowEdit;
  5890. }
  5891. })
  5892. MenuItem({
  5893. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  5894. content: $r('app.string.select_all')
  5895. })
  5896. .onClick(() => {
  5897. this.isMultiSelect = !this.isMultiSelect
  5898. this.longItemFilePath = ''
  5899. this.selectedFiles.push(item)
  5900. })
  5901. MenuItem({
  5902. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.cut')),
  5903. content: $r('app.string.edit_audio')
  5904. })
  5905. .bindContentCover($$this.isEditAudio, this.EditAudioBuilder(item), {
  5906. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5907. })
  5908. .onClick(() => {
  5909. this.isEditAudio = !this.isEditAudio
  5910. })
  5911. MenuItem({
  5912. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  5913. content: $r('app.string.extract_accompaniment')
  5914. })
  5915. .bindContentCover($$this.isExtractAcc, this.ExtractAccBuilder(item), {
  5916. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5917. })
  5918. .onClick(() => {
  5919. if (!Utility.isNoble()) {
  5920. this.showVipDialog()
  5921. return
  5922. }
  5923. this.isExtractAcc = !this.isExtractAcc
  5924. })
  5925. MenuItem({
  5926. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.repeat')),
  5927. content: $r('app.string.converter_audio')
  5928. })
  5929. .bindContentCover($$this.isConverter, this.ConverterBuilder(item), {
  5930. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5931. })
  5932. .onClick(() => {
  5933. if (!Utility.isNoble()) {
  5934. this.showVipDialog()
  5935. return
  5936. }
  5937. this.isConverter = !this.isConverter
  5938. })
  5939. // MenuItem({
  5940. // symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.ai_edit')),
  5941. // content: $r('app.string.vocal_separation')
  5942. // })
  5943. // .bindContentCover($$this.isAIVoiceSeparation, this.AiBuilder(item), {
  5944. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5945. // })
  5946. // .onClick(() => {
  5947. // this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  5948. // })
  5949. MenuItem({
  5950. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_counterclockwise_clock')),
  5951. content: $r('app.string.change_tone')
  5952. })
  5953. .bindContentCover($$this.isChangeTone, this.ChangeToneBuilder(item), {
  5954. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5955. })
  5956. .onClick(() => {
  5957. this.isChangeTone = !this.isChangeTone
  5958. })
  5959. if(Utility.isVideoByExtension(item.filePath)){
  5960. MenuItem({
  5961. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.identify_song')),
  5962. content: $r('app.string.extract_audio')
  5963. })
  5964. .bindContentCover($$this.isExtractAudio, this.extractAudioFromVideoBuilder(item), {
  5965. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5966. })
  5967. .onClick(() => {
  5968. this.isExtractAudio = !this.isExtractAudio
  5969. })
  5970. }
  5971. MenuItem({
  5972. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.phone')),
  5973. content: $r('app.string.set_ring')
  5974. })
  5975. .onClick(async () => {
  5976. await PermissionUtil.activatePermission(item.filePath)
  5977. // if(item.filePath.includes(this.packName)){
  5978. setRingTone(this.context, item.filePath,item.name)
  5979. // }else{
  5980. // ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限设置铃声')
  5981. // }
  5982. this.longItemFilePath = ''
  5983. })
  5984. MenuItem({
  5985. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  5986. content: $r('app.string.rename')
  5987. })
  5988. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  5989. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5990. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  5991. .onClick(() => {
  5992. this.showReNameDialog(item, index + '', filePath)
  5993. this.longItemFilePath = ''
  5994. })
  5995. MenuItem({
  5996. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  5997. content: $r('app.string.delete')
  5998. })
  5999. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  6000. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  6001. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  6002. .onClick(() => {
  6003. this.selectedFiles.push(item)
  6004. this.showWarnIsDelete()
  6005. this.longItemFilePath = ''
  6006. })
  6007. MenuItem({
  6008. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  6009. content: $r('app.string.detail')
  6010. })
  6011. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  6012. height:'100%',
  6013. dragBar: true,
  6014. showClose: true,
  6015. blurStyle:BlurStyle.Thin,
  6016. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6017. backgroundColor:Color.Transparent,
  6018. title: { title: '详情信息' }
  6019. })
  6020. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6021. .onClick(() => {
  6022. if(this.isGridMusic||this.twoFingerType==4){
  6023. this.longItemFilePathDetail = item.filePath
  6024. }else{
  6025. this.isShowDetail = !this.isShowDetail
  6026. }
  6027. })
  6028. MenuItem({
  6029. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  6030. content: $r('app.string.share')
  6031. })
  6032. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  6033. .onClick(() => {
  6034. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  6035. this.longItemFilePath = ''
  6036. })
  6037. }
  6038. .font({ size: 14, weight: FontWeight.Normal })
  6039. }
  6040. .width(180)
  6041. }
  6042. .height('auto')
  6043. .enableScrollInteraction(true)
  6044. .scrollBar(this.isGridMusic?BarState.On:BarState.Off)
  6045. }
  6046. }
  6047. private listMaxScrollOffsetY: number = 0
  6048. private selectedIndex: number = -1
  6049. setlistTwoFingers() {
  6050. this.pinchValue = this.scaleValue;
  6051. Logger.info('this.pinchValue = ' + this.pinchValue);
  6052. if (this.pinchValue >= 1) {
  6053. this.twoFingerType++
  6054. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  6055. if (this.twoFingerType > 3) {
  6056. this.twoFingerType = 1
  6057. this.isGridMusic = true
  6058. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6059. }
  6060. } else {
  6061. this.twoFingerType--
  6062. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  6063. if (this.twoFingerType < 1) {
  6064. this.twoFingerType = 4
  6065. this.columns = 1
  6066. }
  6067. }
  6068. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  6069. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  6070. this.pinchValue = 1;
  6071. this.scaleValue = 1;
  6072. }
  6073. @Builder
  6074. getList(){
  6075. Stack() {
  6076. Refresh({ refreshing: $$this.isRefreshing, refreshingContent: this.contentNode }) {
  6077. this.getListView()
  6078. }
  6079. .pullDownRatio(this.ratioL)
  6080. .pullToRefresh(true)
  6081. .refreshOffset(0)
  6082. .onOffsetChange((offset: number) => {
  6083. // 越接近最大距离,下拉跟手系数越小。
  6084. this.ratioL = 1 - Math.pow((offset / this.maxRefreshingHeight), 3);
  6085. })
  6086. .onStateChange((refreshStatus: RefreshStatus) => {
  6087. console.info('onecold Refresh onStatueChange state is ' + refreshStatus);
  6088. })
  6089. .onRefreshing(async () => {
  6090. if(this.modeType==0){
  6091. this.getHistoryList(false)
  6092. this.asyncCurrentPathOnlyFile()
  6093. }else if(this.modeType == 1){
  6094. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6095. }else if(this.modeType == 2){
  6096. workerInstance.postMessage({ code: 3, data: this.context });
  6097. }else if(this.modeType == 3){
  6098. workerInstance.postMessage({ code: 4, data: this.context });
  6099. }else if(this.modeType == 4){
  6100. this.doSongListTask()
  6101. }
  6102. console.log('onRefreshing test');
  6103. })
  6104. if (this.isLoadingPage) {
  6105. Row() {
  6106. LoadingProgress()
  6107. .width(24)
  6108. .height(24)
  6109. .color(this.themeColor)
  6110. Text('加载中...')
  6111. .margin({ left: 8 })
  6112. .fontSize(13)
  6113. .fontColor($r('app.color.text_color'))
  6114. }
  6115. .padding({ left: 12, right: 12, top: 6, bottom: 6 })
  6116. .backgroundColor(this.isDarkMode ? '#66000000' : '#66FFFFFF')
  6117. .borderRadius(16)
  6118. .align(Alignment.Bottom)
  6119. .margin({ bottom: this.bottomBarHeight + this.bottomSafeHeight + 14 })
  6120. }
  6121. }
  6122. }
  6123. // 扫描当前目录下的文件,不扫描子目录
  6124. asyncCurrentPathOnlyFile(){
  6125. if(this.modeType==0){
  6126. const task = new taskpool.Task(scanCurrentDirectoryTask, getContext(this), this.currentPath,
  6127. this.lockPath,PreferencesUtil.getStringSync('COVER_API',''));
  6128. taskpool.execute(task, taskpool.Priority.HIGH).then(()=>{
  6129. if(this.modeType==0){
  6130. setTimeout(()=>{
  6131. this.isRefreshing =false
  6132. this.deleteCache(this.currentPath)
  6133. this.getSortedFiles(this.currentPath)
  6134. },500)
  6135. }
  6136. }).catch((e:object)=>{
  6137. this.isRefreshing =false
  6138. console.info("onecold task1 catch e: " + e);
  6139. })
  6140. }
  6141. }
  6142. @Builder
  6143. getListView() {
  6144. List({ scroller: this.listScroller }) {
  6145. // ListItemGroup({ header: this.coverHeader() }) {
  6146. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  6147. ListItem() {
  6148. Column() {
  6149. if (item.type === CommonConstants.TYPE_IS_DIR
  6150. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  6151. this.DirItem(item, index)
  6152. } else {
  6153. this.MusicItem(item, index)
  6154. }
  6155. }
  6156. }
  6157. .clickEffect({ level: ClickEffectLevel.LIGHT })
  6158. .swipeAction((
  6159. ((this.isSwipe && !this.isScrolling) &&
  6160. (this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack)))
  6161. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  6162. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath),
  6163. start:null,edgeEffect: SwipeEdgeEffect.None } : {}) //左滑
  6164. .onClick(() => {
  6165. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  6166. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  6167. this.handleFileSelection(item, !isChecked);
  6168. } else {
  6169. this.doPlay(item, index)
  6170. }
  6171. })
  6172. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  6173. }
  6174. .onScrollStart(() => {
  6175. this.isScrolling = true
  6176. this.listVisibleStart = -1
  6177. this.listVisibleEnd = -1
  6178. this.listScrollAlphaCheckAt = 0
  6179. this.listScrollPagingCheckAt = 0
  6180. this.listScrollLastAlphaStart = -1
  6181. this.listScrollLastPagingEnd = -1
  6182. if (this.alphaBetRebuildTimer) {
  6183. clearTimeout(this.alphaBetRebuildTimer)
  6184. this.alphaBetRebuildTimer = 0
  6185. }
  6186. this.showAlphabetIndex()
  6187. })
  6188. .onScrollIndex((start: number,center:number,end:number) => {
  6189. this.selectedIndex = start
  6190. this.listVisibleStart = start
  6191. this.listVisibleEnd = end
  6192. this.lastVisibleEndIndex = end
  6193. if (!this.isMediaLibraryWarmupWindow()) {
  6194. this.warmupListVisibleThumbs(start, end)
  6195. }
  6196. const now = Date.now()
  6197. const alphaDelta = this.listScrollLastAlphaStart >= 0 ? Math.abs(start - this.listScrollLastAlphaStart) : 999
  6198. if (!this.isMediaLibraryWarmupWindow() &&
  6199. start >= 0 && start < this.videoLocalList.length &&
  6200. (alphaDelta >= 2 || now - this.listScrollAlphaCheckAt >= 48)) {
  6201. this.listScrollAlphaCheckAt = now
  6202. this.listScrollLastAlphaStart = start
  6203. const nextAlphaIndex = this.findAlphaBetIndex(this.videoLocalList[start])
  6204. if (nextAlphaIndex !== this.selectAlphaBetIndex) {
  6205. this.selectAlphaBetIndex = nextAlphaIndex
  6206. }
  6207. }
  6208. const pagingDelta = this.listScrollLastPagingEnd >= 0 ? Math.abs(end - this.listScrollLastPagingEnd) : 999
  6209. if (pagingDelta >= 2 || now - this.listScrollPagingCheckAt >= 32) {
  6210. this.listScrollPagingCheckAt = now
  6211. this.listScrollLastPagingEnd = end
  6212. this.tryTriggerLoadNextPageByScroll(end)
  6213. }
  6214. })
  6215. .onScrollStop(() => {
  6216. if(this.isScrolling){
  6217. this.isScrolling = false
  6218. }
  6219. this.flushPendingCoverThumbRefresh()
  6220. if (this.alphaBetDirty) {
  6221. this.scheduleAlphaBetRebuild(0)
  6222. }
  6223. this.hideAlphabetIndexAfterDelay(1500)
  6224. })
  6225. .onReachEnd(() => {
  6226. if(this.modeType === 4 )//歌单不能加载下一页
  6227. return;
  6228. // 触底加载下一页
  6229. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  6230. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  6231. return;
  6232. }
  6233. if (this.hasMoreData && !this.isLoadingPage && !this.isPagingTransition) {
  6234. this.scheduleLoadNextPage();
  6235. }
  6236. })
  6237. .scrollBar(BarState.Off)
  6238. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  6239. .gesture(PinchGesture({ fingers: 2 })
  6240. .onActionEnd((event: GestureEvent) => {
  6241. this.setlistTwoFingers()
  6242. })
  6243. .onActionUpdate(e => {
  6244. this.scaleValue = this.pinchValue * e.scale
  6245. })
  6246. .onActionStart(e => {
  6247. }))
  6248. .contentStartOffset(this.topSafeHeight + 55)
  6249. .scrollBar(BarState.Off)
  6250. .contentEndOffset(this.bottomBarHeight+this.bottomSafeHeight)
  6251. .cachedCount(this.modeType == 1 ? 4 : 8)
  6252. // .reuseId('list_item')
  6253. .borderRadius(20)
  6254. .layoutWeight(1)
  6255. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  6256. .lanes(
  6257. new BreakpointType<number>({
  6258. sm: 1,
  6259. md: 2,
  6260. lg: 2,
  6261. xl: 3,
  6262. xxl: 4
  6263. }).getValue(this.currentBreakpoint),
  6264. new BreakpointType<number>({
  6265. sm: 0,
  6266. md: 12,
  6267. lg: 12,
  6268. xl: 16,
  6269. xxl: 20
  6270. }).getValue(this.currentBreakpoint)
  6271. )
  6272. .onAreaChange((oldValue: Area, newValue: Area) => {
  6273. this.listArea = newValue
  6274. if (this.twoFingerType == 3) {
  6275. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  6276. } else if (this.twoFingerType == 2) {
  6277. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  6278. } else if (this.twoFingerType == 1) {
  6279. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  6280. }
  6281. })
  6282. .onScrollFrameBegin((offset: number) => {
  6283. const currentOffsetY = this.listScroller.currentOffset().yOffset;
  6284. this.updateTitleBarByScrollOffset(currentOffsetY)
  6285. return { offsetRemain: offset };
  6286. })
  6287. }
  6288. setBarHeightNormal() {
  6289. this.hideDone = false;
  6290. this.getUIContext().animateTo({
  6291. duration: 300
  6292. }, () => {
  6293. this.bottomBarHeight = 68 + 0;
  6294. this.topBarHeight = 50 + 0;
  6295. this.barOpacity = 1;
  6296. this.barBottomOpacity = 1
  6297. this.currentYOffset = 0;
  6298. this.isHiding = false;
  6299. });
  6300. }
  6301. setBarHeightHide(offset: number) {
  6302. if (offset > 0 && !this.hideDone) {
  6303. this.currentYOffset += offset;
  6304. if (this.currentYOffset <= 100) {
  6305. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  6306. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  6307. this.barOpacity = 1 - this.currentYOffset / 100;
  6308. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  6309. } else {
  6310. this.topBarHeight = 0;
  6311. this.bottomBarHeight = 0;
  6312. this.barBottomOpacity = 0
  6313. this.barOpacity = 0;
  6314. this.hideDone = true;
  6315. }
  6316. this.isHiding = true;
  6317. }
  6318. if (offset < 0 && this.isHiding) {
  6319. this.hideDone = false;
  6320. this.getUIContext().animateTo({
  6321. duration: 300
  6322. }, () => {
  6323. this.bottomBarHeight = 68 + 0;
  6324. this.topBarHeight = 50 + 0;
  6325. this.barOpacity = 1;
  6326. this.barBottomOpacity = 1
  6327. this.currentYOffset = 0;
  6328. this.isHiding = false;
  6329. });
  6330. }
  6331. }
  6332. //这个方法没隐藏bottomBar,只隐藏topbar
  6333. setBarHeightHide2(offset: number) {
  6334. if (offset > 0 && !this.hideDone) {
  6335. this.currentYOffset += offset;
  6336. if (this.currentYOffset <= 100) {
  6337. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  6338. this.barOpacity = 1 - this.currentYOffset / 100;
  6339. } else {
  6340. this.topBarHeight = 0;
  6341. this.barOpacity = 0;
  6342. this.hideDone = true;
  6343. }
  6344. this.isHiding = true;
  6345. }
  6346. if (offset < 0 && this.isHiding) {
  6347. this.hideDone = false;
  6348. this.getUIContext().animateTo({
  6349. duration: 300
  6350. }, () => {
  6351. this.topBarHeight = 50 + 0;
  6352. this.barOpacity = 1;
  6353. this.currentYOffset = 0;
  6354. this.isHiding = false;
  6355. });
  6356. }
  6357. }
  6358. private async doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean,isOpen?:boolean) {
  6359. Logger.info(`heanup doPlay被调用 - 歌曲: ${item.name}, 文件路径: ${item.filePath}, 索引: ${index}, 类型: ${item.type}, isFromSonPlayList: ${isFromSonPlayList}`)
  6360. switch (item.type) {
  6361. case CommonConstants.TYPE_IS_DIR:
  6362. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  6363. let shouldScrollTopNow = true
  6364. let offsetB = 0
  6365. if(this.twoFingerType==4){
  6366. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6367. let cur = this.waterScroller.currentOffset()
  6368. if (cur && typeof cur.yOffset === 'number') {
  6369. offsetB = cur.yOffset
  6370. }
  6371. }
  6372. this.mScrollMap.set('lastWaterDirScrollOffset', offsetB)
  6373. }else
  6374. if (this.isGridMusic) {
  6375. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6376. let cur = this.scroller.currentOffset()
  6377. if (cur && typeof cur.yOffset === 'number') {
  6378. offsetB = cur.yOffset
  6379. }
  6380. }
  6381. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  6382. } else {
  6383. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6384. let cur = this.listScroller.currentOffset()
  6385. if (cur && typeof cur.yOffset === 'number') {
  6386. offsetB = cur.yOffset
  6387. }
  6388. }
  6389. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  6390. }
  6391. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  6392. this.showVerifyDialog()
  6393. this.currentTitleName = '私密音频'
  6394. this.currentTitleCover = $r('app.media.alt')
  6395. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  6396. this.titleName = '最近播放'
  6397. this.currentTitleCover = $r('app.media.alt')
  6398. this.currentTitleName = '最近播放'
  6399. //加载动画效果
  6400. this.updateListData(this.historyList, true)
  6401. // this.videoLocalList = this.historyList
  6402. if (ArrayUtil.isEmpty(this.historyList)) {
  6403. ToastUtil.showToast('最近播放记录空空如也')
  6404. } else {
  6405. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  6406. }
  6407. this.isHistory = true
  6408. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  6409. this.titleName = '我的收藏'
  6410. this.currentTitleName = '我的收藏'
  6411. this.currentTitleCover = $r('app.media.alt')
  6412. //加载动画效果
  6413. this.updateListData(this.favList, true)
  6414. if (ArrayUtil.isEmpty(this.favList)) {
  6415. ToastUtil.showToast('无音乐收藏记录')
  6416. } else {
  6417. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  6418. }
  6419. this.isFavMusic = true
  6420. } else {
  6421. this.currentTitleName = item.name
  6422. this.currentPath = item.filePath
  6423. this.currentTitleCover = $r('app.media.alt')
  6424. shouldScrollTopNow = false
  6425. this.getSortedFiles(this.currentPath, false, undefined, undefined, undefined, true, true)
  6426. }
  6427. //进入歌单的时候的滚动位置在顶部
  6428. if (shouldScrollTopNow) {
  6429. if(this.twoFingerType==4){
  6430. setTimeout(() => {
  6431. this.waterScroller.scrollEdge(Edge.Top)
  6432. this.scroller.scrollEdge(Edge.Top)
  6433. }, 200)
  6434. }else{
  6435. if (this.isGridMusic) {
  6436. this.scroller.scrollToIndex(0,false)
  6437. }else{
  6438. this.listScroller.scrollToIndex(0,false)
  6439. }
  6440. }
  6441. }
  6442. this.rightTopImage = $r('sys.symbol.chevron_left')
  6443. break;
  6444. case CommonConstants.TYPE_IS_ARTIST:
  6445. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  6446. let offsetA = 0
  6447. if(this.twoFingerType==4){
  6448. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6449. let cur = this.waterScroller.currentOffset()
  6450. if (cur && typeof cur.yOffset === 'number') {
  6451. offsetA = cur.yOffset
  6452. }
  6453. }
  6454. this.mScrollMap.set('lastWaterArtistScrollOffset', offsetA)
  6455. }else
  6456. if (this.isGridMusic) {
  6457. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6458. let cur = this.scroller.currentOffset()
  6459. if (cur && typeof cur.yOffset === 'number') {
  6460. offsetA = cur.yOffset
  6461. }
  6462. }
  6463. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  6464. } else {
  6465. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6466. let cur = this.listScroller.currentOffset()
  6467. if (cur && typeof cur.yOffset === 'number') {
  6468. offsetA = cur.yOffset
  6469. }
  6470. }
  6471. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  6472. }
  6473. // 进入艺术家详情页前,先加载详情页的排序类型
  6474. // 注意:需要临时设置isCanBack=true,以便loadSortTypeForCurrentMode读取详情页的排序设置
  6475. const artistOriginalIsCanBack = this.isCanBack;
  6476. this.isCanBack = true;
  6477. const artistDetailSortType = this.loadSortTypeForCurrentMode();
  6478. this.isCanBack = artistOriginalIsCanBack; // 恢复原值
  6479. Logger.info('heanup LocalMusic', `进入艺术家详情页: 加载详情页排序 sortType=${artistDetailSortType}`);
  6480. // 缓存键需要包含排序类型,因为不同的排序类型会产生不同的数据
  6481. const artistCacheKey = `${item.name}_sort_${artistDetailSortType}`;
  6482. let mList = this.artistMap.get(artistCacheKey)
  6483. if (mList === undefined || ArrayUtil.isEmpty(mList)) {
  6484. // 使用详情页的排序类型查询
  6485. mList = await this.table.querySongsByArtist(item.name, artistDetailSortType, this.isShowFileName);
  6486. if (ArrayUtil.isNotEmpty(mList)) {
  6487. this.artistMap.set(artistCacheKey, mList);
  6488. }
  6489. }
  6490. // 设置当前排序类型为详情页排序
  6491. this.sortType = artistDetailSortType;
  6492. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  6493. // 注意:不再调用 Utility.doSortListAscending,因为数据已经按 artistDetailSortType 排序了
  6494. const nextArtistCountMap = new Map(this.artistSongCountMap);
  6495. nextArtistCountMap.set(item.name, mList.length);
  6496. this.artistSongCountMap = nextArtistCountMap;
  6497. this.isCanBack = true
  6498. this.hasMoreData = false
  6499. this.isLoadingPage = false
  6500. this.pageCache.clear()
  6501. this.pageHasMoreCache.clear()
  6502. this.pageTotalCountCache.clear()
  6503. this.prefetchingPages.clear()
  6504. this.lastScrollTriggerPage = -1
  6505. this.lastVisibleEndIndex = -1
  6506. this.isPagingTransition = false
  6507. if (this.pagingScheduleTimer) {
  6508. clearTimeout(this.pagingScheduleTimer)
  6509. this.pagingScheduleTimer = 0
  6510. }
  6511. this.totalCount = mList.length
  6512. this.titleName = item.name
  6513. this.currentTitleName = '艺术家:' + item.name
  6514. if (item.pixelMapPath) {
  6515. this.currentTitleCover = item.pixelMapPath
  6516. }
  6517. this.updateListData(mList, true, true) // 详情页立即替换列表,避免旧列表顶部闪现
  6518. } else {
  6519. ToastUtil.showToast('未找到该艺术家的歌曲');
  6520. return;
  6521. }
  6522. this.rightTopImage = $r('sys.symbol.chevron_left')
  6523. //进入歌单的时候的滚动位置在顶部
  6524. if(this.twoFingerType==4){
  6525. setTimeout(() => {
  6526. this.waterScroller.scrollEdge(Edge.Top)
  6527. this.scroller.scrollEdge(Edge.Top)
  6528. }, 380)
  6529. }else{
  6530. if (this.isGridMusic) {
  6531. this.scroller.scrollEdge(Edge.Top)
  6532. }else{
  6533. this.listScroller.scrollEdge(Edge.Top)
  6534. }
  6535. }
  6536. break;
  6537. case CommonConstants.TYPE_IS_ALBUM:
  6538. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  6539. let offset = 0
  6540. if(this.twoFingerType==4){
  6541. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6542. let cur = this.waterScroller.currentOffset()
  6543. if (cur && typeof cur.yOffset === 'number') {
  6544. offset = cur.yOffset
  6545. }
  6546. }
  6547. this.mScrollMap.set('lastWaterAlBumScrollOffset', offset)
  6548. }else
  6549. if (this.isGridMusic) {
  6550. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6551. let cur = this.scroller.currentOffset()
  6552. if (cur && typeof cur.yOffset === 'number') {
  6553. offset = cur.yOffset
  6554. }
  6555. }
  6556. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  6557. } else {
  6558. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6559. let cur = this.listScroller.currentOffset()
  6560. if (cur && typeof cur.yOffset === 'number') {
  6561. offset = cur.yOffset
  6562. }
  6563. }
  6564. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  6565. }
  6566. // 进入专辑详情页前,先加载详情页的排序类型
  6567. // 注意:需要临时设置isCanBack=true,以便loadSortTypeForCurrentMode读取详情页的排序设置
  6568. const albumOriginalIsCanBack = this.isCanBack;
  6569. this.isCanBack = true;
  6570. const albumDetailSortType = this.loadSortTypeForCurrentMode();
  6571. this.isCanBack = albumOriginalIsCanBack; // 恢复原值
  6572. Logger.info('heanup LocalMusic', `进入专辑详情页: 加载详情页排序 sortType=${albumDetailSortType}`);
  6573. // 缓存键需要包含排序类型,因为不同的排序类型会产生不同的数据
  6574. const albumCacheKey = `${item.name}_sort_${albumDetailSortType}`;
  6575. let albumList = this.albumMap.get(albumCacheKey)
  6576. if (albumList === undefined || ArrayUtil.isEmpty(albumList)) {
  6577. // 使用详情页的排序类型查询
  6578. albumList = await this.table.querySongsByAlbum(item.name, albumDetailSortType, this.isShowFileName);
  6579. if (ArrayUtil.isNotEmpty(albumList)) {
  6580. this.albumMap.set(albumCacheKey, albumList);
  6581. }
  6582. }
  6583. // 设置当前排序类型为详情页排序
  6584. this.sortType = albumDetailSortType;
  6585. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  6586. // 注意:不再调用 Utility.doSortListAscending,因为数据已经按 albumDetailSortType 排序了
  6587. const nextAlbumCountMap = new Map(this.albumSongCountMap);
  6588. nextAlbumCountMap.set(item.name, albumList.length);
  6589. this.albumSongCountMap = nextAlbumCountMap;
  6590. this.isCanBack = true
  6591. this.hasMoreData = false
  6592. this.isLoadingPage = false
  6593. this.pageCache.clear()
  6594. this.pageHasMoreCache.clear()
  6595. this.pageTotalCountCache.clear()
  6596. this.prefetchingPages.clear()
  6597. this.lastScrollTriggerPage = -1
  6598. this.lastVisibleEndIndex = -1
  6599. this.isPagingTransition = false
  6600. if (this.pagingScheduleTimer) {
  6601. clearTimeout(this.pagingScheduleTimer)
  6602. this.pagingScheduleTimer = 0
  6603. }
  6604. this.totalCount = albumList.length
  6605. this.titleName = item.name
  6606. this.currentTitleName = '专辑:' + item.name
  6607. if (item.pixelMapPath) {
  6608. this.currentTitleCover = item.pixelMapPath
  6609. }
  6610. this.updateListData(albumList, true, true) // 详情页立即替换列表,避免旧列表顶部闪现
  6611. this.mScrollMap.set(item.name, this.selectedIndex)
  6612. this.rightTopImage = $r('sys.symbol.chevron_left')
  6613. } else {
  6614. ToastUtil.showToast('未找到该专辑的歌曲');
  6615. return;
  6616. }
  6617. //进入歌单的时候的滚动位置在顶部
  6618. if(this.twoFingerType==4){
  6619. setTimeout(() => {
  6620. this.waterScroller.scrollEdge(Edge.Top)
  6621. this.scroller.scrollEdge(Edge.Top)
  6622. }, 380)
  6623. }else{
  6624. if (this.isGridMusic) {
  6625. this.scroller.scrollEdge(Edge.Top)
  6626. }else{
  6627. this.listScroller.scrollEdge(Edge.Top)
  6628. }
  6629. }
  6630. break;
  6631. case CommonConstants.TYPE_IS_CSJAD:
  6632. return
  6633. break;
  6634. case CommonConstants.TYPE_LOCAL:
  6635. if(item&&item.filePath.toLowerCase().endsWith('.cue')){
  6636. const cueinfo:CueInfo = await parseCueFile(item.filePath)
  6637. const cueTracks:CueTrack[] = cueinfo.tracks
  6638. console.log('onecold cue cueTracks =', JSON.stringify(cueTracks));
  6639. if(ArrayUtil.isNotEmpty(cueTracks)){
  6640. this.showCueDialog(cueTracks,cueinfo)
  6641. }
  6642. // this.showCueSheet = !this.showCueSheet
  6643. return
  6644. }
  6645. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6646. this.stop();
  6647. }
  6648. if (isOpen) {
  6649. this.currentSong = item
  6650. if (index !== undefined) {
  6651. this.curIndex = index
  6652. }
  6653. this.songList = []
  6654. this.songList.push(item)
  6655. this.sonDataSource.pushArrayData(this.songList)
  6656. this.playQueueScope = 'single'
  6657. }else if(isFromSonPlayList){ //点击来自右下角的播放列表
  6658. this.currentSong = item
  6659. if (index !== undefined) {
  6660. this.curIndex = index
  6661. }
  6662. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  6663. Logger.info(`heanup isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  6664. this.playQueueScope = 'playlist'
  6665. // 确保歌单路径列表已设置(从songList重新构建,以防被清空)
  6666. if (this.currentPlaylistSongFilePaths.length === 0 && this.songList.length > 0) {
  6667. this.currentPlaylistSongFilePaths = this.songList.map(song => song.filePath);
  6668. Logger.info(`heanup isFromSonPlayList - 重新构建歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  6669. }
  6670. }else {
  6671. const globalVideoList = this.buildPlayQueueFromView();
  6672. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  6673. if (this.curIndex < 0) {
  6674. globalVideoList.push(item);
  6675. this.curIndex = globalVideoList.length - 1;
  6676. }
  6677. this.songList = globalVideoList
  6678. this.sonDataSource.pushArrayData(this.songList)
  6679. this.currentSong = this.songList[this.curIndex]
  6680. // 只在非歌单模式下清空歌单路径列表
  6681. if (this.modeType !== 4) {
  6682. this.currentPlaylistSongFilePaths = [];
  6683. Logger.info(`heanup doPlay设置播放列表 - 总歌曲数: ${this.songList.length}, 当前索引: ${this.curIndex}, 当前歌曲: ${this.currentSong?.name}, 已清空歌单路径列表(modeType=${this.modeType})`)
  6684. } else {
  6685. // 歌单模式:确保歌单路径列表已设置
  6686. if (this.currentPlaylistSongFilePaths.length === 0 && this.songList.length > 0) {
  6687. this.currentPlaylistSongFilePaths = this.songList.map(song => song.filePath);
  6688. Logger.info(`heanup doPlay设置播放列表 - 从songList重新构建歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  6689. } else {
  6690. Logger.info(`heanup doPlay设置播放列表 - 歌单模式,保持歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  6691. }
  6692. }
  6693. }
  6694. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  6695. this.videoUrl = this.currentSong.filePath
  6696. this.name = this.currentSong.name
  6697. this.cover = this.currentSong.pixelMapPath
  6698. this.artist = this.currentSong.artist
  6699. LogUtil.info('onecold this.currentSong.cover =' + this.currentSong.pixelMapPath)
  6700. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  6701. this.startPlayOrResumePlay()
  6702. break;
  6703. case CommonConstants.TYPE_WEBDAV:
  6704. case CommonConstants.TYPE_SMB:
  6705. case CommonConstants.TYPE_NAVIDROME:
  6706. case CommonConstants.TYPE_FTP:
  6707. case CommonConstants.TYPE_BAIDU:
  6708. case CommonConstants.TYPE_JELLYFIN:
  6709. case CommonConstants.TYPE_EMBY:
  6710. case CommonConstants.TYPE_AUDIOSTATION:
  6711. case CommonConstants.TYPE_PLEX:
  6712. case CommonConstants.TYPE_DAOLIYU:
  6713. // 处理网络音频播放(WebDAV/SMB/Navidrome/Jellyfin/Emby/AudioStation/Plex/道理鱼/Baidu)
  6714. Logger.info(`heanup 处理云端音频播放: ${item.name}, URL: ${item.filePath}`)
  6715. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6716. this.stop();
  6717. }
  6718. if (isOpen) {
  6719. this.currentSong = item
  6720. if (index !== undefined) {
  6721. this.curIndex = index
  6722. }
  6723. this.songList = []
  6724. this.songList.push(item)
  6725. this.sonDataSource.pushArrayData(this.songList)
  6726. } else if (isFromSonPlayList) {
  6727. // 点击来自右下角的播放列表
  6728. this.currentSong = item
  6729. if (index !== undefined) {
  6730. this.curIndex = index
  6731. }
  6732. // 设置播放队列作用域为歌单
  6733. this.playQueueScope = 'playlist'
  6734. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  6735. Logger.info(`heanup 网络音频 isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}, playQueueScope=${this.playQueueScope}`)
  6736. } else {
  6737. // 从全局网络音频列表中查找
  6738. let globalVideoList = this.videoLocalList.filter(video => isRemoteCloudType(video.type)) as VideoItem[];
  6739. this.curIndex = globalVideoList.findIndex(video => video.filePath === item.filePath);
  6740. if (this.curIndex === -1 && index !== undefined) {
  6741. this.curIndex = index;
  6742. }
  6743. this.songList = globalVideoList.length > 0 ? globalVideoList : [item];
  6744. this.currentSong = this.songList[this.curIndex];
  6745. this.sonDataSource.pushArrayData(this.songList)
  6746. }
  6747. await this.hydrateRemoteSongFromDb(this.currentSong);
  6748. await this.hydrateRemoteSongFromDb(this.currentSong);
  6749. AppStorage.setOrCreate('currentSong', this.currentSong);
  6750. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  6751. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  6752. context: this.context,
  6753. autoParseMusicName: this.autoParseMusicName
  6754. });
  6755. Logger.info(TAG, `WebDAV URL同步构建完成(分支2): ${this.videoUrl}`);
  6756. this.name = this.currentSong.name
  6757. this.cover = this.currentSong.pixelMapPath
  6758. this.artist = this.currentSong.artist
  6759. Logger.info(`heanup 准备播放网络音频 - 歌名: ${this.name}, 艺术家: ${this.artist}, 完整URL: ${this.videoUrl}`)
  6760. this.startPlayOrResumePlay()
  6761. break;
  6762. }
  6763. }
  6764. private cueComponentId: number = 0
  6765. //显示cue分轨列表对话框
  6766. showCueDialog(cueTracks:CueTrack[],cueinfo:CueInfo){
  6767. this.getUIContext().getPromptAction().openCustomDialog({
  6768. builder: () => {
  6769. this.cueComptentBuilder(cueTracks,cueinfo)
  6770. },
  6771. isModal:true,
  6772. showInSubWindow:false,
  6773. maskColor: Color.Transparent,
  6774. dialogTransition: // 设置弹窗内容显示的过渡效果
  6775. TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  6776. .animation({ duration: 600, curve: Curve.Smooth }),
  6777. maskTransition: // 设置蒙层显示的过渡效果
  6778. TransitionEffect.opacity(0.5)
  6779. .animation({ duration: 600, curve: Curve.Smooth })
  6780. }).then((dialogId: number) => {
  6781. this.cueComponentId = dialogId
  6782. })
  6783. .catch((error: BusinessError) => {
  6784. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  6785. })
  6786. }
  6787. @Builder
  6788. cueComptentBuilder(cueTracks:CueTrack[]=[],cueinfo:CueInfo){
  6789. CueComptent({
  6790. title:cueinfo.title,
  6791. cueTracks:cueTracks,
  6792. isLongNameRoLL:this.isLongNameRoLL,
  6793. onCancel:()=>{
  6794. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId)
  6795. },
  6796. onDoItemClick: async (item: CueTrack, index: number)=>{
  6797. //获取cueinfo对应的filePath
  6798. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  6799. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, cueinfo.filePath)
  6800. this.currentSong = Utility.getItemByFilePath(globalVideoList, cueinfo.filePath)
  6801. console.info('onecold cueinfo.filePath=', cueinfo.filePath)
  6802. console.info('onecold this.currentSong =', JSON.stringify(this.currentSong))
  6803. if (this.currentSong){
  6804. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6805. this.stop();//播放之前先停止之前播放。
  6806. }
  6807. this.songList = globalVideoList
  6808. this.sonDataSource.pushArrayData(this.songList)
  6809. if (this.currentSong) {
  6810. try {
  6811. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  6812. context: this.context,
  6813. autoParseMusicName: this.autoParseMusicName
  6814. });
  6815. } catch (error) {
  6816. Logger.error(TAG, `CUE 点播构建播放地址失败: ${(error as Error).message}`);
  6817. this.videoUrl = this.currentSong.filePath;
  6818. }
  6819. }
  6820. this.name = item.title||this.currentSong.name
  6821. this.cover = this.currentSong.pixelMapPath
  6822. this.artist = item.performer||this.currentSong.artist
  6823. this.currentSong.name = this.name
  6824. this.currentSong.artist = this.artist
  6825. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  6826. this.startPlayOrResumePlay(item.startOffset)//从cue的某个位置开始播放
  6827. }
  6828. }
  6829. })
  6830. }
  6831. @State isFrontWhite: boolean = false
  6832. setShowPlayTrue(){
  6833. this.getUIContext()?.animateTo({
  6834. duration: 500,
  6835. curve: Curve.Friction
  6836. }, () => {
  6837. this.isShowPlay = true;
  6838. });
  6839. }
  6840. setShowPlayFalse(){
  6841. this.getUIContext()?.animateTo({
  6842. duration: 500,
  6843. curve: Curve.Friction
  6844. }, () => {
  6845. this.isShowPlay = false;
  6846. });
  6847. }
  6848. //打开播放页
  6849. showPlayerView() {
  6850. console.info('onecold showPlayerView this.songList'+ JSON.stringify(this.songList))
  6851. if (ArrayUtil.isNotEmpty(this.songList)) {
  6852. // this.setShowPlayTrue()
  6853. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
  6854. this.initLyric(lyricPath);
  6855. this.startAutoHide();
  6856. } else {
  6857. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  6858. }
  6859. }
  6860. //打开播放列表
  6861. openPlayList(){
  6862. if (ArrayUtil.isNotEmpty(this.songList)) {
  6863. this.isShowSheet = !this.isShowSheet;
  6864. this.isFrontWhite = false
  6865. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  6866. this.scrollIndex()
  6867. // 只有在播放本地音乐时才自动加载完整列表
  6868. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_LOCAL) {
  6869. void this.hydrateFullMediaPlayListIfNeeded();
  6870. }
  6871. } else {
  6872. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  6873. }
  6874. }
  6875. scrollIndex(){
  6876. try {
  6877. setTimeout(() => {
  6878. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  6879. if(this.curIndex>60){
  6880. this.playListScroller.scrollToIndex(this.curIndex,false, ScrollAlign.CENTER)
  6881. }else{
  6882. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  6883. }
  6884. })
  6885. }, 123)
  6886. }catch (error) {
  6887. console.error(`onecold scrollIndex出错: ${error}`);
  6888. }
  6889. }
  6890. scrollIndexMain(dialogId?:string){
  6891. try {
  6892. setTimeout(() => {
  6893. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  6894. console.info('heanup scrollIndexMain this.curIndex='+this.curIndex)
  6895. if(dialogId)
  6896. DialogHelper.closeDialog(dialogId)
  6897. let isAni:boolean = false
  6898. if(this.curIndex<50){
  6899. isAni = true
  6900. }
  6901. if(this.twoFingerType==4){
  6902. this.waterScroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  6903. }else{
  6904. if(this.isGridMusic){
  6905. this.scroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  6906. }else{
  6907. this.listScroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  6908. }
  6909. }
  6910. })
  6911. }, 123)
  6912. }catch (error) {
  6913. console.error(`onecold scrollIndexMain出错: ${error}`);
  6914. }
  6915. }
  6916. // 智能定位当前播放歌曲,如果当前页没有则加载完整列表
  6917. async locateCurrentSong(): Promise<void> {
  6918. if (!this.currentSong) {
  6919. console.warn("heanup locateCurrentSong: 当前没有播放的歌曲");
  6920. return;
  6921. }
  6922. // 检查当前播放歌曲是否在已加载的列表中
  6923. const targetIndex = Utility.getIndexFromList(this.videoLocalList, this.currentSong.filePath);
  6924. if (targetIndex > 0) {
  6925. // 歌曲在当前列表中,直接滚动
  6926. console.info("heanup locateCurrentSong: 找到歌曲,索引=" + targetIndex);
  6927. this.curIndex = targetIndex;
  6928. this.scrollIndexMain();
  6929. } else {
  6930. // 歌曲不在当前列表中,加载当前歌曲再第几页完整列表后再定位
  6931. console.info("heanup locateCurrentSong: 歌曲不在当前列表,开始加载完整列表");
  6932. const dialogID = DialogHelper.showLoadingDialog()
  6933. await this.hydrateFullMediaPlayListIfNeeded(false);
  6934. this.curIndex = Utility.getIndexFromList(this.videoLocalList, this.currentSong.filePath);
  6935. this.scrollIndexMain(dialogID);
  6936. }
  6937. }
  6938. //播放列表布局
  6939. @Builder
  6940. PlayListSheet() {
  6941. Column() {
  6942. this.PlayList()
  6943. }
  6944. .width('100%')
  6945. .height('100%')
  6946. }
  6947. @State titleStr: string = ''
  6948. @State ablumStr: string = ''
  6949. @State artistStr: string = ''
  6950. @State lyricConStr: string = ''
  6951. @State currentEditItem: string = ''
  6952. @State yearStr: string = ''
  6953. @State trackStr: string = ''
  6954. @State genreStr: string = ''
  6955. @State imagePathStr: string = ''
  6956. @State albumArtistStr: string = ''
  6957. @State composerStr: string = ''
  6958. @State lyricistStr: string = ''
  6959. @State commentStr: string = ''
  6960. @State discStr: string = ''
  6961. doUpdateData() {
  6962. setTimeout(async () => {
  6963. if (this.modeType === 0) {
  6964. this.deleteCache(this.currentPath)
  6965. await this.resetAndLoadFirstPage();
  6966. }else if (this.modeType === 1){
  6967. await this.resetAndLoadFirstPage();
  6968. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6969. }
  6970. }, 500)
  6971. }
  6972. doAllUpdateData() {
  6973. setTimeout(async () => {
  6974. if (this.modeType === 0) {
  6975. this.deleteCache(this.currentPath)
  6976. await this.resetAndLoadFirstPage();
  6977. }else{
  6978. await this.resetAndLoadFirstPage();
  6979. }
  6980. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6981. workerInstance.postMessage({ code: 3, data: this.context });
  6982. workerInstance.postMessage({ code: 4, data: this.context });
  6983. }, 999)
  6984. }
  6985. private delayMs(ms: number): Promise<void> {
  6986. return new Promise(resolve => {
  6987. setTimeout(() => resolve(), ms);
  6988. });
  6989. }
  6990. private async appendItemsSmoothly(items: VideoItem[]): Promise<void> {
  6991. if (!items || items.length === 0) {
  6992. return;
  6993. }
  6994. const isMediaLibraryListMode = this.isMediaLibraryListMode();
  6995. const isHeavyGridWaterMode = this.isGridMusic || this.twoFingerType == 4;
  6996. const directAppendThreshold = isHeavyGridWaterMode ? 8 : (isMediaLibraryListMode ? 6 : 12);
  6997. if (!this.isScrolling || items.length <= directAppendThreshold) {
  6998. this.videoLocalList.push(...items);
  6999. this.dataSource.appendArrayData(items);
  7000. return;
  7001. }
  7002. const chunkSize = isHeavyGridWaterMode
  7003. ? Math.max(3, Math.min(6, Math.floor(this.pageSize * 0.15)))
  7004. : (isMediaLibraryListMode
  7005. ? Math.max(2, Math.min(4, Math.floor(this.pageSize * 0.08)))
  7006. : Math.max(4, Math.min(8, Math.floor(this.pageSize * 0.18))));
  7007. const chunkDelay = isHeavyGridWaterMode ? 12 : (isMediaLibraryListMode ? 10 : 8);
  7008. for (let index = 0; index < items.length; index += chunkSize) {
  7009. const chunk = items.slice(index, Math.min(index + chunkSize, items.length));
  7010. this.videoLocalList.push(...chunk);
  7011. this.dataSource.appendArrayData(chunk);
  7012. if (index + chunkSize < items.length) {
  7013. await this.delayMs(chunkDelay);
  7014. }
  7015. }
  7016. }
  7017. /**
  7018. * 加载指定页的数据
  7019. */
  7020. private async loadPage(pageIndex: number, append: boolean = true): Promise<void> {
  7021. try {
  7022. // 1. 检查缓存
  7023. if (this.pageCache.has(pageIndex)) {
  7024. Logger.info('heanup LocalMusic', `loadPage: 从缓存加载 page=${pageIndex}`);
  7025. const inMediaLibraryWarmup = this.modeType === 1 && pageIndex === 0 && !append && this.isMediaLibraryWarmupWindow();
  7026. const cachedData = this.pageCache.get(pageIndex)!;
  7027. const cachedHasMore = this.pageHasMoreCache.get(pageIndex);
  7028. const cachedTotal = this.pageTotalCountCache.get(pageIndex);
  7029. if (cachedHasMore !== undefined) {
  7030. this.hasMoreData = cachedHasMore;
  7031. }
  7032. if (cachedTotal !== undefined) {
  7033. this.totalCount = cachedTotal;
  7034. if (this.modeType === 1) {
  7035. this.mediaKuCount = cachedTotal;
  7036. }
  7037. }
  7038. if (append) {
  7039. this.prefetchListThumbsFromItems(cachedData, 26);
  7040. this.prefetchGridWaterThumbsFromItems(cachedData, this.twoFingerType == 4 ? 56 : 42);
  7041. await this.appendItemsSmoothly(cachedData);
  7042. } else {
  7043. this.videoLocalList = cachedData;
  7044. this.dataSource.pushArrayData(this.videoLocalList);
  7045. if (inMediaLibraryWarmup) {
  7046. this.prefetchListThumbsFromItems(cachedData, 8);
  7047. } else {
  7048. this.prefetchListThumbsFromItems(cachedData, 30);
  7049. this.prefetchGridWaterThumbsFromItems(cachedData, this.twoFingerType == 4 ? 56 : 42);
  7050. }
  7051. }
  7052. this.setButtonStatus();
  7053. if (inMediaLibraryWarmup) {
  7054. this.scheduleAlphaBetRebuild(900);
  7055. } else {
  7056. this.markAlphaBetDirty();
  7057. }
  7058. if (this.hasMoreData) {
  7059. if (inMediaLibraryWarmup) {
  7060. if (this.mediaLibraryWarmupPrefetchTimer) {
  7061. clearTimeout(this.mediaLibraryWarmupPrefetchTimer);
  7062. }
  7063. this.mediaLibraryWarmupPrefetchTimer = setTimeout(() => {
  7064. this.mediaLibraryWarmupPrefetchTimer = 0;
  7065. if (this.modeType === 1 && !this.isCanBack) {
  7066. this.prefetchFollowingPages(pageIndex + 1);
  7067. }
  7068. }, 900) as number;
  7069. } else {
  7070. this.prefetchFollowingPages(pageIndex + 1);
  7071. }
  7072. }
  7073. return;
  7074. }
  7075. this.isLoadingPage = true;
  7076. Logger.info('heanup LocalMusic', `loadPage: 开始加载 page=${pageIndex}, size=${this.pageSize}, mode=${this.modeType}`);
  7077. // 2. 构造查询参数
  7078. const options: PageQueryOptions = {
  7079. pageIndex: pageIndex,
  7080. pageSize: this.pageSize,
  7081. sortType: this.sortType,
  7082. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  7083. isShowFileName: this.isShowFileName
  7084. };
  7085. // 根据 modeType 补充查询条件
  7086. if (this.modeType === 0) {
  7087. options.parentPath = this.currentPath;
  7088. }
  7089. // 3. 执行查询
  7090. let result: PageQueryResult = { items: [], totalCount: 0, hasMore: false };
  7091. switch (this.modeType) {
  7092. case 0:
  7093. result = await this.table.queryByParentPathPaged(options);
  7094. // modeType=0时,第一页需要添加文件夹列表
  7095. if (pageIndex === 0 && !this.isSearchMode) {
  7096. const directories: VideoItem[] = await this.loadDirectories(this.currentPath);
  7097. result.items = [...directories, ...result.items];
  7098. result.totalCount += directories.length;
  7099. }
  7100. break;
  7101. case 1:
  7102. result = await this.table.queryMediaLibraryPaged(options);
  7103. break;
  7104. case 2:
  7105. result = await this.table.queryArtistsPaged(options);
  7106. break;
  7107. case 3:
  7108. result = await this.table.queryAlbumsPaged(options);
  7109. break;
  7110. default:
  7111. result = await this.table.queryMediaLibraryPaged(options);
  7112. break;
  7113. }
  7114. if (!result || result.items.length === 0) {
  7115. Logger.info('heanup LocalMusic', 'loadPage: 查询结果为空');
  7116. this.isLoadingPage = false;
  7117. this.hasMoreData = false;
  7118. // 仅首页为空时清空,后续页为空只终止继续分页
  7119. if (pageIndex === 0) {
  7120. this.totalCount = 0;
  7121. this.videoLocalList = [];
  7122. this.dataSource.pushArrayData(this.videoLocalList);
  7123. this.setButtonStatus();
  7124. this.markAlphaBetDirty();
  7125. }
  7126. return;
  7127. }
  7128. // 4. 更新状态和缓存
  7129. this.totalCount = result.totalCount;
  7130. this.hasMoreData = result.hasMore;
  7131. if (this.modeType === 1) {
  7132. this.mediaKuCount = result.totalCount;
  7133. }
  7134. if (this.modeType === 2 && result.countMap) {
  7135. this.mergeArtistCountMap(result.countMap);
  7136. } else if (this.modeType === 3 && result.countMap) {
  7137. this.mergeAlbumCountMap(result.countMap);
  7138. }
  7139. Logger.info('heanup LocalMusic', `loadPage: 查询完成 items=${result.items.length}, total=${result.totalCount}, hasMore=${result.hasMore}`);
  7140. // 缓存管理 - 只保留最近3页
  7141. this.pageCache.set(pageIndex, result.items);
  7142. this.pageHasMoreCache.set(pageIndex, result.hasMore);
  7143. this.pageTotalCountCache.set(pageIndex, result.totalCount);
  7144. this.cleanOldCache(pageIndex);
  7145. // 5. 更新显示列表
  7146. const inMediaLibraryWarmup = this.modeType === 1 && pageIndex === 0 && !append && this.isMediaLibraryWarmupWindow();
  7147. if (append) {
  7148. this.prefetchListThumbsFromItems(result.items, 26);
  7149. this.prefetchGridWaterThumbsFromItems(result.items, this.twoFingerType == 4 ? 56 : 42);
  7150. await this.appendItemsSmoothly(result.items);
  7151. } else {
  7152. this.videoLocalList = result.items;
  7153. this.dataSource.pushArrayData(this.videoLocalList);
  7154. if (inMediaLibraryWarmup) {
  7155. this.prefetchListThumbsFromItems(result.items, 8);
  7156. } else {
  7157. this.prefetchListThumbsFromItems(result.items, 30);
  7158. this.prefetchGridWaterThumbsFromItems(result.items, this.twoFingerType == 4 ? 56 : 42);
  7159. }
  7160. }
  7161. this.setButtonStatus();
  7162. if (inMediaLibraryWarmup) {
  7163. this.scheduleAlphaBetRebuild(900);
  7164. } else {
  7165. this.markAlphaBetDirty();
  7166. }
  7167. if (inMediaLibraryWarmup) {
  7168. if (this.mediaLibraryWarmupPrefetchTimer) {
  7169. clearTimeout(this.mediaLibraryWarmupPrefetchTimer);
  7170. }
  7171. this.mediaLibraryWarmupPrefetchTimer = setTimeout(() => {
  7172. this.mediaLibraryWarmupPrefetchTimer = 0;
  7173. if (this.modeType === 1 && !this.isCanBack) {
  7174. this.prefetchFollowingPages(pageIndex + 1);
  7175. }
  7176. }, 900) as number;
  7177. } else {
  7178. this.prefetchFollowingPages(pageIndex + 1);
  7179. }
  7180. this.isLoadingPage = false;
  7181. } catch (err) {
  7182. const error = err as Error;
  7183. Logger.error('heanup LocalMusic', `loadPage error: ${error.message}`);
  7184. ToastUtil.showToast('加载数据失败');
  7185. this.isLoadingPage = false;
  7186. this.hasMoreData = false;
  7187. }
  7188. }
  7189. /**
  7190. * 清理旧缓存 - 只保留当前页前后各1页
  7191. */
  7192. private cleanOldCache(currentPage: number): void {
  7193. const pagesToKeep = new Set([currentPage - 1, currentPage, currentPage + 1]);
  7194. const keysToDelete: number[] = [];
  7195. this.pageCache.forEach((_, page) => {
  7196. if (!pagesToKeep.has(page)) {
  7197. keysToDelete.push(page);
  7198. }
  7199. });
  7200. keysToDelete.forEach(page => {
  7201. this.pageCache.delete(page);
  7202. this.pageHasMoreCache.delete(page);
  7203. this.pageTotalCountCache.delete(page);
  7204. });
  7205. if (keysToDelete.length > 0) {
  7206. Logger.info('heanup LocalMusic', `cleanOldCache: 清理了 ${keysToDelete.length} 页缓存`);
  7207. }
  7208. }
  7209. private async prefetchNextPage(nextPage: number): Promise<void> {
  7210. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  7211. return;
  7212. }
  7213. if (!this.hasMoreData || this.pageCache.has(nextPage) || this.prefetchingPages.has(nextPage)) {
  7214. return;
  7215. }
  7216. const expectedModeType = this.modeType;
  7217. const expectedSortType = this.sortType;
  7218. const expectedIsShowFileName = this.isShowFileName;
  7219. const expectedSearchKeyword = this.isSearchMode ? this.searchText : '';
  7220. const expectedParentPath = this.currentPath;
  7221. this.prefetchingPages.add(nextPage);
  7222. try {
  7223. const options: PageQueryOptions = {
  7224. pageIndex: nextPage,
  7225. pageSize: this.pageSize,
  7226. sortType: this.sortType,
  7227. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  7228. isShowFileName: this.isShowFileName
  7229. };
  7230. if (this.modeType === 0) {
  7231. options.parentPath = this.currentPath;
  7232. }
  7233. let result: PageQueryResult = { items: [], totalCount: 0, hasMore: false };
  7234. switch (this.modeType) {
  7235. case 0:
  7236. result = await this.table.queryByParentPathPaged(options);
  7237. break;
  7238. case 1:
  7239. result = await this.table.queryMediaLibraryPaged(options);
  7240. break;
  7241. case 2:
  7242. result = await this.table.queryArtistsPaged(options);
  7243. if (result.countMap) {
  7244. this.mergeArtistCountMap(result.countMap);
  7245. }
  7246. break;
  7247. case 3:
  7248. result = await this.table.queryAlbumsPaged(options);
  7249. if (result.countMap) {
  7250. this.mergeAlbumCountMap(result.countMap);
  7251. }
  7252. break;
  7253. default:
  7254. result = await this.table.queryMediaLibraryPaged(options);
  7255. break;
  7256. }
  7257. const currentSearchKeyword = this.isSearchMode ? this.searchText : '';
  7258. if (expectedModeType !== this.modeType ||
  7259. expectedSortType !== this.sortType ||
  7260. expectedIsShowFileName !== this.isShowFileName ||
  7261. expectedSearchKeyword !== currentSearchKeyword ||
  7262. (expectedModeType === 0 && expectedParentPath !== this.currentPath)) {
  7263. Logger.info('heanup LocalMusic', `prefetchNextPage: 上下文已变化,放弃写入 page=${nextPage}`);
  7264. return;
  7265. }
  7266. this.pageHasMoreCache.set(nextPage, result.hasMore);
  7267. this.pageTotalCountCache.set(nextPage, result.totalCount);
  7268. if (result.items.length > 0) {
  7269. this.pageCache.set(nextPage, result.items);
  7270. this.prefetchGridWaterThumbsFromItems(result.items, this.twoFingerType == 4 ? 48 : 36);
  7271. this.cleanOldCache(nextPage);
  7272. if (nextPage === this.currentPage + 1 && !this.isLoadingPage && !this.isPagingTransition
  7273. && this.lastVisibleEndIndex >= 0 && this.videoLocalList.length > 0) {
  7274. const seenRatio = (this.lastVisibleEndIndex + 1) / Math.max(this.videoLocalList.length, 1);
  7275. if (seenRatio >= Math.max(0.14, this.getDynamicAppendStartRatio() - 0.12)) {
  7276. Logger.info('heanup LocalMusic',
  7277. `prefetchNextPage: 下一页缓存已就绪,提前衔接 page=${nextPage}, ratio=${seenRatio}`);
  7278. this.scheduleLoadNextPage(8);
  7279. }
  7280. }
  7281. }
  7282. } catch (err) {
  7283. const error = err as Error;
  7284. Logger.warn('heanup LocalMusic', `prefetchNextPage error: ${error.message}`);
  7285. } finally {
  7286. this.prefetchingPages.delete(nextPage);
  7287. }
  7288. }
  7289. private mergeArtistCountMap(countMap: Map<string, number>): void {
  7290. const nextMap = new Map(this.artistSongCountMap);
  7291. countMap.forEach((count, artist) => {
  7292. nextMap.set(artist, count);
  7293. });
  7294. this.artistSongCountMap = nextMap;
  7295. }
  7296. private mergeAlbumCountMap(countMap: Map<string, number>): void {
  7297. const nextMap = new Map(this.albumSongCountMap);
  7298. countMap.forEach((count, album) => {
  7299. nextMap.set(album, count);
  7300. });
  7301. this.albumSongCountMap = nextMap;
  7302. }
  7303. private getArtistSongCount(artist: string): number {
  7304. return this.artistSongCountMap.get(artist) ?? this.artistMap.get(artist)?.length ?? 0;
  7305. }
  7306. private getAlbumSongCount(album: string): number {
  7307. return this.albumSongCountMap.get(album) ?? this.albumMap.get(album)?.length ?? 0;
  7308. }
  7309. /**
  7310. * 加载文件夹列表(仅用于modeType=0的首页模式)
  7311. */
  7312. private async loadDirectories(curPath: string): Promise<VideoItem[]> {
  7313. try {
  7314. Logger.info('heanup LocalMusic', `loadDirectories: 开始加载文件夹 path=${curPath}`);
  7315. // 检查缓存
  7316. const cacheKey = curPath + "_dirList";
  7317. const cachedDirList = this.findCache(cacheKey);
  7318. if (cachedDirList !== undefined && Array.isArray(cachedDirList)) {
  7319. Logger.info('heanup LocalMusic', `loadDirectories: 从缓存加载 count=${cachedDirList.length}`);
  7320. return cachedDirList as VideoItem[];
  7321. }
  7322. // 从文件系统读取
  7323. const fileList = FileUtil.listFileSync(curPath);
  7324. const directories: VideoItem[] = [];
  7325. for (let i = 0; i < fileList.length; i++) {
  7326. const path = curPath + '/' + fileList[i];
  7327. if (FileUtil.isDirectory(path)) {
  7328. const item: VideoItem = new VideoItem(
  7329. fileList[i].toString(),
  7330. fileList[i].toString(),
  7331. path,
  7332. CommonConstants.TYPE_IS_DIR,
  7333. 0,
  7334. ''
  7335. );
  7336. if (this.isShowDir(item.name)) {
  7337. directories.push(item);
  7338. }
  7339. }
  7340. }
  7341. // 排序
  7342. Utility.doSortListAscending(directories);
  7343. // 缓存文件夹列表
  7344. if (curPath === this.rootPath) {
  7345. this.dirList = directories;
  7346. this.addCache(cacheKey, directories);
  7347. }
  7348. Logger.info('heanup LocalMusic', `loadDirectories: 加载完成 count=${directories.length}`);
  7349. return directories;
  7350. } catch (err) {
  7351. const error = err as Error;
  7352. Logger.error('heanup LocalMusic', `loadDirectories error: ${error.message}`);
  7353. return [];
  7354. }
  7355. }
  7356. /**
  7357. * 构建播放队列(避免一次性加载全量)
  7358. */
  7359. private buildPlayQueueFromView(): Array<VideoItem> {
  7360. if (this.modeType === 4) {
  7361. this.playQueueScope = 'playlist';
  7362. return this.currentSongList;
  7363. }
  7364. if (this.isHistory) {
  7365. this.playQueueScope = 'history';
  7366. return this.historyList;
  7367. }
  7368. if (this.isFavMusic) {
  7369. this.playQueueScope = 'fav';
  7370. return this.favList;
  7371. }
  7372. this.playQueueScope = 'view';
  7373. return this.videoLocalList.filter((item: VideoItem) => item.type === CommonConstants.TYPE_LOCAL);
  7374. }
  7375. private async tryLoadNextPageForPlayback(): Promise<void> {
  7376. if (this.playQueueScope !== 'view') {
  7377. return;
  7378. }
  7379. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  7380. return;
  7381. }
  7382. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  7383. return;
  7384. }
  7385. await this.loadNextPage();
  7386. const nextList = this.videoLocalList.filter((item: VideoItem) => item.type === CommonConstants.TYPE_LOCAL);
  7387. if (nextList.length > this.songList.length) {
  7388. this.songList = nextList;
  7389. this.sonDataSource.pushArrayData(this.songList);
  7390. }
  7391. }
  7392. /**
  7393. * 加载更多流媒体歌曲(Navidrome/Jellyfin/Emby/AudioStation/Plex)
  7394. * 当播放列表弹窗滚动到底部时调用
  7395. */
  7396. private async loadMoreNavidromeSongs(): Promise<void> {
  7397. const beforeCount = this.songList.length;
  7398. const hasMore = hasMoreData();
  7399. Logger.info('heanup', `开始加载更多流媒体歌曲, 当前数量=${beforeCount}, hasMoreData=${hasMore}`);
  7400. if (!hasMore) {
  7401. Logger.info('heanup', '没有更多数据可加载(hasMoreData=false)');
  7402. return;
  7403. }
  7404. // 触发加载更多(会更新NavidromePlaylistStore中的数据)
  7405. const success = await triggerLoadMoreSongs(1);
  7406. Logger.info('heanup', `triggerLoadMoreSongs返回: ${success}`);
  7407. if (success) {
  7408. // 获取更新后的完整列表
  7409. const updatedList = getNavidromeVideoItems();
  7410. Logger.info('heanup', `更新后列表长度: ${updatedList.length}`);
  7411. if (updatedList.length > beforeCount) {
  7412. Logger.info('heanup', `流媒体歌曲加载成功: ${beforeCount} -> ${updatedList.length}`);
  7413. this.songList = updatedList;
  7414. this.sonDataSource.pushArrayData(this.songList);
  7415. } else {
  7416. Logger.info('heanup', '列表长度未增加');
  7417. }
  7418. } else {
  7419. Logger.info('heanup', '流媒体歌曲加载未返回新数据(triggerLoadMoreSongs=false)');
  7420. }
  7421. }
  7422. /**
  7423. * 重置分页状态并加载首页
  7424. */
  7425. private async resetAndLoadFirstPage(clearExistingList: boolean = true): Promise<void> {
  7426. Logger.info('heanup LocalMusic', 'resetAndLoadFirstPage: 重置分页状态');
  7427. this.currentPage = 0;
  7428. if (clearExistingList) {
  7429. this.videoLocalList = [];
  7430. }
  7431. this.pageCache.clear();
  7432. this.pageHasMoreCache.clear();
  7433. this.pageTotalCountCache.clear();
  7434. this.prefetchingPages.clear();
  7435. this.hasMoreData = true;
  7436. this.totalCount = 0;
  7437. this.lastScrollTriggerPage = -1;
  7438. this.lastVisibleEndIndex = -1;
  7439. this.listScrollAlphaCheckAt = 0;
  7440. this.listScrollPagingCheckAt = 0;
  7441. this.listScrollLastAlphaStart = -1;
  7442. this.listScrollLastPagingEnd = -1;
  7443. this.gridScrollPagingCheckAt = 0;
  7444. this.gridScrollLastPagingEnd = -1;
  7445. this.waterScrollPagingCheckAt = 0;
  7446. this.waterScrollLastPagingEnd = -1;
  7447. this.listVisibleStart = -1;
  7448. this.listVisibleEnd = -1;
  7449. this.listThumbWarmupCheckAt = 0;
  7450. this.listThumbWarmupStart = -1;
  7451. this.listThumbWarmupEnd = -1;
  7452. this.gridThumbWarmupCheckAt = 0;
  7453. this.gridThumbWarmupStart = -1;
  7454. this.gridThumbWarmupEnd = -1;
  7455. this.waterThumbWarmupCheckAt = 0;
  7456. this.waterThumbWarmupStart = -1;
  7457. this.waterThumbWarmupEnd = -1;
  7458. this.gridVisibleStart = -1;
  7459. this.gridVisibleEnd = -1;
  7460. this.waterVisibleStart = -1;
  7461. this.waterVisibleEnd = -1;
  7462. this.gridWaterLastActiveTs = 0;
  7463. this.isPagingTransition = false;
  7464. if (this.pagingScheduleTimer) {
  7465. clearTimeout(this.pagingScheduleTimer);
  7466. this.pagingScheduleTimer = 0;
  7467. }
  7468. if (this.gridWaterScrollIdleTimer) {
  7469. clearTimeout(this.gridWaterScrollIdleTimer);
  7470. this.gridWaterScrollIdleTimer = 0;
  7471. }
  7472. this.coverThumbCache.clearPending();
  7473. this.pendingCoverThumbRefresh = false;
  7474. if (this.modeType === 2) {
  7475. this.artistSongCountMap = new Map();
  7476. } else if (this.modeType === 3) {
  7477. this.albumSongCountMap = new Map();
  7478. }
  7479. await this.loadPage(0, false);
  7480. }
  7481. private markGridWaterScrollingActive(): void {
  7482. if (!this.isScrolling) {
  7483. this.isScrolling = true;
  7484. }
  7485. const now = Date.now();
  7486. if (now - this.gridWaterLastActiveTs < 80) {
  7487. return;
  7488. }
  7489. this.gridWaterLastActiveTs = now;
  7490. if (this.gridWaterScrollIdleTimer) {
  7491. clearTimeout(this.gridWaterScrollIdleTimer);
  7492. }
  7493. this.gridWaterScrollIdleTimer = setTimeout(() => {
  7494. this.gridWaterScrollIdleTimer = 0;
  7495. if (this.isScrolling) {
  7496. this.isScrolling = false;
  7497. }
  7498. this.flushPendingCoverThumbRefresh();
  7499. }, 120);
  7500. }
  7501. private updateTitleBarByScrollOffset(currentOffsetY: number): void {
  7502. if (!this.autoHideTitle) {
  7503. return;
  7504. }
  7505. const now = Date.now();
  7506. if (now - this.titleBarLastCheckTs < 36) {
  7507. return;
  7508. }
  7509. this.titleBarLastCheckTs = now;
  7510. const delta = currentOffsetY - this.prevOffsetY;
  7511. if (Math.abs(delta) < this.titleBarToggleMinDelta) {
  7512. return;
  7513. }
  7514. if (delta > 0) {
  7515. if (this.isShowTitleBar) {
  7516. this.isShowTitleBar = false;
  7517. }
  7518. } else {
  7519. if (!this.isShowTitleBar) {
  7520. this.isShowTitleBar = true;
  7521. }
  7522. }
  7523. this.prevOffsetY = currentOffsetY;
  7524. }
  7525. private shouldPrefetchSecondPage(): boolean {
  7526. if (this.isMediaLibraryListMode()) {
  7527. return this.pageSize <= 120;
  7528. }
  7529. if (this.pageSize > 60) {
  7530. return false;
  7531. }
  7532. return this.isGridMusic || this.twoFingerType == 4;
  7533. }
  7534. private isMediaLibraryListMode(): boolean {
  7535. return this.modeType === 1 && !this.isGridMusic && this.twoFingerType != 4;
  7536. }
  7537. private isMediaLibraryWarmupWindow(): boolean {
  7538. if (this.modeType !== 1 || this.isCanBack) {
  7539. return false;
  7540. }
  7541. if (this.mediaLibraryEnterTs <= 0) {
  7542. return false;
  7543. }
  7544. return Date.now() - this.mediaLibraryEnterTs < 1800;
  7545. }
  7546. private getDynamicPreloadStartRatio(): number {
  7547. if (this.twoFingerType == 4) {
  7548. return 0.10;
  7549. }
  7550. if (this.isGridMusic) {
  7551. return 0.14;
  7552. }
  7553. if (this.isMediaLibraryListMode()) {
  7554. return 0.12;
  7555. }
  7556. return this.preloadStartRatio;
  7557. }
  7558. private getDynamicAppendStartRatio(): number {
  7559. if (this.twoFingerType == 4) {
  7560. return 0.18;
  7561. }
  7562. if (this.isGridMusic) {
  7563. return 0.22;
  7564. }
  7565. if (this.isMediaLibraryListMode()) {
  7566. return 0.22;
  7567. }
  7568. return this.appendStartRatio;
  7569. }
  7570. private getDynamicEarlyAppendReserveCount(): number {
  7571. if (this.twoFingerType == 4) {
  7572. return Math.max(this.earlyAppendReserveCount, Math.floor(this.pageSize * 0.9));
  7573. }
  7574. if (this.isGridMusic) {
  7575. return Math.max(this.earlyAppendReserveCount, Math.floor(this.pageSize * 0.82));
  7576. }
  7577. if (this.isMediaLibraryListMode()) {
  7578. return Math.max(this.earlyAppendReserveCount, Math.floor(this.pageSize * 0.75));
  7579. }
  7580. return this.earlyAppendReserveCount;
  7581. }
  7582. private prefetchFollowingPages(nextPage: number): void {
  7583. void this.prefetchNextPage(nextPage);
  7584. if (this.shouldPrefetchSecondPage()) {
  7585. void this.prefetchNextPage(nextPage + 1);
  7586. }
  7587. }
  7588. private scrollToTopForCurrentLayout(): void {
  7589. if (this.twoFingerType == 4) {
  7590. this.waterScroller.scrollEdge(Edge.Top);
  7591. this.scroller.scrollEdge(Edge.Top);
  7592. return;
  7593. }
  7594. if (this.isGridMusic) {
  7595. this.scroller.scrollEdge(Edge.Top);
  7596. return;
  7597. }
  7598. this.listScroller.scrollEdge(Edge.Top);
  7599. }
  7600. private getListImageSource(item: VideoItem, index: number, coverVersion: number = 0): ResourceStr {
  7601. const fallback = item.type == CommonConstants.TYPE_IS_DIR ? $r('app.media.dir_alt') : $r('app.media.alt');
  7602. if (coverVersion < -1) {
  7603. return fallback;
  7604. }
  7605. if (StrUtil.isEmpty(item.pixelMapPath)) {
  7606. return fallback;
  7607. }
  7608. const sourceUri = item.pixelMapPath as string;
  7609. this.initCoverThumbCacheIfNeeded();
  7610. const targetSize = this.getListThumbTargetSize();
  7611. const cachedThumb = this.coverThumbCache.getThumbUri(sourceUri, targetSize);
  7612. if (cachedThumb) {
  7613. return cachedThumb;
  7614. }
  7615. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  7616. const preloadBuffer = Math.max(8, Math.floor(this.pageSize * 0.2));
  7617. const hasRange = this.listVisibleStart >= 0 && this.listVisibleEnd >= 0;
  7618. const isNearVisible = !hasRange ||
  7619. (index >= this.listVisibleStart - preloadBuffer && index <= this.listVisibleEnd + preloadBuffer);
  7620. if (isNearVisible) {
  7621. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  7622. }
  7623. }
  7624. return sourceUri;
  7625. }
  7626. private getListThumbTargetSize(): number {
  7627. if (this.twoFingerType == 1) {
  7628. return 96;
  7629. }
  7630. if (this.twoFingerType == 2) {
  7631. return 112;
  7632. }
  7633. return 128;
  7634. }
  7635. private prefetchListThumbsFromItems(items: VideoItem[], limit: number = 24): void {
  7636. if (!this.isMediaLibraryListMode() || !items || items.length === 0) {
  7637. return;
  7638. }
  7639. this.initCoverThumbCacheIfNeeded();
  7640. const targetSize = this.getListThumbTargetSize();
  7641. const maxCount = Math.min(limit, items.length);
  7642. for (let i = 0; i < maxCount; i++) {
  7643. const item = items[i];
  7644. if (StrUtil.isEmpty(item.pixelMapPath)) {
  7645. continue;
  7646. }
  7647. const sourceUri = item.pixelMapPath as string;
  7648. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  7649. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  7650. }
  7651. }
  7652. }
  7653. private warmupListVisibleThumbs(start: number, end: number): void {
  7654. if (!this.isMediaLibraryListMode()) {
  7655. return;
  7656. }
  7657. if (start < 0 || end < 0 || this.videoLocalList.length <= 0) {
  7658. return;
  7659. }
  7660. const now = Date.now();
  7661. const startDelta = this.listThumbWarmupStart >= 0 ? Math.abs(start - this.listThumbWarmupStart) : 999;
  7662. const endDelta = this.listThumbWarmupEnd >= 0 ? Math.abs(end - this.listThumbWarmupEnd) : 999;
  7663. if (startDelta < 2 && endDelta < 2 && now - this.listThumbWarmupCheckAt < 90) {
  7664. return;
  7665. }
  7666. this.listThumbWarmupCheckAt = now;
  7667. this.listThumbWarmupStart = start;
  7668. this.listThumbWarmupEnd = end;
  7669. this.initCoverThumbCacheIfNeeded();
  7670. const targetSize = this.getListThumbTargetSize();
  7671. const preloadAhead = Math.max(14, Math.floor(this.pageSize * 0.4));
  7672. const begin = Math.max(0, start - 4);
  7673. const last = Math.min(this.videoLocalList.length - 1, end + preloadAhead);
  7674. for (let index = begin; index <= last; index++) {
  7675. const item = this.videoLocalList[index];
  7676. if (!item || StrUtil.isEmpty(item.pixelMapPath)) {
  7677. continue;
  7678. }
  7679. const sourceUri = item.pixelMapPath as string;
  7680. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  7681. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  7682. }
  7683. }
  7684. }
  7685. private prefetchGridWaterThumbsFromItems(items: VideoItem[], limit: number = 42): void {
  7686. if (!(this.isGridMusic || this.twoFingerType == 4) || !items || items.length === 0) {
  7687. return;
  7688. }
  7689. this.initCoverThumbCacheIfNeeded();
  7690. const isWater = this.twoFingerType == 4;
  7691. const targetSize = this.getCoverThumbTargetSize(isWater);
  7692. const maxCount = Math.min(limit, items.length);
  7693. for (let i = 0; i < maxCount; i++) {
  7694. const item = items[i];
  7695. if (!item || StrUtil.isEmpty(item.pixelMapPath)) {
  7696. continue;
  7697. }
  7698. const sourceUri = item.pixelMapPath as string;
  7699. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  7700. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  7701. }
  7702. }
  7703. }
  7704. private warmupGridWaterVisibleThumbs(start: number, end: number, isWater: boolean): void {
  7705. if (!(this.isGridMusic || this.twoFingerType == 4)) {
  7706. return;
  7707. }
  7708. if (start < 0 || end < 0 || this.videoLocalList.length <= 0) {
  7709. return;
  7710. }
  7711. const now = Date.now();
  7712. let lastStart = -1;
  7713. let lastEnd = -1;
  7714. let lastCheckAt = 0;
  7715. if (isWater) {
  7716. lastStart = this.waterThumbWarmupStart;
  7717. lastEnd = this.waterThumbWarmupEnd;
  7718. lastCheckAt = this.waterThumbWarmupCheckAt;
  7719. } else {
  7720. lastStart = this.gridThumbWarmupStart;
  7721. lastEnd = this.gridThumbWarmupEnd;
  7722. lastCheckAt = this.gridThumbWarmupCheckAt;
  7723. }
  7724. const startDelta = lastStart >= 0 ? Math.abs(start - lastStart) : 999;
  7725. const endDelta = lastEnd >= 0 ? Math.abs(end - lastEnd) : 999;
  7726. if (startDelta < 2 && endDelta < 2 && now - lastCheckAt < 70) {
  7727. return;
  7728. }
  7729. if (isWater) {
  7730. this.waterThumbWarmupCheckAt = now;
  7731. this.waterThumbWarmupStart = start;
  7732. this.waterThumbWarmupEnd = end;
  7733. } else {
  7734. this.gridThumbWarmupCheckAt = now;
  7735. this.gridThumbWarmupStart = start;
  7736. this.gridThumbWarmupEnd = end;
  7737. }
  7738. this.initCoverThumbCacheIfNeeded();
  7739. const columns = isWater ? Math.max(this.columns, 1) :
  7740. (this.twoFingerType == 1 ? 4 : this.twoFingerType == 2 ? 3 : 2);
  7741. const preloadAhead = Math.max(columns * (isWater ? 8 : 6), isWater ? 24 : 18);
  7742. const begin = Math.max(0, start - Math.max(columns * 2, 4));
  7743. const last = Math.min(this.videoLocalList.length - 1, end + preloadAhead);
  7744. const targetSize = this.getCoverThumbTargetSize(isWater);
  7745. for (let index = begin; index <= last; index++) {
  7746. const item = this.videoLocalList[index];
  7747. if (!item || StrUtil.isEmpty(item.pixelMapPath)) {
  7748. continue;
  7749. }
  7750. const sourceUri = item.pixelMapPath as string;
  7751. if (!this.coverThumbCache.isRemoteImageSource(sourceUri)) {
  7752. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  7753. }
  7754. }
  7755. }
  7756. private getGridWaterImageSource(item: VideoItem, index: number, isWater: boolean,
  7757. coverVersion: number = 0): ResourceStr {
  7758. const fallback = item.type == CommonConstants.TYPE_IS_DIR ? $r('app.media.dir_alt') : $r('app.media.alt');
  7759. if (coverVersion < -1) {
  7760. return fallback;
  7761. }
  7762. if (StrUtil.isEmpty(item.pixelMapPath)) {
  7763. return fallback;
  7764. }
  7765. const sourceUri = item.pixelMapPath as string;
  7766. this.initCoverThumbCacheIfNeeded();
  7767. const isRemoteCover = this.coverThumbCache.isRemoteImageSource(sourceUri);
  7768. const targetSize = this.getCoverThumbTargetSize(isWater);
  7769. const cachedThumb = this.coverThumbCache.getThumbUri(sourceUri, targetSize);
  7770. if (cachedThumb) {
  7771. return cachedThumb;
  7772. }
  7773. const visibleStart = isWater ? this.waterVisibleStart : this.gridVisibleStart;
  7774. const visibleEnd = isWater ? this.waterVisibleEnd : this.gridVisibleEnd;
  7775. const columns = isWater ? Math.max(this.columns, 1) :
  7776. (this.twoFingerType == 1 ? 4 : this.twoFingerType == 2 ? 3 : 2);
  7777. const preloadBuffer = Math.max(columns * 2, 8);
  7778. const isVisibleRangeReady = visibleStart >= 0 && visibleEnd >= 0;
  7779. const isNearVisible = !isVisibleRangeReady || (index >= visibleStart - preloadBuffer && index <= visibleEnd + preloadBuffer);
  7780. if (!isRemoteCover && isNearVisible) {
  7781. this.coverThumbCache.ensureThumbRequested(sourceUri, targetSize);
  7782. }
  7783. if (!this.isScrolling) {
  7784. return sourceUri;
  7785. }
  7786. if (isNearVisible) {
  7787. return sourceUri;
  7788. }
  7789. return fallback;
  7790. }
  7791. private flushPendingCoverThumbRefresh(): void {
  7792. if (!this.pendingCoverThumbRefresh) {
  7793. return;
  7794. }
  7795. this.pendingCoverThumbRefresh = false;
  7796. this.coverThumbVersion++;
  7797. }
  7798. private initCoverThumbCacheIfNeeded(): void {
  7799. if (this.coverThumbCacheReady) {
  7800. return;
  7801. }
  7802. this.coverThumbCache.setContext(this.context);
  7803. this.coverThumbCache.setOnThumbReady(() => {
  7804. if (this.isScrolling) {
  7805. this.pendingCoverThumbRefresh = true;
  7806. return;
  7807. }
  7808. this.coverThumbVersion++;
  7809. });
  7810. this.coverThumbCacheReady = true;
  7811. }
  7812. private getCoverThumbTargetSize(isWater: boolean): number {
  7813. if (isWater) {
  7814. if (this.columns >= 4) {
  7815. return 160;
  7816. }
  7817. if (this.columns == 3) {
  7818. return 200;
  7819. }
  7820. return 260;
  7821. }
  7822. const baseSize = Math.max(this.getGridWight(), this.getGridHeight());
  7823. if (this.twoFingerType == 1) {
  7824. return baseSize;
  7825. }
  7826. if (this.twoFingerType == 2) {
  7827. return Math.floor(baseSize * 1.1);
  7828. }
  7829. return Math.floor(baseSize * 1.15);
  7830. }
  7831. private tryTriggerLoadForWaterByOffset(currentOffsetY: number): void {
  7832. if (this.videoLocalList.length <= 0) {
  7833. return;
  7834. }
  7835. const columns = Math.max(this.columns, 1);
  7836. const viewportHeight = this.windowHeight > 0 ? this.windowHeight : 900;
  7837. const estimatedCardHeight = this.columns >= 3 ? 196 : 228;
  7838. const startRow = Math.max(0, Math.floor(Math.max(currentOffsetY, 0) / estimatedCardHeight) - 1);
  7839. const estimatedRows = Math.ceil((Math.max(currentOffsetY, 0) + viewportHeight) / estimatedCardHeight);
  7840. const startIndex = Math.min(this.videoLocalList.length - 1, startRow * columns);
  7841. const estimatedEnd = Math.min(this.videoLocalList.length - 1, estimatedRows * columns + columns);
  7842. this.waterVisibleStart = startIndex;
  7843. this.waterVisibleEnd = estimatedEnd;
  7844. this.lastVisibleEndIndex = estimatedEnd;
  7845. this.warmupGridWaterVisibleThumbs(startIndex, estimatedEnd, true);
  7846. const now = Date.now();
  7847. const pagingDelta = this.waterScrollLastPagingEnd >= 0 ? Math.abs(estimatedEnd - this.waterScrollLastPagingEnd) : 999;
  7848. if (pagingDelta >= 3 || now - this.waterScrollPagingCheckAt >= 80) {
  7849. this.waterScrollPagingCheckAt = now;
  7850. this.waterScrollLastPagingEnd = estimatedEnd;
  7851. this.tryTriggerLoadNextPageByScroll(estimatedEnd);
  7852. }
  7853. }
  7854. private tryTriggerLoadNextPageByScroll(endIndex: number): void {
  7855. if (this.modeType === 4) {
  7856. return;
  7857. }
  7858. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  7859. return;
  7860. }
  7861. if (this.isHistory || this.isFavMusic) {
  7862. return;
  7863. }
  7864. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  7865. return;
  7866. }
  7867. if (endIndex < 0 || endIndex >= this.videoLocalList.length) {
  7868. return;
  7869. }
  7870. const nextPage = this.currentPage + 1;
  7871. const next2Page = this.currentPage + 2;
  7872. const totalLoaded = this.videoLocalList.length;
  7873. const seenRatio = (endIndex + 1) / Math.max(totalLoaded, 1);
  7874. const remainCount = this.videoLocalList.length - endIndex - 1;
  7875. const preloadStartRatio = this.getDynamicPreloadStartRatio();
  7876. const appendStartRatio = this.getDynamicAppendStartRatio();
  7877. const earlyAppendReserveCount = this.getDynamicEarlyAppendReserveCount();
  7878. const emergencyDistance = Math.max(12, Math.floor(this.pageSize * 0.5));
  7879. if (seenRatio >= preloadStartRatio) {
  7880. if (!this.pageCache.has(nextPage)) {
  7881. void this.prefetchNextPage(nextPage);
  7882. }
  7883. if (this.shouldPrefetchSecondPage() && !this.pageCache.has(next2Page)) {
  7884. void this.prefetchNextPage(next2Page);
  7885. }
  7886. }
  7887. const shouldAppendEarly = this.pageCache.has(nextPage) &&
  7888. (seenRatio >= appendStartRatio || remainCount <= earlyAppendReserveCount);
  7889. const shouldGapAppend = this.pageCache.has(nextPage) &&
  7890. seenRatio >= (appendStartRatio - 0.08) &&
  7891. remainCount <= Math.max(earlyAppendReserveCount, Math.floor(this.pageSize * 0.9));
  7892. const shouldEmergencyLoad = remainCount <= emergencyDistance;
  7893. if (!shouldAppendEarly && !shouldGapAppend && !shouldEmergencyLoad) {
  7894. return;
  7895. }
  7896. if (this.lastScrollTriggerPage === this.currentPage) {
  7897. return;
  7898. }
  7899. this.lastScrollTriggerPage = this.currentPage;
  7900. Logger.info('heanup LocalMusic',
  7901. `tryTriggerLoadNextPageByScroll: end=${endIndex}, remain=${remainCount}, ratio=${seenRatio}, page=${this.currentPage}`);
  7902. this.scheduleLoadNextPage(8);
  7903. }
  7904. private scheduleLoadNextPage(delayMs: number = 0): void {
  7905. if (this.pagingScheduleTimer) {
  7906. return;
  7907. }
  7908. this.pagingScheduleTimer = setTimeout(() => {
  7909. this.pagingScheduleTimer = 0;
  7910. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  7911. return;
  7912. }
  7913. void this.loadNextPage();
  7914. }, delayMs);
  7915. }
  7916. /**
  7917. * 加载下一页
  7918. */
  7919. private async loadNextPage(): Promise<void> {
  7920. if (!this.hasMoreData || this.isLoadingPage || this.isPagingTransition) {
  7921. return;
  7922. }
  7923. this.isPagingTransition = true;
  7924. this.currentPage++;
  7925. Logger.info('heanup LocalMusic', `loadNextPage: 加载第 ${this.currentPage} 页`);
  7926. try {
  7927. await this.loadPage(this.currentPage, true);
  7928. } finally {
  7929. this.isPagingTransition = false;
  7930. }
  7931. }
  7932. //编辑信息
  7933. async doEdit(item: VideoItem) {
  7934. if (!item) {
  7935. return
  7936. }
  7937. if (StrUtil.isEmpty(this.titleStr)) {
  7938. ToastUtil.showToast('标题不能为空')
  7939. return
  7940. }
  7941. //内嵌音乐标签不能开启监听
  7942. // this.deletionWatcher?.stop();
  7943. this.loadingDialogId = DialogHelper.showLoadingDialog()
  7944. if (isRemoteCloudType(item.type)) {
  7945. await this.saveRemoteSongEdit(item);
  7946. return;
  7947. }
  7948. await PermissionUtil.activatePermission(item.filePath)
  7949. let tempOutPath = ''
  7950. // 如果不是 packName 包下的文件,则直接路径用this.currentPath
  7951. if(!item.filePath.toLowerCase().includes(this.packName)){
  7952. tempOutPath = this.currentPath + '/' + item.fileName
  7953. }
  7954. console.info('onecold tempOutPath ='+tempOutPath)
  7955. //用户更改了封面,那就内嵌下封面
  7956. if(StrUtil.isNotEmpty(this.imagePathStr)){
  7957. const resultCover:boolean = await changeMusicCover(this.context,
  7958. item.filePath,this.imagePathStr,true,tempOutPath);
  7959. this.imagePathStr = ''
  7960. if(resultCover){
  7961. ToastUtil.showToast('内嵌封面成功')
  7962. }
  7963. }
  7964. const metadata:FFMpegTags = {
  7965. title: this.titleStr,
  7966. artist: this.artistStr,
  7967. album: this.ablumStr,
  7968. TYER:this.yearStr,
  7969. genre:this.genreStr,
  7970. track:this.trackStr,
  7971. album_artist:this.albumArtistStr,
  7972. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  7973. COMPOSER:this.composerStr,
  7974. lyricist:this.lyricistStr,
  7975. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  7976. comment:this.commentStr,
  7977. disc:this.discStr,
  7978. };
  7979. let newInput = item.filePath
  7980. //内嵌标签歌路径如果不是包含包名,输入newInput要赋值tempOutPath,然后tempOutPath为空
  7981. if(!item.filePath.toLowerCase().includes(this.packName)&&FileUtil.accessSync(tempOutPath)){
  7982. newInput = tempOutPath
  7983. tempOutPath = ''
  7984. }
  7985. const isWav:boolean = newInput.toLowerCase().endsWith('.wav')
  7986. ||newInput.toLowerCase().endsWith('.ape')
  7987. ||newInput.toLowerCase().endsWith('.dsf')
  7988. ||newInput.toLowerCase().endsWith('.dff');
  7989. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  7990. const result:boolean = await repairAudioMetadata(
  7991. newInput,
  7992. this.lyricConStr,
  7993. metadata,
  7994. true,
  7995. tempOutPath
  7996. );
  7997. // ToastUtil.showToast('result ='+ result)
  7998. if (result||isWav) {
  7999. if(!item.filePath.includes(this.packName)){
  8000. //内嵌成功的歌路径如果不是包含包名,则要入库
  8001. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newInput,
  8002. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  8003. this.table.insert(newItem, (id: number) => {
  8004. //加入数据库
  8005. if(this.modeType==0){
  8006. this.deleteCache(this.currentPath)
  8007. this.getSortedFiles(this.currentPath)
  8008. }
  8009. });
  8010. }
  8011. const task = new taskpool.Task(
  8012. updateInfoDb,
  8013. this.context,
  8014. item.filePath,
  8015. this.titleStr,
  8016. this.artistStr,
  8017. this.ablumStr,
  8018. this.lyricConStr,
  8019. this.yearStr,this.genreStr,
  8020. this.trackStr,this.albumArtistStr,
  8021. this.composerStr, this.lyricistStr,
  8022. this.commentStr,this.discStr
  8023. );
  8024. taskpool.execute(task, taskpool.Priority.HIGH).then((result) => {
  8025. if (result) {
  8026. console.log(" onecold 编辑信息成功,数据库已同步");
  8027. if(isWav){
  8028. ToastUtil.showToast('dsf、wav、dff或者ape格式有可能内嵌失败,但是编辑信息成功')
  8029. }else{
  8030. ToastUtil.showToast('内嵌音乐标签成功')
  8031. }
  8032. this.isShowMoreView = false
  8033. this.name = this.titleStr
  8034. this.syncEditedFields(item)
  8035. if (item.filePath == this.currentSong?.filePath) {
  8036. this.currentSong.name = this.titleStr
  8037. this.artist = this.artistStr
  8038. this.currentSong.artist = this.artistStr
  8039. this.currentSong.album = this.ablumStr
  8040. this.currentSong.year = this.yearStr
  8041. this.currentSong.genre = this.genreStr
  8042. this.currentSong.track = this.trackStr
  8043. this.currentSong.lyricContent = this.lyricConStr
  8044. this.currentSong.ALBUMARTIST = this.albumArtistStr
  8045. this.currentSong.COMPOSER = this.composerStr
  8046. this.currentSong.LYRICIST = this.lyricistStr
  8047. this.currentSong.COMMENT = this.commentStr
  8048. }
  8049. this.syncListsAfterEdit(item.filePath)
  8050. this.doUpateEditedFields(item)
  8051. //this.doUpdateData()
  8052. } else {
  8053. // ToastUtil.showToast('保存失败' + error?.toString())
  8054. console.error(" onecold 编辑信息数据库失败 ");
  8055. }
  8056. // 关闭进度条
  8057. DialogHelper.closeDialog(this.loadingDialogId)
  8058. }).catch((error: Error) => {
  8059. // 关闭进度条
  8060. DialogHelper.closeDialog(this.loadingDialogId)
  8061. console.error('onecold Subtitle sync failed:', error);
  8062. });
  8063. console.log(' onecold 元数据标签更新成功,');
  8064. } else {
  8065. // 关闭进度条
  8066. DialogHelper.closeDialog(this.loadingDialogId)
  8067. ToastUtil.showToast('内嵌音乐标签失败')
  8068. console.log('onecold 内嵌音乐标签失败');
  8069. }
  8070. this.longItemFilePath = ''
  8071. this.tempLyricContent = ''
  8072. this.isShowEdit = false
  8073. }
  8074. private normalizeEditedCoverPath(path: string): string {
  8075. if (StrUtil.isEmpty(path)) {
  8076. return '';
  8077. }
  8078. const lowerPath = path.toLowerCase();
  8079. if (lowerPath.startsWith('http://') || lowerPath.startsWith('https://')
  8080. || lowerPath.startsWith('file://') || lowerPath.startsWith('data:')) {
  8081. return path;
  8082. }
  8083. return fileUri.getUriFromPath(path);
  8084. }
  8085. private emitRemoteMetadataUpdated(item: VideoItem): void {
  8086. if (!item || StrUtil.isEmpty(item.filePath)) {
  8087. return;
  8088. }
  8089. const payload: WebDavMetadataUpdatePayload = {
  8090. filePath: item.filePath,
  8091. pixelMapPath: item.pixelMapPath,
  8092. name: item.name,
  8093. artist: item.artist
  8094. };
  8095. const eventUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
  8096. emitter.emit(eventUpdate, { data: [payload] });
  8097. }
  8098. private syncRemoteManagerSong(item: VideoItem): void {
  8099. if (!item || StrUtil.isEmpty(item.filePath)) {
  8100. return;
  8101. }
  8102. const remoteManager = RemoteDriveManager.getInstance();
  8103. const target = Utility.getItemByFilePath(remoteManager.webDavSongs, item.filePath);
  8104. if (!target) {
  8105. return;
  8106. }
  8107. this.mergeVideoItemFromSource(target, item);
  8108. if (StrUtil.isNotEmpty(item.pixelMapPath)) {
  8109. target.pixelMapPath = item.pixelMapPath;
  8110. }
  8111. }
  8112. private async saveRemoteSongEdit(item: VideoItem): Promise<void> {
  8113. try {
  8114. this.syncEditedFields(item);
  8115. if (StrUtil.isNotEmpty(this.imagePathStr)) {
  8116. item.pixelMapPath = this.normalizeEditedCoverPath(this.imagePathStr);
  8117. }
  8118. this.name = this.titleStr;
  8119. if (this.currentSong && item.filePath === this.currentSong.filePath) {
  8120. this.syncEditedFields(this.currentSong);
  8121. if (StrUtil.isNotEmpty(item.pixelMapPath)) {
  8122. this.currentSong.pixelMapPath = item.pixelMapPath;
  8123. this.cover = item.pixelMapPath;
  8124. }
  8125. this.artist = this.currentSong.artist ?? '';
  8126. this.currentSong = cloneVideoItem(this.currentSong);
  8127. AppStorage.setOrCreate('currentSong', this.currentSong);
  8128. }
  8129. this.syncListsAfterEdit(item.filePath);
  8130. this.syncRemoteManagerSong(item);
  8131. await this.persistRemoteMetadataToDb(item);
  8132. this.emitRemoteMetadataUpdated(item);
  8133. ToastUtil.showToast(StrUtil.isNotEmpty(item.pixelMapPath) ? '网盘歌曲信息已保存' : '网盘歌曲标签已保存');
  8134. } catch (error) {
  8135. Logger.error(TAG, `saveRemoteSongEdit 失败: ${(error as Error).message}`);
  8136. ToastUtil.showToast('网盘歌曲编辑失败');
  8137. } finally {
  8138. DialogHelper.closeDialog(this.loadingDialogId);
  8139. this.longItemFilePath = '';
  8140. this.tempLyricContent = '';
  8141. this.isShowEdit = false;
  8142. this.imagePathStr = '';
  8143. this.isShowMoreView = false;
  8144. }
  8145. }
  8146. // 内嵌标签更新当前内嵌的Item
  8147. async doUpateEditedFields(item: VideoItem) {
  8148. // 找到当前项在 videoLocalList 中的索引
  8149. const index = this.videoLocalList.findIndex(video => video.filePath === item.filePath);
  8150. if (index !== -1) {
  8151. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  8152. const updatedItem = await this.table.queryVideoByFilePath(item.filePath)
  8153. // 只有当查询结果不为 null 时才更新列表
  8154. if (updatedItem !== null) {
  8155. // 更新 videoLocalList 中的项(通过创建新数组触发响应式更新)
  8156. this.videoLocalList = [
  8157. ...this.videoLocalList.slice(0, index),
  8158. updatedItem,
  8159. ...this.videoLocalList.slice(index + 1)
  8160. ];
  8161. // 同步更新 LazyDataSource
  8162. this.dataSource.pushArrayData(this.videoLocalList)
  8163. } else {
  8164. ToastUtil.showToast('未找到更新的数据');
  8165. }
  8166. }
  8167. DialogHelper.closeDialog(this.loadingDialogId)
  8168. }
  8169. @Builder
  8170. editSheet(item: VideoItem) {
  8171. Scroll() {
  8172. Column() {
  8173. this.editDetail(item)
  8174. }
  8175. }
  8176. .width('100%')
  8177. .height('100%')
  8178. }
  8179. @Builder
  8180. editDetail(item: VideoItem) {
  8181. Column() {
  8182. if (item) {
  8183. Row() {
  8184. Stack() {
  8185. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  8186. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  8187. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
  8188. item.pixelMapPath)
  8189. .fillColor(this.themeColor)
  8190. .height(88)
  8191. .width(88)
  8192. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  8193. .borderRadius(12)
  8194. .clip(true)
  8195. .opacity(this.opacityItem)// 绑定透明度
  8196. .margin({ left: 25 })
  8197. }
  8198. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  8199. .onClick(async () => {
  8200. const imagePath:string | undefined = await this.goSelectImage(item);
  8201. if (imagePath) {
  8202. //用户更改过图片
  8203. this.imagePathStr = imagePath
  8204. }
  8205. })
  8206. .width('28%')
  8207. Row() {
  8208. Column() {
  8209. Text(item.name)
  8210. .fontSize(17)
  8211. .maxLines(1)
  8212. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  8213. .animation({
  8214. duration: 555,
  8215. curve: 'Linear',
  8216. })
  8217. .fontColor(this.themeColor)
  8218. .margin({ left: 8 })
  8219. Row() {
  8220. Text(item.artist)
  8221. .fontSize(14)
  8222. .maxLines(1)
  8223. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  8224. .padding({ top: 8 })
  8225. .fontColor(this.themeColor)
  8226. .margin({ left: 8 })
  8227. }
  8228. }
  8229. .height('100%')
  8230. .width(100)
  8231. .layoutWeight(1)
  8232. .justifyContent(FlexAlign.Center)
  8233. .alignItems(HorizontalAlign.Start)
  8234. Column() {
  8235. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8236. Row(){
  8237. SymbolGlyph($r('sys.symbol.picture'))
  8238. .fontSize(18)
  8239. .fontColor([Color.White])
  8240. Text('获取封面')
  8241. .margin({ left: 4 })
  8242. .fontSize(11)
  8243. .fontColor(Color.White)
  8244. .fontWeight(480)
  8245. .textAlign(TextAlign.Center)
  8246. }
  8247. .justifyContent(FlexAlign.Center)
  8248. }
  8249. .height(38)
  8250. .width(100)
  8251. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8252. .backgroundColor(this.themeColor)
  8253. .stateEffect(true)
  8254. .margin({ right: 35 })
  8255. .onClick(async () => {
  8256. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  8257. this.showTipsDialog();
  8258. return; // Return empty string when no API is configured
  8259. }
  8260. const imagePath:string | undefined = await this.doSearchCover(item,
  8261. this.titleStr,this.artistStr);
  8262. console.info('onecold imagePath = '+imagePath)
  8263. if (StrUtil.isNotEmpty(imagePath)) {
  8264. //用户更改过图片
  8265. this.imagePathStr = imagePath
  8266. ToastUtil.showToast('获取封面成功')
  8267. }else{
  8268. ToastUtil.showToast('获取封面失败,请重试')
  8269. }
  8270. })
  8271. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8272. Row(){
  8273. SymbolGlyph($r('sys.symbol.input_mode'))
  8274. .fontSize(18)
  8275. .fontColor([Color.White])
  8276. Text('获取歌词')
  8277. .margin({ left: 4 })
  8278. .fontSize(11)
  8279. .fontColor(Color.White)
  8280. .fontWeight(480)
  8281. .textAlign(TextAlign.Center)
  8282. }
  8283. .justifyContent(FlexAlign.Center)
  8284. }
  8285. .height(38)
  8286. .width(100)
  8287. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8288. .backgroundColor(this.themeColor)
  8289. .stateEffect(true)
  8290. .margin({ top: 9, right: 35 })
  8291. .onClick(async () => {
  8292. //判断有没有设置api
  8293. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  8294. if (StrUtil.isEmpty(apiUrl)) {
  8295. this.isLyricSetting = false
  8296. this.showTipsDialog()
  8297. return
  8298. }
  8299. let res: string | undefined = await getApiLyric(apiUrl,
  8300. this.titleStr, this.artistStr, false);
  8301. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  8302. this.lyricConStr = res;
  8303. ToastUtil.showToast('获取歌词成功')
  8304. }else{
  8305. ToastUtil.showToast('获取歌词失败,请重试')
  8306. }
  8307. })
  8308. }
  8309. .justifyContent(FlexAlign.Start)
  8310. }
  8311. .height('100%')
  8312. .justifyContent(FlexAlign.Start)
  8313. .layoutWeight(1)
  8314. }
  8315. .width('100%')
  8316. .height(98)
  8317. Row() {
  8318. Text('标题:')
  8319. .fontSize(14)
  8320. .fontColor($r('app.color.text_color'))
  8321. .margin({ left: 22 })
  8322. TextInput({ text: this.titleStr })
  8323. .height(40)
  8324. .maxLines(1)
  8325. .fontSize(14)
  8326. .layoutWeight(1)
  8327. .fontColor($r('app.color.text_color'))
  8328. .margin({ right: 15, left: 10 })
  8329. .onChange((val: string) => {
  8330. this.titleStr = val
  8331. })
  8332. Button('修复乱码',{ type: ButtonType.Capsule, stateEffect: true})
  8333. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8334. .backgroundColor(this.themeColor)
  8335. .fontSize(10)
  8336. .margin({ right: 20})
  8337. .onClick(async () => {
  8338. let hwTags = await extractHwMediaMetadata(item.filePath)
  8339. let artist = hwTags?.artist|| '';
  8340. let title = hwTags?.title|| '';
  8341. let album = hwTags?.album|| '';
  8342. console.info('onecold 乱码修正 artist='+artist);
  8343. console.info('onecold 乱码修正 title='+title);
  8344. console.info('onecold 乱码修正 album='+album);
  8345. this.titleStr = title;
  8346. this.artistStr = artist;
  8347. this.ablumStr = album;
  8348. })
  8349. }
  8350. .width('100%')
  8351. .margin({ top: 10, bottom: 10 })
  8352. .justifyContent(FlexAlign.Start)
  8353. Row() {
  8354. Text('艺术家:')
  8355. .fontSize(14)
  8356. .fontColor($r('app.color.text_color'))
  8357. .margin({ left: 22 })
  8358. TextInput({ text: this.artistStr })
  8359. .height(40)
  8360. .maxLines(1)
  8361. .fontSize(14)
  8362. .layoutWeight(1)
  8363. .fontColor($r('app.color.text_color'))
  8364. .margin({ right: 20, left: 10 })
  8365. .onChange((val: string) => {
  8366. this.artistStr = val
  8367. })
  8368. }
  8369. .width('100%')
  8370. .margin({ top: 10, bottom: 10 })
  8371. .justifyContent(FlexAlign.Start)
  8372. Row() {
  8373. Text('专辑名:')
  8374. .fontSize(14)
  8375. .fontColor($r('app.color.text_color'))
  8376. .margin({ left: 22 })
  8377. TextInput({ text: this.ablumStr})
  8378. .height(40)
  8379. .maxLines(1)
  8380. .fontSize(14)
  8381. .layoutWeight(1)
  8382. .fontColor($r('app.color.text_color'))
  8383. .margin({ right: 20, left: 10 })
  8384. .onChange((val: string) => {
  8385. this.ablumStr = val
  8386. })
  8387. }
  8388. .width('100%')
  8389. .margin({ top: 10, bottom: 10 })
  8390. .justifyContent(FlexAlign.Start)
  8391. Row() {
  8392. Column(){
  8393. Column(){
  8394. Text('歌词:')
  8395. .fontSize(14)
  8396. .fontColor($r('app.color.text_color'))
  8397. .margin({ top:9,left: 22 })
  8398. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8399. SymbolGlyph($r('sys.symbol.trash_fill'))
  8400. .fontSize(25)
  8401. .alignSelf(ItemAlign.Center)
  8402. .margin({ left: 22,top:25})
  8403. }
  8404. .backgroundColor(Color.Transparent)
  8405. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  8406. Visibility.None:Visibility.Visible)
  8407. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8408. .onClick(()=>{
  8409. this.lyricConStr = ''
  8410. this.lyricContent = ''
  8411. this.tempLyricContent = ''
  8412. })
  8413. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8414. SymbolGlyph($r('sys.symbol.plus'))
  8415. .fontSize(25)
  8416. .alignSelf(ItemAlign.Center)
  8417. .margin({ left: 22,top:25})
  8418. }
  8419. .backgroundColor(Color.Transparent)
  8420. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8421. .onClick( ()=>{
  8422. this.callFilePickerSelectFileForLyric()
  8423. })
  8424. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8425. SymbolGlyph($r('sys.symbol.traditional_square'))
  8426. .fontSize(25)
  8427. .alignSelf(ItemAlign.Center)
  8428. .margin({ left: 22,top:25})
  8429. }
  8430. .backgroundColor(Color.Transparent)
  8431. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  8432. Visibility.None:Visibility.Visible)
  8433. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8434. .onClick( ()=>{
  8435. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  8436. this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
  8437. })
  8438. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8439. Image($r('app.media.jianti'))
  8440. .height(25)
  8441. .fillColor($r('app.color.text_color'))
  8442. .alignSelf(ItemAlign.Center)
  8443. .margin({ left: 22,top:25})
  8444. }
  8445. .backgroundColor(Color.Transparent)
  8446. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  8447. Visibility.None:Visibility.Visible)
  8448. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8449. .onClick( ()=>{
  8450. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  8451. this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
  8452. })
  8453. }
  8454. .layoutWeight(1)
  8455. }
  8456. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  8457. this.tempLyricContent })
  8458. .type(TextAreaType.NORMAL)
  8459. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
  8460. .fontSize(14)
  8461. .layoutWeight(1)
  8462. .fontColor($r('app.color.text_color'))
  8463. .margin({ right: 20, left: 10 })
  8464. .onChange((val: string) => {
  8465. this.lyricConStr = val
  8466. })
  8467. }
  8468. .width('100%')
  8469. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
  8470. .margin({ top: 10, bottom: 10 })
  8471. .justifyContent(FlexAlign.Start)
  8472. Row() {
  8473. Text('年份:')
  8474. .fontSize(14)
  8475. .fontColor($r('app.color.text_color'))
  8476. .margin({ left: 22 })
  8477. TextInput({ text: item.year })
  8478. .height(40)
  8479. .maxLines(1)
  8480. .fontSize(14)
  8481. .type(InputType.Number)
  8482. .layoutWeight(1)
  8483. .fontColor($r('app.color.text_color'))
  8484. .margin({ right: 20, left: 10 })
  8485. .onChange((val: string) => {
  8486. this.yearStr = val
  8487. })
  8488. }
  8489. .width('100%')
  8490. .margin({ top: 10, bottom: 10 })
  8491. .justifyContent(FlexAlign.Start)
  8492. Row() {
  8493. Text('音轨号:')
  8494. .fontSize(14)
  8495. .fontColor($r('app.color.text_color'))
  8496. .margin({ left: 22 })
  8497. TextInput({ text:item.track=='未知'?'': item.track })
  8498. .height(40)
  8499. .maxLines(1)
  8500. .fontSize(14)
  8501. .type(InputType.Number)
  8502. .layoutWeight(1)
  8503. .fontColor($r('app.color.text_color'))
  8504. .margin({ right: 20, left: 10 })
  8505. .onChange((val: string) => {
  8506. this.trackStr = val
  8507. })
  8508. }
  8509. .width('100%')
  8510. .margin({ top: 10, bottom: 10 })
  8511. .justifyContent(FlexAlign.Start)
  8512. Row() {
  8513. Text('碟号:')
  8514. .fontSize(14)
  8515. .fontColor($r('app.color.text_color'))
  8516. .margin({ left: 22 })
  8517. TextInput({ text:item.disc })
  8518. .height(40)
  8519. .maxLines(1)
  8520. .fontSize(14)
  8521. .type(InputType.Number)
  8522. .layoutWeight(1)
  8523. .fontColor($r('app.color.text_color'))
  8524. .margin({ right: 20, left: 10 })
  8525. .onChange((val: string) => {
  8526. this.discStr = val
  8527. })
  8528. }
  8529. .width('100%')
  8530. .margin({ top: 10, bottom: 10 })
  8531. .justifyContent(FlexAlign.Start)
  8532. Row() {
  8533. Text('风格:')
  8534. .fontSize(14)
  8535. .fontColor($r('app.color.text_color'))
  8536. .margin({ left: 22 })
  8537. TextInput({ text: item.genre })
  8538. .height(40)
  8539. .maxLines(1)
  8540. .fontSize(14)
  8541. .layoutWeight(1)
  8542. .fontColor($r('app.color.text_color'))
  8543. .margin({ right: 20, left: 10 })
  8544. .onChange((val: string) => {
  8545. this.genreStr = val
  8546. })
  8547. }
  8548. .width('100%')
  8549. .margin({ top: 10, bottom: 10 })
  8550. .justifyContent(FlexAlign.Start)
  8551. Row() {
  8552. Text('专辑艺术家:')
  8553. .fontSize(14)
  8554. .fontColor($r('app.color.text_color'))
  8555. .margin({ left: 22 })
  8556. TextInput({ text: item.ALBUMARTIST })
  8557. .height(40)
  8558. .maxLines(1)
  8559. .fontSize(14)
  8560. .layoutWeight(1)
  8561. .fontColor($r('app.color.text_color'))
  8562. .margin({ right: 20, left: 10 })
  8563. .onChange((val: string) => {
  8564. this.albumArtistStr = val
  8565. })
  8566. }
  8567. .width('100%')
  8568. .margin({ top: 10, bottom: 10 })
  8569. .justifyContent(FlexAlign.Start)
  8570. Row() {
  8571. Text('作曲:')
  8572. .fontSize(14)
  8573. .fontColor($r('app.color.text_color'))
  8574. .margin({ left: 22 })
  8575. TextInput({ text: item.COMPOSER })
  8576. .height(40)
  8577. .maxLines(1)
  8578. .fontSize(14)
  8579. .layoutWeight(1)
  8580. .fontColor($r('app.color.text_color'))
  8581. .margin({ right: 20, left: 10 })
  8582. .onChange((val: string) => {
  8583. this.composerStr = val
  8584. })
  8585. }
  8586. .width('100%')
  8587. .margin({ top: 10, bottom: 10 })
  8588. .justifyContent(FlexAlign.Start)
  8589. Row() {
  8590. Text('作词:')
  8591. .fontSize(14)
  8592. .fontColor($r('app.color.text_color'))
  8593. .margin({ left: 22 })
  8594. TextInput({ text: item.LYRICIST })
  8595. .height(40)
  8596. .maxLines(1)
  8597. .fontSize(14)
  8598. .layoutWeight(1)
  8599. .fontColor($r('app.color.text_color'))
  8600. .margin({ right: 20, left: 10 })
  8601. .onChange((val: string) => {
  8602. this.lyricistStr = val
  8603. })
  8604. }
  8605. .width('100%')
  8606. .margin({ top: 10, bottom: 10 })
  8607. .justifyContent(FlexAlign.Start)
  8608. Row() {
  8609. Text('注释:')
  8610. .fontSize(14)
  8611. .fontColor($r('app.color.text_color'))
  8612. .margin({ left: 22 })
  8613. TextInput({ text: item.COMMENT })
  8614. .height(40)
  8615. .maxLines(1)
  8616. .fontSize(14)
  8617. .layoutWeight(1)
  8618. .fontColor($r('app.color.text_color'))
  8619. .margin({ right: 20, left: 10 })
  8620. .onChange((val: string) => {
  8621. this.commentStr = val
  8622. })
  8623. }
  8624. .width('100%')
  8625. .margin({ top: 10, bottom: 10 })
  8626. .justifyContent(FlexAlign.Start)
  8627. Row() {
  8628. Button('保存')
  8629. .fontColor(Color.White)
  8630. .layoutWeight(1)
  8631. .height(50)
  8632. .width(100)
  8633. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8634. .backgroundColor(this.themeColor)
  8635. .stateEffect(true)
  8636. .margin({ right: 20, bottom: 20 })
  8637. .onClick(async () => {
  8638. this.doEdit(item)
  8639. })
  8640. Button('取消')
  8641. .fontColor(Color.White)
  8642. .layoutWeight(1)
  8643. .height(50)
  8644. .width(100)
  8645. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  8646. .backgroundColor(this.themeColor)
  8647. .stateEffect(true)
  8648. .margin({ left: 20, bottom: 20 })
  8649. .onClick(async () => {
  8650. if(this.isGridMusic){
  8651. this.longItemFilePath =''
  8652. }else{
  8653. this.isShowEdit = false
  8654. }
  8655. this.setEditStrEmpty()
  8656. if(this.isShowPlay){
  8657. this.isShowEdit = false
  8658. }
  8659. })
  8660. }
  8661. .margin({
  8662. left: 38,
  8663. right: 38,
  8664. top: 10,
  8665. bottom: 10
  8666. })
  8667. .width(250)
  8668. .height(60)
  8669. }
  8670. }
  8671. .margin({ bottom: 20 })
  8672. }
  8673. setEditStrEmpty(){
  8674. this.imagePathStr = ''
  8675. this.lyricConStr = ''
  8676. this.artistStr = ''
  8677. this.titleStr = ''
  8678. this.ablumStr = ''
  8679. this.genreStr = ''
  8680. this.yearStr = ''
  8681. this.trackStr = ''
  8682. this.albumArtistStr = ''
  8683. this.composerStr = ''
  8684. this.lyricistStr = ''
  8685. this.commentStr = ''
  8686. this.discStr = ''
  8687. }
  8688. initEditFields(item?: VideoItem) {
  8689. if (!item) {
  8690. this.setEditStrEmpty()
  8691. return
  8692. }
  8693. this.imagePathStr = ''
  8694. this.titleStr = item.name ?? ''
  8695. this.artistStr = item.artist ?? ''
  8696. this.ablumStr = item.album ?? ''
  8697. this.genreStr = item.genre ?? ''
  8698. this.yearStr = item.year ?? ''
  8699. this.trackStr = item.track ?? ''
  8700. this.albumArtistStr = item.ALBUMARTIST ?? ''
  8701. this.composerStr = item.COMPOSER ?? ''
  8702. this.lyricistStr = item.LYRICIST ?? ''
  8703. this.commentStr = item.COMMENT ?? ''
  8704. this.discStr = item.disc ?? ''
  8705. this.lyricConStr = item.lyricContent ?? ''
  8706. }
  8707. private syncEditedFields(target?: VideoItem) {
  8708. if (!target) {
  8709. return
  8710. }
  8711. target.name = this.titleStr
  8712. target.artist = this.artistStr
  8713. target.album = this.ablumStr
  8714. target.lyricContent = this.lyricConStr
  8715. target.year = this.yearStr
  8716. target.genre = this.genreStr
  8717. target.track = this.trackStr
  8718. target.ALBUMARTIST = this.albumArtistStr
  8719. target.COMPOSER = this.composerStr
  8720. target.LYRICIST = this.lyricistStr
  8721. target.COMMENT = this.commentStr
  8722. target.disc = this.discStr
  8723. }
  8724. private replaceItemInList(list: Array<VideoItem> | undefined, filePath: string,
  8725. apply?: (next: Array<VideoItem>) => void) {
  8726. if (!list || ArrayUtil.isEmpty(list)) {
  8727. return
  8728. }
  8729. const index = list.findIndex((video: VideoItem) => video.filePath === filePath)
  8730. if (index < 0) {
  8731. return
  8732. }
  8733. const nextList = [...list]
  8734. this.syncEditedFields(nextList[index])
  8735. apply?.(nextList)
  8736. }
  8737. private syncListsAfterEdit(filePath: string) {
  8738. this.replaceItemInList(this.videoLocalList, filePath, (next: Array<VideoItem>) => {
  8739. this.videoLocalList = next
  8740. this.dataSource.pushArrayData(next)
  8741. })
  8742. this.replaceItemInList(this.songList, filePath, (next: Array<VideoItem>) => {
  8743. this.songList = next
  8744. this.sonDataSource.pushArrayData(next)
  8745. })
  8746. this.replaceItemInList(this.favList, filePath, (next: Array<VideoItem>) => {
  8747. this.favList = next
  8748. })
  8749. this.replaceItemInList(this.historyList, filePath, (next: Array<VideoItem>) => {
  8750. this.historyList = next
  8751. })
  8752. this.replaceItemInList(this.currentSongList, filePath, (next: Array<VideoItem>) => {
  8753. this.currentSongList = next
  8754. })
  8755. this.replaceItemInList(this.mediaKuList, filePath, (next: Array<VideoItem>) => {
  8756. this.mediaKuList = next
  8757. })
  8758. this.replaceItemInList(this.filteredList, filePath, (next: Array<VideoItem>) => {
  8759. this.filteredList = next
  8760. })
  8761. this.replaceItemInList(this.artistList, filePath, (next: Array<VideoItem>) => {
  8762. this.artistList = next
  8763. })
  8764. this.replaceItemInList(this.albumList, filePath, (next: Array<VideoItem>) => {
  8765. this.albumList = next
  8766. })
  8767. this.listRefreshKey++
  8768. }
  8769. private refreshLazyListViews(mainListUpdated: boolean, playlistUpdated: boolean): void {
  8770. if (!mainListUpdated && !playlistUpdated) {
  8771. return;
  8772. }
  8773. this.listRefreshKey++;
  8774. if (mainListUpdated) {
  8775. this.dataSource.notifyDataReload();
  8776. }
  8777. if (playlistUpdated) {
  8778. this.sonDataSource.notifyDataReload();
  8779. }
  8780. }
  8781. @Builder
  8782. detailSheet(item:VideoItem) {
  8783. Scroll() {
  8784. Column() {
  8785. this.songDetail(item)
  8786. }
  8787. }
  8788. .width('100%')
  8789. .height('100%')
  8790. }
  8791. @Builder
  8792. songDetail(currentItem:VideoItem) {
  8793. Column() {
  8794. if (currentItem) {
  8795. Row() {
  8796. Stack() {
  8797. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.alt') :
  8798. currentItem.pixelMapPath)
  8799. .fillColor(this.themeColor)
  8800. .height(80)
  8801. .width(80)
  8802. .borderRadius(10)
  8803. .opacity(this.opacityItem)// 绑定透明度
  8804. .margin({ left: 22 })
  8805. }
  8806. Column() {
  8807. Column() {
  8808. Text(currentItem.name)
  8809. .fontSize(16)
  8810. .maxLines(1)
  8811. .animation({
  8812. duration: 555,
  8813. curve: 'Linear',
  8814. })
  8815. .fontColor($r('app.color.text_color'))
  8816. .margin({ left: 15 })
  8817. }
  8818. .height('100%')
  8819. .width('100%')
  8820. .justifyContent(FlexAlign.Center)
  8821. .alignItems(HorizontalAlign.Start)
  8822. }
  8823. .height('100%')
  8824. }
  8825. .width('100%')
  8826. .height(90)
  8827. .justifyContent(FlexAlign.SpaceBetween)
  8828. Row() {
  8829. Text('艺术家:')
  8830. .fontSize(14)
  8831. .fontColor($r('app.color.text_color'))
  8832. .margin({ left: 22 })
  8833. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  8834. .fontSize(14)
  8835. .fontColor($r('app.color.text_color'))
  8836. .margin({ left: 10 })
  8837. .layoutWeight(1)
  8838. }
  8839. .width('100%')
  8840. .margin({ top: 10, bottom: 10 })
  8841. .justifyContent(FlexAlign.Start)
  8842. Row() {
  8843. Text('专辑名:')
  8844. .fontSize(14)
  8845. .fontColor($r('app.color.text_color'))
  8846. .margin({ left: 22 })
  8847. Text(currentItem?.album ?currentItem.album : '未知专辑')
  8848. .fontSize(14)
  8849. .margin({ left: 10 })
  8850. .fontColor($r('app.color.text_color'))
  8851. .layoutWeight(1)
  8852. }
  8853. .width('100%')
  8854. .margin({ top: 10, bottom: 10 })
  8855. .justifyContent(FlexAlign.Start)
  8856. Row() {
  8857. Text('时长:')
  8858. .fontSize(14)
  8859. .fontColor($r('app.color.text_color'))
  8860. .margin({ left: 22 })
  8861. Text(StrUtil.isEmpty(currentItem.duration)?
  8862. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  8863. .fontSize(14)
  8864. .margin({ left: 10 })
  8865. .fontColor($r('app.color.text_color'))
  8866. .layoutWeight(1)
  8867. }
  8868. .width('100%')
  8869. .margin({ top: 10, bottom: 10 })
  8870. .justifyContent(FlexAlign.Start)
  8871. Row() {
  8872. Text('采样率:')
  8873. .fontSize(14)
  8874. .fontColor($r('app.color.text_color'))
  8875. .margin({ left: 22 })
  8876. Text(Utility.convertToKHz(currentItem.sampleRate))
  8877. .fontSize(14)
  8878. .margin({ left: 10 })
  8879. .fontColor($r('app.color.text_color'))
  8880. .layoutWeight(1)
  8881. }
  8882. .width('100%')
  8883. .margin({ top: 10, bottom: 10 })
  8884. .justifyContent(FlexAlign.Start)
  8885. Row() {
  8886. Text('比特率:')
  8887. .fontSize(14)
  8888. .fontColor($r('app.color.text_color'))
  8889. .margin({ left: 22 })
  8890. Text(currentItem.bit_rate)
  8891. .fontSize(14)
  8892. .margin({ left: 10 })
  8893. .fontColor($r('app.color.text_color'))
  8894. .layoutWeight(1)
  8895. }
  8896. .width('100%')
  8897. .margin({ top: 10, bottom: 10 })
  8898. .justifyContent(FlexAlign.Start)
  8899. Row() {
  8900. Text('位深:')
  8901. .fontSize(14)
  8902. .fontColor($r('app.color.text_color'))
  8903. .margin({ left: 22 })
  8904. Text(`${currentItem.bits_per_raw_sample} bits`)
  8905. .fontSize(14)
  8906. .margin({ left: 10 })
  8907. .fontColor($r('app.color.text_color'))
  8908. .layoutWeight(1)
  8909. }
  8910. .width('100%')
  8911. .margin({ top: 10, bottom: 10 })
  8912. .justifyContent(FlexAlign.Start)
  8913. Row() {
  8914. Text('声道:')
  8915. .fontSize(14)
  8916. .fontColor($r('app.color.text_color'))
  8917. .margin({ left: 22 })
  8918. Text(`${currentItem.channels}`)
  8919. .fontSize(14)
  8920. .margin({ left: 10 })
  8921. .fontColor($r('app.color.text_color'))
  8922. .layoutWeight(1)
  8923. }
  8924. .width('100%')
  8925. .margin({ top: 10, bottom: 10 })
  8926. .justifyContent(FlexAlign.Start)
  8927. Row() {
  8928. Text('声道布局:')
  8929. .fontSize(14)
  8930. .fontColor($r('app.color.text_color'))
  8931. .margin({ left: 22 })
  8932. Text(`${currentItem.channel_layout}`)
  8933. .fontSize(14)
  8934. .margin({ left: 10 })
  8935. .fontColor($r('app.color.text_color'))
  8936. .layoutWeight(1)
  8937. }
  8938. .width('100%')
  8939. .margin({ top: 10, bottom: 10 })
  8940. .justifyContent(FlexAlign.Start)
  8941. Row() {
  8942. Text('起始播放点:')
  8943. .fontSize(14)
  8944. .fontColor($r('app.color.text_color'))
  8945. .margin({ left: 22 })
  8946. Text(`${currentItem.start_time}`)
  8947. .fontSize(14)
  8948. .margin({ left: 10 })
  8949. .fontColor($r('app.color.text_color'))
  8950. .layoutWeight(1)
  8951. }
  8952. .width('100%')
  8953. .margin({ top: 10, bottom: 10 })
  8954. .justifyContent(FlexAlign.Start)
  8955. Row() {
  8956. Text('风格:')
  8957. .fontSize(14)
  8958. .fontColor($r('app.color.text_color'))
  8959. .margin({ left: 22 })
  8960. Text(currentItem.genre)
  8961. .fontSize(14)
  8962. .margin({ left: 10 })
  8963. .fontColor($r('app.color.text_color'))
  8964. .layoutWeight(1)
  8965. }
  8966. .width('100%')
  8967. .margin({ top: 10, bottom: 10 })
  8968. .justifyContent(FlexAlign.Start)
  8969. Row() {
  8970. Text('发行时间:')
  8971. .fontSize(14)
  8972. .fontColor($r('app.color.text_color'))
  8973. .margin({ left: 22 })
  8974. Text(currentItem.year)
  8975. .fontSize(14)
  8976. .margin({ left: 10 })
  8977. .fontColor($r('app.color.text_color'))
  8978. .layoutWeight(1)
  8979. }
  8980. .width('100%')
  8981. .margin({ top: 10, bottom: 10 })
  8982. .justifyContent(FlexAlign.Start)
  8983. Row() {
  8984. Text('质量评分:')
  8985. .fontSize(14)
  8986. .fontColor($r('app.color.text_color'))
  8987. .margin({ left: 22 })
  8988. Text(currentItem.probe_score+"")
  8989. .fontSize(14)
  8990. .margin({ left: 10 })
  8991. .fontColor($r('app.color.text_color'))
  8992. .layoutWeight(1)
  8993. }
  8994. .width('100%')
  8995. .margin({ top: 10, bottom: 10 })
  8996. .justifyContent(FlexAlign.Start)
  8997. Row() {
  8998. Text('音轨号:')
  8999. .fontSize(14)
  9000. .fontColor($r('app.color.text_color'))
  9001. .margin({ left: 22 })
  9002. Text(currentItem.track)
  9003. .fontSize(14)
  9004. .margin({ left: 10 })
  9005. .fontColor($r('app.color.text_color'))
  9006. .layoutWeight(1)
  9007. }
  9008. .width('100%')
  9009. .margin({ top: 10, bottom: 10 })
  9010. .justifyContent(FlexAlign.Start)
  9011. Row() {
  9012. Text('碟号:')
  9013. .fontSize(14)
  9014. .fontColor($r('app.color.text_color'))
  9015. .margin({ left: 22 })
  9016. Text(currentItem.disc)
  9017. .fontSize(14)
  9018. .margin({ left: 10 })
  9019. .fontColor($r('app.color.text_color'))
  9020. .layoutWeight(1)
  9021. }
  9022. .width('100%')
  9023. .margin({ top: 10, bottom: 10 })
  9024. .justifyContent(FlexAlign.Start)
  9025. Row() {
  9026. Text('专辑艺术家:')
  9027. .fontSize(14)
  9028. .fontColor($r('app.color.text_color'))
  9029. .margin({ left: 22 })
  9030. Text(currentItem.ALBUMARTIST)
  9031. .fontSize(14)
  9032. .margin({ left: 10 })
  9033. .fontColor($r('app.color.text_color'))
  9034. .layoutWeight(1)
  9035. }
  9036. .width('100%')
  9037. .margin({ top: 10, bottom: 10 })
  9038. .justifyContent(FlexAlign.Start)
  9039. Row() {
  9040. Text('作曲家:')
  9041. .fontSize(14)
  9042. .fontColor($r('app.color.text_color'))
  9043. .margin({ left: 22 })
  9044. Text(currentItem.COMPOSER)
  9045. .fontSize(14)
  9046. .margin({ left: 10 })
  9047. .fontColor($r('app.color.text_color'))
  9048. .layoutWeight(1)
  9049. }
  9050. .width('100%')
  9051. .margin({ top: 10, bottom: 10 })
  9052. .justifyContent(FlexAlign.Start)
  9053. Row() {
  9054. Text('作词家:')
  9055. .fontSize(14)
  9056. .fontColor($r('app.color.text_color'))
  9057. .margin({ left: 22 })
  9058. Text(currentItem.LYRICIST)
  9059. .fontSize(14)
  9060. .margin({ left: 10 })
  9061. .fontColor($r('app.color.text_color'))
  9062. .layoutWeight(1)
  9063. }
  9064. .width('100%')
  9065. .margin({ top: 10, bottom: 10 })
  9066. .justifyContent(FlexAlign.Start)
  9067. Row() {
  9068. Text('注释:')
  9069. .fontSize(14)
  9070. .fontColor($r('app.color.text_color'))
  9071. .margin({ left: 22 })
  9072. Text(currentItem.COMMENT)
  9073. .fontSize(14)
  9074. .margin({ left: 10 })
  9075. .fontColor($r('app.color.text_color'))
  9076. .layoutWeight(1)
  9077. }
  9078. .width('100%')
  9079. .margin({ top: 10, bottom: 10 })
  9080. .justifyContent(FlexAlign.Start)
  9081. Row() {
  9082. Text('格式:')
  9083. .fontSize(14)
  9084. .fontColor($r('app.color.text_color'))
  9085. .margin({ left: 22 })
  9086. Text(Utility.formatMimeType(currentItem.mimeType))
  9087. .fontSize(14)
  9088. .margin({ left: 10 })
  9089. .fontColor($r('app.color.text_color'))
  9090. .layoutWeight(1)
  9091. }
  9092. .width('100%')
  9093. .margin({ top: 10, bottom: 10 })
  9094. .justifyContent(FlexAlign.Start)
  9095. Row() {
  9096. Text('播放次数:')
  9097. .fontSize(14)
  9098. .fontColor($r('app.color.text_color'))
  9099. .margin({ left: 22 })
  9100. Text(currentItem.playCount?.toString())
  9101. .fontSize(14)
  9102. .margin({ left: 10 })
  9103. .fontColor($r('app.color.text_color'))
  9104. .layoutWeight(1)
  9105. }
  9106. .width('100%')
  9107. .margin({ top: 10, bottom: 10 })
  9108. .justifyContent(FlexAlign.Start)
  9109. Row() {
  9110. Text('流数量:')
  9111. .fontSize(14)
  9112. .fontColor($r('app.color.text_color'))
  9113. .margin({ left: 22 })
  9114. Text(currentItem.nb_streams?.toString())
  9115. .fontSize(14)
  9116. .margin({ left: 10 })
  9117. .fontColor($r('app.color.text_color'))
  9118. .layoutWeight(1)
  9119. }
  9120. .width('100%')
  9121. .margin({ top: 10, bottom: 10 })
  9122. .justifyContent(FlexAlign.Start)
  9123. Row() {
  9124. Text('文件大小:')
  9125. .fontSize(14)
  9126. .fontColor($r('app.color.text_color'))
  9127. .margin({ left: 22 })
  9128. Text(currentItem.size)
  9129. .fontSize(14)
  9130. .margin({ left: 10 })
  9131. .fontColor($r('app.color.text_color'))
  9132. .layoutWeight(1)
  9133. }
  9134. .width('100%')
  9135. .margin({ top: 10, bottom: 10 })
  9136. .justifyContent(FlexAlign.Start)
  9137. Row() {
  9138. Text('文件名:')
  9139. .fontSize(14)
  9140. .fontColor($r('app.color.text_color'))
  9141. .margin({ left: 22 })
  9142. Text(currentItem.fileName)
  9143. .fontSize(14)
  9144. .margin({ left: 10 })
  9145. .fontColor($r('app.color.text_color'))
  9146. .layoutWeight(1)
  9147. }
  9148. .width('100%')
  9149. .margin({ top: 10, bottom: 10 })
  9150. .justifyContent(FlexAlign.Start)
  9151. Row() {
  9152. Text('修改时间:')
  9153. .fontSize(14)
  9154. .fontColor($r('app.color.text_color'))
  9155. .margin({ left: 22 })
  9156. Text(currentItem.cTime)
  9157. .fontSize(14)
  9158. .margin({ left: 10 })
  9159. .fontColor($r('app.color.text_color'))
  9160. .layoutWeight(1)
  9161. }
  9162. .width('100%')
  9163. .margin({ top: 10, bottom: 10 })
  9164. .justifyContent(FlexAlign.Start)
  9165. Row() {
  9166. Text('存放目录:')
  9167. .fontSize(14)
  9168. .fontColor($r('app.color.text_color'))
  9169. .margin({ left: 22 })
  9170. Text(currentItem.filePath)
  9171. .fontSize(12)
  9172. .margin({ left: 10 })
  9173. .fontColor($r('app.color.text_color'))
  9174. .layoutWeight(1)
  9175. }
  9176. .margin({ top: 10, bottom: 10 })
  9177. .width('100%')
  9178. .justifyContent(FlexAlign.Start)
  9179. Row() {
  9180. Text('内嵌歌词:')
  9181. .fontSize(14)
  9182. .fontColor($r('app.color.text_color'))
  9183. .margin({ left: 22 })
  9184. Text(currentItem.lyricContent)
  9185. .fontSize(12)
  9186. .copyOption(CopyOptions.InApp)
  9187. .margin({ left: 10 })
  9188. .fontColor($r('app.color.text_color'))
  9189. .layoutWeight(1)
  9190. }
  9191. .margin({ top: 10, bottom: 10 })
  9192. .width('100%')
  9193. .justifyContent(FlexAlign.Start)
  9194. }
  9195. }
  9196. .margin({ bottom: 20 })
  9197. }
  9198. //定时关闭布局
  9199. @Builder
  9200. TimeCloseSheet() {
  9201. Scroll() {
  9202. Column() {
  9203. this.TimeClose()
  9204. }
  9205. }
  9206. .width('100%')
  9207. .height('100%')
  9208. }
  9209. //倒计时关闭音乐,退出App功能实现。
  9210. @State selectedMinutes: number = 0 // 0表示未开启
  9211. @State remainingSeconds: number = 0
  9212. // 预设时间选项
  9213. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  9214. private formatTime(seconds: number): string {
  9215. const mins = Math.floor(seconds / 60)
  9216. const secs = seconds % 60
  9217. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  9218. }
  9219. // 开始倒计时
  9220. private handleTimeSelect(minutes: number) {
  9221. if (minutes === this.selectedMinutes) {
  9222. this.stopCountdown();
  9223. this.selectedMinutes = 0;
  9224. return;
  9225. }
  9226. this.selectedMinutes = minutes;
  9227. this.remainingSeconds = minutes * 60;
  9228. this.startCountdown(); // 新增调用
  9229. }
  9230. @Builder
  9231. TimeClose() {
  9232. Column() {
  9233. // 倒计时显示区域
  9234. Text(this.selectedMinutes > 0 ?
  9235. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  9236. "定时关闭未开启")
  9237. .fontSize(17)
  9238. .fontColor($r('app.color.text_color'))
  9239. .margin({ top: 2, bottom: 8 });
  9240. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  9241. ForEach(this.presetTimes, (minutes: number, index: number) => {
  9242. // 单行时间选项容器
  9243. Row() {
  9244. // 文字描述区域
  9245. Text(this.getDisplayText(minutes))
  9246. .fontSize(15)
  9247. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  9248. $r('app.color.text_color'))// 选中态颜色变化
  9249. .textAlign(TextAlign.Start)
  9250. .layoutWeight(1); // 占据剩余空间
  9251. // 复选框样式的选择器
  9252. Row() {
  9253. if (minutes === this.selectedMinutes) {
  9254. // 选中状态 - 带勾号的圆形复选框
  9255. Row() {
  9256. // 使用系统内置的勾号图标
  9257. Image($r('sys.media.ohos_ic_public_ok'))
  9258. .width(14)
  9259. .height(14)
  9260. .fillColor(Color.White)
  9261. }
  9262. .width(24)
  9263. .height(24)
  9264. .borderRadius(12)
  9265. .backgroundColor(this.themeColor)
  9266. .justifyContent(FlexAlign.Center)
  9267. .alignItems(VerticalAlign.Center)
  9268. } else {
  9269. // 未选中状态的圆形边框
  9270. Row()
  9271. .width(24)
  9272. .height(24)
  9273. .borderRadius(12)
  9274. .border({
  9275. width: 2,
  9276. color: $r('app.color.text_color'),
  9277. style: BorderStyle.Solid
  9278. })
  9279. .backgroundColor(Color.Transparent)
  9280. }
  9281. }
  9282. .width(24)
  9283. .height(24)
  9284. .margin({ left: 20 })
  9285. .justifyContent(FlexAlign.Center)
  9286. .alignItems(VerticalAlign.Center)
  9287. }
  9288. .width('100%')
  9289. .padding({
  9290. top: 18,
  9291. bottom: 18,
  9292. left: 18,
  9293. right: 18
  9294. })
  9295. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  9296. $r('app.color.bottom_control_background')) // 选中背景高亮
  9297. .borderRadius(12)
  9298. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9299. .margin({ bottom: 18 })
  9300. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  9301. });
  9302. }
  9303. .width('100%')
  9304. .padding(16)
  9305. }
  9306. }
  9307. // 获取显示文本
  9308. private getDisplayText(minutes: number): string {
  9309. if (minutes === -1) {
  9310. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  9311. }
  9312. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  9313. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  9314. }
  9315. // 处理选择事件
  9316. private handleSelect(minutes: number): void {
  9317. if (minutes === -1) { // 自定义
  9318. // 弹出自定义时间对话框
  9319. DialogHelper.showTextInputDialog({
  9320. title: '自定义时间',
  9321. maskColor: Color.Transparent,
  9322. inputType: InputType.Number,
  9323. text: '',
  9324. onChange: (text) => {
  9325. console.error("onChange: " + text);
  9326. },
  9327. onAction: (action, dialogId, content) => {
  9328. if (action == DialogAction.TWO) {
  9329. const customMinutes = Number(content);
  9330. if (customMinutes > 0) {
  9331. this.handleTimeSelect(customMinutes); // 设置自定义时间
  9332. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  9333. }
  9334. }
  9335. }
  9336. });
  9337. } else {
  9338. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  9339. }
  9340. }
  9341. // 添加定时器引用
  9342. private timerId: number = -1;
  9343. // 启动/重置倒计时
  9344. private startCountdown() {
  9345. // 清除旧定时器
  9346. if (this.timerId !== -1) {
  9347. clearInterval(this.timerId);
  9348. }
  9349. // 创建新定时器
  9350. if (this.selectedMinutes > 0) {
  9351. this.timerId = setInterval(() => {
  9352. if (this.remainingSeconds === 15) {
  9353. this.showConfirmationDialog();
  9354. }
  9355. if (this.remainingSeconds > 0) {
  9356. this.remainingSeconds -= 1;
  9357. } else {
  9358. this.stopCountdown();
  9359. this.handleTimeout();
  9360. }
  9361. }, 1000);
  9362. }
  9363. }
  9364. // 15倒计时后再次提示显示确认是否关闭App对话框
  9365. private showConfirmationDialog() {
  9366. DialogHelper.showAlertDialog({
  9367. backgroundColor: $r('app.color.btn_green'),
  9368. title: '确认关闭',
  9369. maskColor: Color.Transparent,
  9370. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  9371. borderStyle: BorderStyle.Dashed,
  9372. primaryButton: '暂不关闭',
  9373. secondaryButton: '确定',
  9374. onAction: (action) => {
  9375. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  9376. this.stopCountdown();
  9377. this.selectedMinutes = 0
  9378. } else if (action == DialogAction.TWO) {
  9379. }
  9380. }
  9381. })
  9382. }
  9383. // 停止倒计时
  9384. private stopCountdown() {
  9385. if (this.timerId !== -1) {
  9386. clearInterval(this.timerId);
  9387. this.timerId = -1;
  9388. }
  9389. }
  9390. // 超时处理
  9391. private handleTimeout() {
  9392. // 执行播放器关闭逻辑
  9393. this.selectedMinutes = 0;
  9394. ToastUtil.showToast(" 定时关闭已完成");
  9395. this.stop(); // 假设存在的播放器实例
  9396. //退出APP
  9397. const mContext = getContext(this) as common.UIAbilityContext
  9398. mContext.terminateSelf();
  9399. AvSessionController.getInstance(true).unregisterSessionListener()
  9400. }
  9401. //倒计时关闭音乐,退出App功能实现结束。
  9402. //播放列表的拖动List 重新排序
  9403. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  9404. //左滑操作 移动文件 重命名 删除等操作
  9405. @Builder
  9406. sonButton(item: VideoItem, index: number, filePath: string) {
  9407. Row() {
  9408. //加入下一首播放
  9409. Button() {
  9410. Image($r('app.media.next_to_play'))
  9411. .fillColor(Color.White)
  9412. .width(20)
  9413. }
  9414. .width(40)
  9415. .height(40)
  9416. .type(ButtonType.Circle)
  9417. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  9418. .backgroundColor(this.themeColor)
  9419. .margin(5)
  9420. .onClick(() => {
  9421. this.addToNextPlay(item);
  9422. })
  9423. Button() {
  9424. Image($r('app.media.close'))
  9425. .fillColor(Color.White)
  9426. .width(20)
  9427. }
  9428. .width(40)
  9429. .height(40)
  9430. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  9431. .type(ButtonType.Circle)
  9432. .backgroundColor(this.themeColor)
  9433. .margin(5)
  9434. .onClick(() => {
  9435. this.songList.splice(Number(index), 1)
  9436. this.sonDataSource.pushArrayData(this.songList)
  9437. })
  9438. Button() {
  9439. Image($r('app.media.share2'))
  9440. .fillColor(Color.White)
  9441. .width(20)
  9442. }
  9443. .width(40)
  9444. .height(40)
  9445. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  9446. .type(ButtonType.Circle)
  9447. .backgroundColor(this.themeColor)
  9448. .margin(5)
  9449. .onClick(() => {
  9450. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  9451. })
  9452. }
  9453. }
  9454. itemMoveSon(index: number, newIndex: number): void {
  9455. if (newIndex < 0 || newIndex >= this.songList.length) {
  9456. return;
  9457. }
  9458. let tmp = this.songList.splice(index, 1);
  9459. this.songList.splice(newIndex, 0, tmp[0]);
  9460. this.sonDataSource.pushArrayData(this.songList)
  9461. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  9462. if(this.modeType==4&&this.playlistTable){
  9463. updateAllSongsSortOrder(this.playlistTable, this.songList,this.currentSongListID)
  9464. }
  9465. }
  9466. @Builder
  9467. PlayList() {
  9468. List({ scroller: this.playListScroller }) {
  9469. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  9470. ListItem() {
  9471. this.MusicItemSon(item, index)
  9472. }
  9473. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  9474. .animation({
  9475. duration: 666,
  9476. curve: 'ease-in-out' // 可选动画曲线
  9477. })
  9478. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 600 }),
  9479. TransitionEffect.scale({ x: 0, y: 0 })))
  9480. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  9481. //拖动List关键代码开始
  9482. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  9483. .zIndex(this.dragItem === index ? 1 : 0)
  9484. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  9485. .gesture(
  9486. GestureGroup(GestureMode.Sequence,
  9487. LongPressGesture({ repeat: true })
  9488. .onAction((event?: GestureEvent) => {
  9489. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  9490. this.scaleItem = index
  9491. })
  9492. })
  9493. .onActionEnd(() => {
  9494. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  9495. this.scaleItem = -1
  9496. })
  9497. }),
  9498. PanGesture({ fingers: 1, direction: null, distance: 0 })
  9499. .onActionStart(() => {
  9500. this.dragItem = index // 记录当前拖动项索引
  9501. this.dragRefOffset = 0 // 重置偏移基准
  9502. })
  9503. .onActionUpdate((event: GestureEvent) => {
  9504. this.offsetY = event.offsetY - this.dragRefOffset;
  9505. this.neighborItem = -1;
  9506. let indexA = this.songList.indexOf(item);
  9507. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  9508. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  9509. let value: number = 0;
  9510. if (this.offsetY < 0) {
  9511. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  9512. this.neighborItem = indexA - 1;
  9513. this.neighborScale = 1 - value / 20;
  9514. } else if (this.offsetY > 0) {
  9515. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  9516. this.neighborItem = indexA + 1;
  9517. this.neighborScale = 1 - value / 20;
  9518. }
  9519. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  9520. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  9521. this.offsetY -= this.ITEM_INTV;
  9522. this.dragRefOffset += this.ITEM_INTV;
  9523. this.itemMoveSon(indexA, indexA + 1);
  9524. });
  9525. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  9526. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  9527. this.offsetY += this.ITEM_INTV;
  9528. this.dragRefOffset -= this.ITEM_INTV;
  9529. this.itemMoveSon(indexA, indexA - 1);
  9530. });
  9531. }
  9532. })
  9533. .onActionEnd((event: GestureEvent) => {
  9534. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  9535. this.dragItem = -1
  9536. this.neighborItem = -1
  9537. })
  9538. animateTo({
  9539. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  9540. }, () => {
  9541. this.scaleItem = -1
  9542. })
  9543. })
  9544. )
  9545. .onCancel(() => {
  9546. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  9547. this.dragItem = -1
  9548. this.neighborItem = -1
  9549. })
  9550. animateTo({
  9551. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  9552. }, () => {
  9553. this.scaleItem = -1
  9554. })
  9555. })
  9556. ) //拖动List关键代码结束
  9557. .onClick(() => {
  9558. this.doPlay(item, index, true)
  9559. })
  9560. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  9561. }
  9562. .width('100%')
  9563. .height('100%')
  9564. .onReachEnd(() => {
  9565. if(this.modeType === 4 )
  9566. return;
  9567. // 检测是否是流媒体类型(Navidrome/Jellyfin/Emby/AudioStation/Plex),如果是则调用网盘加载更多逻辑
  9568. const isStreamingSong = this.currentSong && (
  9569. isNavidromeType(this.currentSong.type) ||
  9570. isJellyfinType(this.currentSong.type) ||
  9571. isEmbyType(this.currentSong.type) ||
  9572. isAudioStationType(this.currentSong.type) ||
  9573. isPlexType(this.currentSong.type)
  9574. );
  9575. if (isStreamingSong && hasMoreData()) {
  9576. Logger.info('heanup', '播放列表滚动到底部,加载更多流媒体歌曲');
  9577. void this.loadMoreNavidromeSongs();
  9578. } else {
  9579. void this.tryLoadNextPageForPlayback();
  9580. }
  9581. })
  9582. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  9583. // .animation({ duration: 500, curve: Curve.Ease }))
  9584. .cachedCount(10)
  9585. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  9586. .gesture(PinchGesture({ fingers: 2 })
  9587. .onActionEnd((event: GestureEvent) => {
  9588. this.setSonListTwoFingers()
  9589. })
  9590. .onActionUpdate(e => {
  9591. this.scaleValue = this.pinchValue * e.scale
  9592. })
  9593. .onActionStart(e => {
  9594. }))
  9595. .padding({
  9596. bottom: 0
  9597. })
  9598. }
  9599. setSonListTwoFingers() {
  9600. this.pinchValue = this.scaleValue;
  9601. Logger.info('this.pinchValue = ' + this.pinchValue);
  9602. if (this.pinchValue >= 1) {
  9603. this.sonTwoFingerType++
  9604. Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
  9605. if (this.sonTwoFingerType > 3) {
  9606. this.sonTwoFingerType = 1
  9607. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  9608. }
  9609. } else {
  9610. this.sonTwoFingerType--
  9611. Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
  9612. if (this.sonTwoFingerType < 1) {
  9613. this.sonTwoFingerType = 1
  9614. }
  9615. }
  9616. PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
  9617. this.pinchValue = 1;
  9618. this.scaleValue = 1;
  9619. }
  9620. @State sonTwoFingerType:number = 3
  9621. @Builder
  9622. private MusicItemSon(item: VideoItem, index?: number) {
  9623. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  9624. Row() {
  9625. Stack() {
  9626. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  9627. .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  9628. .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  9629. .alt($r('app.media.alt'))
  9630. .fillColor(this.themeColor)
  9631. .borderRadius(this.isCoverRectangle?11:'100%')
  9632. .clip(true)
  9633. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  9634. .draggable(false)// 禁止长按手势拖动
  9635. .autoResize(true) // 重采样,可减少内存占用
  9636. .margin({ left: 20 })
  9637. }
  9638. .width('15%')
  9639. Column() {
  9640. Column() {
  9641. Text(this.isShowFileName?item.fileName :item.name)
  9642. .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
  9643. .fontColor(this.curIndex === index ? this.themeColor :
  9644. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  9645. .maxLines(1)
  9646. .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
  9647. Row() {
  9648. Column(){
  9649. Text(item.md5Str?.includes('Lossless')?
  9650. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  9651. .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
  9652. .padding({ top: 3,right:6,left:6,bottom:3 })
  9653. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  9654. $r('app.color.text_color'))
  9655. .fontWeight(500)
  9656. .borderRadius(12)
  9657. .visibility(StrUtil.isEmpty(item.md5Str) ? Visibility.None : Visibility.Visible)
  9658. .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
  9659. .backgroundColor('#FFC107')
  9660. }
  9661. .padding({ top: 8 })
  9662. Text(StrUtil.isEmpty(item.artist) ? item.duration :
  9663. item.artist + ' ' + item?.duration)
  9664. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  9665. .padding({ top: 8 })
  9666. .maxLines(1)
  9667. .fontColor(this.curIndex === index ? this.themeColor :
  9668. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  9669. .margin({ left: StrUtil.isEmpty(item.md5Str)? 12 :this.sonTwoFingerType == 3 ? 5 : 3 })
  9670. Blank()
  9671. Text(item.size)
  9672. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  9673. .padding({ top: 8 })
  9674. .maxLines(1)
  9675. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  9676. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  9677. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  9678. .margin({ left: 10 })
  9679. }
  9680. }
  9681. .height('100%')
  9682. .width('100%')
  9683. .justifyContent(FlexAlign.Center)
  9684. .alignItems(HorizontalAlign.Start)
  9685. }
  9686. .height('100%')
  9687. .width('65%')
  9688. Column() {
  9689. ImageAnimator()
  9690. .images(this.imagesF)// 动画数组
  9691. .duration(1000)// 持续
  9692. .state(this.animationState)// 动画状态
  9693. .fillMode(FillMode.Forwards)
  9694. .width(18)
  9695. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  9696. Visibility.None)
  9697. .height(18)
  9698. .iterations(-1) // 播放次数
  9699. }
  9700. .width('20%')
  9701. }
  9702. }
  9703. .backgroundColor(Color.Transparent)
  9704. .width('100%')
  9705. .reuseId('son_item')
  9706. .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
  9707. .shadow(this.scaleItem === index ? {
  9708. radius: 70,
  9709. color: '#15000000',
  9710. offsetX: 0,
  9711. offsetY: 0
  9712. } :
  9713. {
  9714. radius: 0,
  9715. color: '#15000000',
  9716. offsetX: 0,
  9717. offsetY: 0
  9718. })
  9719. .animation({ curve: Curve.Sharp, duration: 300 })
  9720. }
  9721. @Builder
  9722. MusicPlayBuilder() {
  9723. Column() {
  9724. this.IjkMusicPlayerView()
  9725. }
  9726. .transition(TransitionEffect.asymmetric(
  9727. TransitionEffect.opacity(1),
  9728. TransitionEffect.OPACITY
  9729. ))
  9730. .visualEffect(deviceInfo.sdkApiVersion>=20&&this.bgController?
  9731. new hdsEffect.HdsEffectBuilder()
  9732. .shaderEffect({
  9733. effectType: hdsEffect.EffectType.UV_BACKGROUND_FLOW_LIGHT,
  9734. animation: {
  9735. duration: 10000,
  9736. iterations: -1,
  9737. autoPlay: true,
  9738. onFinish: ()=> {
  9739. console.info('Succeeded in finishing');
  9740. }
  9741. },
  9742. controller: this.bgController,
  9743. })
  9744. .buildEffect():null)
  9745. .height('100%')
  9746. .width('100%')
  9747. .onDisAppear(() => {
  9748. this.translateY = 0;
  9749. this.playDragUiOpacity = 1
  9750. })
  9751. .translate({ y: this.translateY })
  9752. .gesture(
  9753. PanGesture(this.panOption)
  9754. .onActionUpdate((event?: GestureEvent) => {
  9755. if (event) {
  9756. // 判断滑动方向
  9757. const offsetY = event.offsetY ?? 0;
  9758. const isSwipeUp = offsetY < 0;
  9759. if (isSwipeUp) {
  9760. // 向上滑动:不应用位移动画,保持 translateY = 0
  9761. this.translateY = 0;
  9762. this.scaleValueImage = 1
  9763. this.scaleValueText = 1
  9764. this.playDragUiOpacity = 1
  9765. } else {
  9766. if(this.isGeKongPlayNext){
  9767. return
  9768. }
  9769. // 向下滑动:应用位移动画
  9770. this.translateY = offsetY;
  9771. // 向下滑动时的缩放效果
  9772. this.getUIContext().animateTo({
  9773. duration: 500,
  9774. curve: Curve.Sharp
  9775. }, () => {
  9776. this.scaleValueImage = Math.min(1, Math.max(0.5, 1 - this.translateY / 880));
  9777. console.info('onecold scaleValueImage:', this.scaleValueImage)
  9778. this.scaleValueText = Math.min(1, Math.max(0.88, 1 - this.translateY / 2000));
  9779. this.playDragUiOpacity = Math.min(1, Math.max(0, 1 - this.translateY / 300));
  9780. })
  9781. }
  9782. }
  9783. })
  9784. .onActionEnd((event?: GestureEvent) => {
  9785. // 判断滑动方向
  9786. const offsetY = event?.offsetY ?? 0;
  9787. const isSwipeUp = offsetY < 0;
  9788. const minDistance = 300; // 最小滑动距离
  9789. const minVelocity = 500; // 最小滑动速度
  9790. const velocity = event?.velocityY ?? 0;
  9791. if (isSwipeUp) {
  9792. // 向上滑动:切换下一首
  9793. const shouldSwitch = this.isPlayPageSwipeNext &&
  9794. (Math.abs(offsetY) > minDistance || Math.abs(velocity) > minVelocity);
  9795. if (shouldSwitch) {
  9796. // 直接切换下一首,无需动画(因为界面没有移动)
  9797. this.playNext().catch(() => {
  9798. Logger.error('heanup MusicPlayBuilder', '向上滑动切换下一首失败');
  9799. });
  9800. }
  9801. } else {
  9802. //这里加个变量,是否开启隔空手势播放下一首
  9803. if(this.isGeKongPlayNext){
  9804. this.playNext()
  9805. return
  9806. }
  9807. // 向下滑动:关闭播放页
  9808. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  9809. if (shouldClose) {
  9810. // 添加关闭动画
  9811. this.getUIContext().animateTo({
  9812. duration: 600,
  9813. curve: Curve.Friction
  9814. }, () => {
  9815. this.isShowPlay = false;
  9816. this.scaleValueImage = 1
  9817. this.scaleValueText = 1
  9818. this.playDragUiOpacity = 1
  9819. this.translateY = 0;
  9820. })
  9821. } else {
  9822. // 回弹动画
  9823. this.getUIContext().animateTo({
  9824. duration: 600,
  9825. curve: Curve.Friction
  9826. }, () => {
  9827. this.scaleValueImage = 1
  9828. this.scaleValueText = 1
  9829. this.playDragUiOpacity = 1
  9830. this.translateY = 0;
  9831. })
  9832. }
  9833. }
  9834. })
  9835. )
  9836. }
  9837. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  9838. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  9839. HeightBreakpoint.HEIGHT_LG;
  9840. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  9841. @State topBarHeight: number = 50
  9842. @State barOpacity: number = 1
  9843. @State barBottomOpacity: number = 1
  9844. private hideDone: boolean = false;
  9845. @State currentYOffset: number = 0;
  9846. @State bottomBarHeight: number = 68;
  9847. private isHiding: boolean = false;
  9848. //是否是Pura X外屏,或者小屏幕
  9849. isPuraWP() {
  9850. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  9851. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  9852. }
  9853. //是否是Pura X外屏,或者小屏幕,手机横屏
  9854. /**
  9855. * 是否是Pura X外屏,或者小屏幕,手机横屏
  9856. * @returns
  9857. */
  9858. isCoverOpacity() {
  9859. if (this.isPuraWP()) {
  9860. return true
  9861. }
  9862. if (this.isPhoneLan()) {
  9863. return true
  9864. }
  9865. if (deviceInfo.marketName.includes('Pura X')
  9866. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  9867. return true
  9868. }
  9869. return false
  9870. }
  9871. //是不是手机横屏
  9872. isPhoneLan() {
  9873. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  9874. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  9875. logHiCarWindow(`isPhoneLan width=${this.windowWidth}`);
  9876. logHiCarWindow(`isPhoneLan height=${this.windowHeight}`);
  9877. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarStatus=${this.isHiCarStatus}`);
  9878. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, curDisplayIsHiCar=${this.curDisplayIsHiCar}`);
  9879. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall=${this.isHiCarSmall()}`);
  9880. if (this.isHiCarKuanBianPing()) {
  9881. return true
  9882. }
  9883. if (this.isHiCar()) {
  9884. return false
  9885. }
  9886. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  9887. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  9888. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  9889. return true
  9890. }
  9891. return false
  9892. }
  9893. //是不是1920x720的hicar的屏幕分辨率
  9894. isHiCarKuanBianPing(){
  9895. // if(!this.isHiCar()){
  9896. // return false
  9897. // }
  9898. const hiCarAspectRatios: HiCarAspectRatio[] = [
  9899. { ratio: 1920 / 720, name: "1920x720" },
  9900. ];
  9901. const currentRatio: number = this.windowWidth / this.windowHeight;
  9902. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  9903. logHiCarWindow(`HiCarKuanBianPing currentRatio=${currentRatio}`)
  9904. for (const hiCarRatio of hiCarAspectRatios) {
  9905. logHiCarWindow(`HiCarKuanBianPing hiCarRatio=${hiCarRatio.ratio}`)
  9906. logHiCarWindow(`HiCarKuanBianPing diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  9907. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  9908. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  9909. //宽扁平的尺寸设置列表展示
  9910. this.twoFingerType ==3
  9911. this.isGridMusic = false
  9912. return true;
  9913. }
  9914. }
  9915. return false;
  9916. }
  9917. //是不是hicar的屏幕分辨率
  9918. isHiCarSmall() {
  9919. if(!this.isHiCar()){
  9920. return false
  9921. }
  9922. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  9923. {
  9924. this.columns = 6
  9925. return false
  9926. }
  9927. const hiCarAspectRatios: HiCarAspectRatio[] = [
  9928. { ratio: 800 / 480, name: "800x480" },
  9929. { ratio: 1280 / 720, name: "1280x720" },
  9930. { ratio: 1920 / 1080, name: "1920x1080" },
  9931. ];
  9932. const currentRatio: number = this.windowWidth / this.windowHeight;
  9933. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  9934. logHiCarWindow(`HiCarSmall currentRatio=${currentRatio}`)
  9935. for (const hiCarRatio of hiCarAspectRatios) {
  9936. logHiCarWindow(`HiCarSmall hiCarRatio=${hiCarRatio.ratio}`)
  9937. logHiCarWindow(`HiCarSmall diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  9938. logHiCarWindow(`HiCarSmall isHiCarStatus=${this.isHiCarStatus}`);
  9939. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  9940. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  9941. //宽扁平的尺寸设置列表展示
  9942. return true;
  9943. }
  9944. }
  9945. return false;
  9946. }
  9947. isHiCar(): boolean {
  9948. return this.curDisplayIsHiCar;
  9949. }
  9950. //是不是正常的手机竖屏
  9951. isPhonePortrait() {
  9952. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  9953. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  9954. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  9955. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  9956. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  9957. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  9958. return true
  9959. }
  9960. return false
  9961. }
  9962. @State showSpeedDialog: boolean = false
  9963. @State longPressSpeed: number = 3 //长按默认倍数
  9964. @Builder
  9965. SpeedDialog() {
  9966. Stack() {
  9967. Column() {
  9968. Text('已切换至' + this.longPressSpeed + '倍速播放')
  9969. .fontColor(Color.White)
  9970. .visibility(Visibility.Hidden)
  9971. }
  9972. .backgroundColor(Color.Black)
  9973. .borderRadius(20)
  9974. .padding({
  9975. top: 10,
  9976. right: 20,
  9977. left: 15,
  9978. bottom: 20
  9979. })
  9980. .opacity(0.6)
  9981. Text('已切换至' + this.longPressSpeed + '倍速播放')
  9982. .fontColor(Color.White)
  9983. }
  9984. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  9985. .zIndex(5)
  9986. .margin({ top: 80 })
  9987. }
  9988. @Builder
  9989. IjkMusicPlayerView() {
  9990. Stack() {
  9991. if(canIUse("SystemCapability.UIDesign.HDSComponent.Core")
  9992. &&deviceInfo.sdkApiVersion>=20&&this.sceneBgController){
  9993. HdsVisualComponent()
  9994. .scene(HdsSceneType.DUAL_EDGE_FLOW_LIGHT_WITH_BACKGROUND_MASK, this.sceneBgController, () => {
  9995. console.info('Succeeded in finishing');
  9996. })
  9997. .width('100%')
  9998. .height('100%')
  9999. .visibility(this.isShowBgLiuGUANG?Visibility.Visible:Visibility.None)
  10000. }
  10001. Column() {
  10002. Column() {
  10003. //播放标题
  10004. Column() {
  10005. this.PlayTitle()
  10006. }
  10007. .opacity(this.playDragUiOpacity)
  10008. .position({ x: 0, y: this.isCoverOpacity() ? 10 : 30 })
  10009. .width('100%')
  10010. .margin({ top: 0 })
  10011. .height(PlayConstants.HEIGHT)
  10012. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  10013. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  10014. if (this.showSpeedDialog) {
  10015. this.SpeedDialog()
  10016. }
  10017. Stack() {
  10018. //手势拖动快进
  10019. Column()
  10020. .width(CommonConstants.FULL_PERCENT)
  10021. .height('100%')
  10022. .gesture(
  10023. GestureGroup(GestureMode.Parallel,
  10024. // 长按屏幕倍数播放
  10025. LongPressGesture({ repeat: true })
  10026. .onAction(() => {
  10027. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  10028. this.showSpeedDialog = true;
  10029. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  10030. }
  10031. })
  10032. .onActionEnd(() => {
  10033. this.showSpeedDialog = false;
  10034. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  10035. }),
  10036. //双击屏幕暂停或者播放
  10037. TapGesture({ count: 2 })
  10038. .onAction((event: GestureEvent) => {
  10039. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  10040. ToastUtil.showToast('已暂停')
  10041. }
  10042. console.info('onecold playOrPause 6693')
  10043. this.playOrPause()
  10044. })
  10045. )
  10046. )
  10047. }
  10048. .height('65%')
  10049. Swiper() {
  10050. this.CoverInfo()
  10051. this.PlayerLyrics()
  10052. }
  10053. .onChange((index: number) => {
  10054. this.currentSwiperIndex = index
  10055. if (index === 1) {
  10056. this.syncLyricPositionNow()
  10057. }
  10058. })
  10059. .indicator(false)
  10060. .displayCount(this.getPlayerSwiperDisplayCount())
  10061. .clip(false)
  10062. .loop(false)
  10063. .autoPlay(false)
  10064. // .interval(8000)
  10065. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  10066. .height('100%')
  10067. .hitTestBehavior(HitTestMode.Transparent)
  10068. Image($r('app.media.icon_replay'))
  10069. .objectFit(ImageFit.Auto)
  10070. .width('120px')
  10071. .height('120px')
  10072. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  10073. .border({ width: 0 })
  10074. .visibility(Visibility.None)
  10075. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  10076. .onClick(() => {
  10077. console.info('onecold startPlayOrResumePlay 6744')
  10078. this.startPlayOrResumePlay();
  10079. })
  10080. }
  10081. .width(CommonConstants.FULL_PERCENT)
  10082. .height(CommonConstants.FULL_PERCENT)
  10083. .justifyContent(FlexAlign.End)
  10084. }
  10085. .justifyContent(FlexAlign.End)
  10086. .margin({ bottom: 5 })
  10087. }
  10088. .backgroundImage(!this.isMusicBGCover||StrUtil.isEmpty(this.cover)?null: this.cover)
  10089. .backgroundImageSize(this.isPuraWP()||!this.isMusicBGCover ? { width: '100%' } : { height: '150%', width: '100%' })
  10090. .animation({
  10091. duration: 666,
  10092. curve: 'ease-in-out' // 可选动画曲线
  10093. })
  10094. .backgroundBlurStyle((this.isPuraWP() && this.currentSwiperIndex === 0) ||!this.isMusicBGCover
  10095. ? BlurStyle.NONE :
  10096. BlurStyle.BACKGROUND_ULTRA_THICK)
  10097. .hitTestBehavior(HitTestMode.Transparent)
  10098. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  10099. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  10100. .onClick(() => {
  10101. if(this.isHiCar())
  10102. return
  10103. if(this.is_auto_hide_progress){
  10104. this.is_auto_hide_progress = false
  10105. }
  10106. this.startAutoHide()
  10107. })
  10108. }
  10109. @Consume progressValue: number ;
  10110. @State currentTime: string = "00:00";
  10111. @State totalTime: string = "00:00";
  10112. @State loadingVisible: Visibility = Visibility.None;
  10113. @State replayVisible: Visibility = Visibility.None;
  10114. @State slideEnable: boolean = false;
  10115. @State aspRatio: number = 0.5;
  10116. @State mContext: object | undefined = undefined;
  10117. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  10118. @State mFirst: boolean = true;
  10119. @State mDestroyPage: boolean = false;
  10120. @State playSpeed: number = 1;
  10121. @State oldSeconds: number = 0;
  10122. @State isSeekTo: boolean = false;
  10123. @State isCurrentTime: boolean = false;
  10124. @State videoWidth: string = '100%';
  10125. @State videoHeight: string = '100%';
  10126. @State initAspectRatio: number = 1;
  10127. @State videoAspectRatio: number = this.initAspectRatio;
  10128. @State videoUrl: string = '';
  10129. private last: number = 0;
  10130. @State videoParentAspectRatio: number = this.initAspectRatio;
  10131. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  10132. @Consume CONTROL_PlayStatus: number ;
  10133. @State PROGRESS_MAX_VALUE: number = 100;
  10134. @State updateProgressTimer: number = 0;
  10135. private readonly progressUpdateIntervalMs: number = 120;
  10136. private readonly lyricUpdateMinDeltaMs: number = 24;
  10137. private lastLyricRenderPosition: number = Number.NaN;
  10138. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  10139. @State name: string = '';
  10140. // @State loop: boolean = false;
  10141. @State playType: number = 0; //0:连续循环播放 1:单片重复播放 2:正常播放 3:随机播放 4:连续播放不循环
  10142. @State multiple: string = '1.0X';
  10143. xcomponentController: XComponentController = new XComponentController()
  10144. private panOptionBright: PanGestureOptions =
  10145. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  10146. private panOptionVolume: PanGestureOptions =
  10147. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  10148. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  10149. //手势的音量控制和亮度控制
  10150. private positionX: number = PlayConstants.POSITION_X;
  10151. private positionY: number = PlayConstants.POSITION_Y;
  10152. private windowClass: window.Window = globalThis.windowClass
  10153. @State volume: number = 0.8;
  10154. @State volumeBoostPercent: number = 0
  10155. @State volumeSmall: boolean = false
  10156. @State autoParseMusicName: boolean = true
  10157. @State isShowFileName: boolean = false
  10158. @State isLongNameRoLL: boolean = true//长歌名滚动
  10159. private readonly volumeBoostPreferenceKey: string = 'volumeBoostPercent';
  10160. private readonly volumeBoostMaxPercent: number = 500;
  10161. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  10162. @State bright: number = PlayConstants.BRIGHT;
  10163. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  10164. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  10165. @State screenWidth: number = 0
  10166. @State screenHeight: number = 0
  10167. @State statusBarHeight: number = 0
  10168. @State isYesFull: boolean = false
  10169. private seekValue: number = 0
  10170. @State isVideoLock: boolean = false; // Whether the video playback is locked
  10171. private preloadNextRandomIndex: number = -1; // 预缓存的随机下一首索引
  10172. eventHub = getContext().eventHub;
  10173. private isAppForeground: boolean = true;
  10174. private lastBufferingLogTs: number = 0;
  10175. private readonly bufferingLogIntervalMs: number = 5000;
  10176. //投播组件
  10177. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  10178. // 新的投播控制器(封装了官方示例的逻辑)
  10179. private castControllerWrapper: CastController | undefined = undefined;
  10180. // 保留原始的 avCastController 引用(用于兼容旧代码)
  10181. private castController: avSession.AVCastController | undefined = undefined;
  10182. @State isCastPlaying: boolean = false;
  10183. @State currentTime2: number = 0;
  10184. @State currentStringTime: string = '00:00';
  10185. @State duration: number = 0;
  10186. @State isReady: boolean = false;
  10187. @State durationTime: number = 0;
  10188. @State durationStringTime: string = '00:00';
  10189. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  10190. // @State isPlaying: boolean = false;
  10191. private castSeek: boolean = false;
  10192. private castItem: avSession.AVQueueItem | undefined = undefined;
  10193. private castFile: fs.File | undefined = undefined; // 保持文件描述符引用,避免被垃圾回收
  10194. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  10195. @State rotateAngle2: number = -9
  10196. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  10197. @Consume cover: string | undefined ;
  10198. @State artist: string | undefined = ''
  10199. // 1.初始化controller
  10200. private lyricController: LyricController = new LyricController()
  10201. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  10202. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  10203. private parser = new LyricParser()
  10204. @State randomShakenX: number = 0
  10205. @State randomShakenY: number = 0
  10206. @State lyricTextSize: number = 24
  10207. @State lyricContent: string = ''
  10208. @State isDebug: boolean = false
  10209. @State isHightLightCenter: boolean = true
  10210. private syncWordByWordLyricMode(): void {
  10211. this.lyricController.setEnableWordByWordLyric(this.isEnableWordByWordLyric)
  10212. this.lyricControllerXF.setEnableWordByWordLyric(this.isEnableWordByWordLyric)
  10213. this.lyricControllerSingle.setEnableWordByWordLyric(this.isEnableWordByWordLyric)
  10214. }
  10215. /**
  10216. * 初始化歌词加载与展示逻辑
  10217. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  10218. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  10219. * @param isApi2 是否使用API2获取歌词(可选)
  10220. *
  10221. * 主要流程:
  10222. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  10223. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  10224. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  10225. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  10226. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  10227. * 6. 解析失败或读取失败时,清空歌词显示。
  10228. *
  10229. * 注意事项:
  10230. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  10231. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  10232. * - 歌词内容解析后通过lyricController驱动UI渲染。
  10233. */
  10234. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
  10235. if (StrUtil.isEmpty(lyricPath)) {
  10236. return
  10237. }
  10238. this.syncWordByWordLyricMode()
  10239. this.initPipLyricSetting()
  10240. this.lyricControllerSingle
  10241. .setTextSize(15)
  10242. .setCacheSize(4)
  10243. .setTextColor("#FFFFFF")
  10244. .setHighlightColor(this.currentHighLightLyricColor)
  10245. .setHighlightScale(1.2)
  10246. .setEmptyHint("")
  10247. .setLineSpace(1)
  10248. .setAlignMode('center')
  10249. .setAnimationDuration(500)
  10250. .setSingleLine(true)
  10251. this.lyricContent = ''
  10252. this.lyricController
  10253. .setTextSize(this.currentLyricSize)
  10254. .setCacheSize(4)
  10255. .setTextColor("#DDDDDD")
  10256. .setHighlightColor("#FFFFFF")
  10257. .setEmptyHint("")
  10258. .setAnimationDuration(1000)
  10259. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  10260. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  10261. this.setBlurDegree(this.blurDegree, false)
  10262. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  10263. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  10264. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  10265. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  10266. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  10267. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  10268. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  10269. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  10270. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  10271. this.lyricController.setTextWeight(this.lyricTextWeight)
  10272. this.showSingleLyric = false
  10273. // 加载已保存的歌词时间偏移
  10274. this.loadLyricTimeOffset()
  10275. this.lyricController.setLyric(null)
  10276. this.lyricControllerSingle.setLyric(null)
  10277. console.log("onecold lyricPath =" + lyricPath)
  10278. // 1. 检查内嵌歌词
  10279. let neiqianLrc = ''
  10280. let lyContent = this.currentSong?.lyricContent
  10281. if(lyContent && StrUtil.isNotEmpty(lyContent)){
  10282. neiqianLrc = lyContent
  10283. }
  10284. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast && !isLocal) {
  10285. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  10286. // Navidrome JSON歌词转换
  10287. if (this.currentSong && isNavidromeType(this.currentSong.type)) {
  10288. const convertedLyric: string | undefined = LyricUtil.convertNavidromeJsonLyricToLrc(neiqianLrc);
  10289. if (convertedLyric) {
  10290. neiqianLrc = convertedLyric;
  10291. console.log("onecold Navidrome歌词转换成功");
  10292. }
  10293. }
  10294. this.setLyricToControllers(neiqianLrc);
  10295. return
  10296. }
  10297. // 2. 远程播放实时探测歌词: 优先探测内嵌歌词,失败后查找同路径同名 .lrc
  10298. if (this.currentSong && shouldResolveRemoteLyricOnPlay(this.currentSong) && !isOnLineAndToast && !isLocal) {
  10299. const remoteLyric: string = await tryResolveRemotePlaybackLyric({
  10300. song: this.currentSong,
  10301. playbackUrl: this.videoUrl,
  10302. manager: RemoteDriveManager.getInstance(),
  10303. detectEncoding: (data: ArrayBuffer): string => this.detect(data)
  10304. });
  10305. if (StrUtil.isNotEmpty(remoteLyric)) {
  10306. this.currentSong.lyricContent = remoteLyric;
  10307. this.setLyricToControllers(remoteLyric);
  10308. void this.persistRemoteMetadataToDb(this.currentSong);
  10309. return;
  10310. }
  10311. }
  10312. // 3. 尝试从服务器获取歌词 (Navidrome/Jellyfin/Emby/AudioStation/Plex)
  10313. if (this.currentSong && (isJellyfinType(this.currentSong.type)||isNavidromeType(this.currentSong.type)
  10314. || isEmbyType(this.currentSong.type) || isAudioStationType(this.currentSong.type)
  10315. || isPlexType(this.currentSong.type))) {
  10316. const manager = RemoteDriveManager.getInstance();
  10317. const getAccount = (accountId: string) => manager.getWebDavAccountById(accountId);
  10318. // 将currentSong转换为SongData接口
  10319. const songData: SongData = {
  10320. webdav_account_id: this.currentSong.webdav_account_id,
  10321. artist: this.currentSong.artist,
  10322. name: this.currentSong.name,
  10323. webdav_id: this.currentSong.webdav_id,
  10324. lyricIndex: this.currentSong.lyricIndex,
  10325. type: this.currentSong.type
  10326. };
  10327. let serverLyric = '';
  10328. if (!serverLyric && isNavidromeType(songData.type)) {
  10329. serverLyric = await lyricService.fetchNavidromeLyric(songData, getAccount,this.currentSong.id);
  10330. }
  10331. if (!serverLyric && isJellyfinType(songData.type)) {
  10332. serverLyric = await lyricService.fetchJellyfinLyric(songData, getAccount);
  10333. }
  10334. if (!serverLyric && isEmbyType(songData.type)) {
  10335. serverLyric = await lyricService.fetchEmbyLyric(songData, getAccount);
  10336. }
  10337. if (!serverLyric && isAudioStationType(songData.type)) {
  10338. serverLyric = await lyricService.fetchAudioStationLyric(songData, getAccount);
  10339. }
  10340. if (!serverLyric && isPlexType(songData.type)) {
  10341. serverLyric = await lyricService.fetchPlexLyric(songData, getAccount);
  10342. }
  10343. if (serverLyric) {
  10344. this.setLyricToControllers(serverLyric, lyricPath);
  10345. return;
  10346. }
  10347. }
  10348. // 4. 尝试在线歌词API
  10349. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath))
  10350. && !Utility.isVideoByExtension(this.videoUrl))) {
  10351. this.fetchOnlineLyric(lyricPath, isOnLineAndToast || false, isApi2);
  10352. return;
  10353. }
  10354. // 5. 从本地文件读取歌词
  10355. await this.loadLyricFromFile(lyricPath, isLocal || false);
  10356. }
  10357. /**
  10358. * 从本地文件加载歌词
  10359. */
  10360. private async loadLyricFromFile(lyricPath: string, isLocal: boolean): Promise<void> {
  10361. try {
  10362. let realLyricPath = lyricPath;
  10363. // 读取文件内容
  10364. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  10365. const stat = await fileIo.stat(file.fd);
  10366. const arrayBuffer = new ArrayBuffer(stat.size);
  10367. fs.read(file.fd, arrayBuffer)
  10368. .then((readLen: number) => {
  10369. console.info("read file data succeed");
  10370. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  10371. if (buf.length === 0) {
  10372. throw new Error("Buffer is empty after reading the file");
  10373. }
  10374. try {
  10375. // 检测文件编码
  10376. let detectedEncoding = this.detect(arrayBuffer);
  10377. console.info("onecoldT Detected encoding: " + detectedEncoding);
  10378. // 使用检测到的编码解码,解决中文乱码问题
  10379. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  10380. console.info("onecoldT Detected textDecoder: " + textDecoder);
  10381. let fileContent = textDecoder.decode(buf);
  10382. console.info(`onecoldT The content of file1: ${fileContent}`);
  10383. console.info(`onecold The content of file2: ${fileContent}`);
  10384. this.lyricContent = fileContent;
  10385. if(isLocal){
  10386. // 编辑标签选择本地歌词需要赋值给this.lyricConStr
  10387. this.lyricConStr = fileContent;
  10388. }
  10389. this.setLyricToControllers(fileContent);
  10390. console.info(`The content of file: ${fileContent}`);
  10391. } catch (chardetError) {
  10392. console.error("chardet.detect failed with error: " + chardetError.message);
  10393. this.clearLyricControllers();
  10394. }
  10395. })
  10396. .catch((err: BusinessError) => {
  10397. this.clearLyricControllers();
  10398. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  10399. })
  10400. .catch((err: Error) => {
  10401. this.clearLyricControllers();
  10402. console.error("read file 2 data failed with error message: " + err.message);
  10403. })
  10404. .finally(() => {
  10405. fs.closeSync(file);
  10406. });
  10407. } catch (error) {
  10408. this.clearLyricControllers();
  10409. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  10410. }
  10411. }
  10412. detect(data: ArrayBuffer): string {
  10413. //创建检测对象
  10414. let detector: UniversalDetector = new UniversalDetector();
  10415. // 限制检测数据大小,避免内存溢出
  10416. // 通常只需要检测文件前16KB就足够判断编码格式
  10417. const MAX_DETECT_SIZE = 16 * 1024; // 16KB
  10418. const detectSize = Math.min(data.byteLength, MAX_DETECT_SIZE);
  10419. // 传入检测数据并实时判断编码格式
  10420. detector.handleData(data, 0, detectSize);
  10421. // 标记检测数据 读取结束
  10422. detector.dataEnd();
  10423. // 获取检测结果
  10424. let detected: string = detector.getDetectedCharset();
  10425. // 释放资源
  10426. detector.reset();
  10427. Logger.info(TAG, "heanup detect encoding: " + detected + ", data size: " + data.byteLength + ", detect size: " + detectSize);
  10428. return detected;
  10429. }
  10430. /**
  10431. * 设置歌词到所有控制器
  10432. * @param lyricText 歌词文本
  10433. * @param savePath 可选,如果提供则保存到本地文件
  10434. */
  10435. private setLyricToControllers(lyricText: string, savePath?: string): void {
  10436. if (StrUtil.isEmpty(lyricText)) {
  10437. this.clearLyricControllers();
  10438. return;
  10439. }
  10440. this.lyricContent = lyricText;
  10441. const lines: string[] = lyricText.split('\n').map((line: string) => line.trim());
  10442. const lyric: Lyric = this.parser.parse(lines);
  10443. this.lyricController.setLyric(lyric);
  10444. this.lyricControllerXF.setLyric(lyric);
  10445. this.lyricControllerSingle.setLyric(lyric);
  10446. this.showSingleLyric = true;
  10447. // 如果提供了保存路径,保存歌词到本地
  10448. if (savePath) {
  10449. this.saveDataToFile(lyricText, savePath);
  10450. }
  10451. }
  10452. /**
  10453. * 清空所有歌词控制器
  10454. */
  10455. private clearLyricControllers(): void {
  10456. this.lyricController.setLyric(null);
  10457. this.lyricControllerXF.setLyric(null);
  10458. this.lyricControllerSingle.setLyric(null);
  10459. }
  10460. private extractLyricCopyLines(lyricText: string): string[] {
  10461. if (StrUtil.isEmpty(lyricText)) {
  10462. return [];
  10463. }
  10464. const normalizedLyric = LyricUtil.convertLyricToSimpleLrc(lyricText);
  10465. const source = StrUtil.isNotEmpty(normalizedLyric) ? normalizedLyric : lyricText;
  10466. const lines = source.split('\n');
  10467. const result: string[] = [];
  10468. const metaTagPattern = /^\[(ti|ar|al|by|offset|hash|sign|qq|total|tool|re|ve|length|au):?.*]$/i;
  10469. for (let i = 0; i < lines.length; i++) {
  10470. const line = lines[i].trim();
  10471. if (!line || metaTagPattern.test(line)) {
  10472. continue;
  10473. }
  10474. const pureLine = line
  10475. .replace(/\[\d{1,2}:\d{2}(?:\.\d{1,3})?]/g, '')
  10476. .replace(/<\d{1,2}:\d{2}(?:\.\d{1,3})?>/g, '')
  10477. .trim();
  10478. if (pureLine.length > 0) {
  10479. result.push(pureLine);
  10480. }
  10481. }
  10482. return result;
  10483. }
  10484. private openLyricCopySheet(): void {
  10485. const lines = this.extractLyricCopyLines(this.lyricContent);
  10486. if (ArrayUtil.isEmpty(lines)) {
  10487. ToastUtil.showToast('暂无可复制歌词');
  10488. return;
  10489. }
  10490. this.lyricCopyLines = lines;
  10491. this.lyricSelectedIndexes = [];
  10492. this.isShowLyricCopySheet = true;
  10493. }
  10494. private toggleLyricLineSelection(index: number): void {
  10495. const selectedIndex = this.lyricSelectedIndexes.indexOf(index);
  10496. if (selectedIndex >= 0) {
  10497. const nextSelectedIndexes = [...this.lyricSelectedIndexes];
  10498. nextSelectedIndexes.splice(selectedIndex, 1);
  10499. this.lyricSelectedIndexes = nextSelectedIndexes;
  10500. return;
  10501. }
  10502. this.lyricSelectedIndexes = [...this.lyricSelectedIndexes, index];
  10503. }
  10504. private toggleLyricSelectAll(): void {
  10505. if (this.lyricSelectedIndexes.length === this.lyricCopyLines.length) {
  10506. this.lyricSelectedIndexes = [];
  10507. return;
  10508. }
  10509. this.lyricSelectedIndexes = this.lyricCopyLines.map((_: string, index: number) => index);
  10510. }
  10511. private copySelectedLyricLines(): void {
  10512. if (ArrayUtil.isEmpty(this.lyricSelectedIndexes)) {
  10513. ToastUtil.showToast('请先选择歌词');
  10514. return;
  10515. }
  10516. const selectedIndexes = [...this.lyricSelectedIndexes].sort((a: number, b: number) => a - b);
  10517. const selectedLines: string[] = [];
  10518. for (let i = 0; i < selectedIndexes.length; i++) {
  10519. const index = selectedIndexes[i];
  10520. if (index >= 0 && index < this.lyricCopyLines.length) {
  10521. selectedLines.push(this.lyricCopyLines[index]);
  10522. }
  10523. }
  10524. if (ArrayUtil.isEmpty(selectedLines)) {
  10525. ToastUtil.showToast('暂无可复制歌词');
  10526. return;
  10527. }
  10528. Utility.copyText(selectedLines.join('\n'));
  10529. ToastUtil.showToast(`已复制${selectedLines.length}行歌词`);
  10530. }
  10531. /**
  10532. * 从在线API获取歌词
  10533. */
  10534. private fetchOnlineLyric(lyricPath: string, isOnLineAndToast: boolean, isApi2?: boolean): void {
  10535. if (!this.currentSong) {
  10536. this.clearLyricControllers();
  10537. if (isOnLineAndToast) {
  10538. ToastUtil.showShort('未获取到歌词!');
  10539. }
  10540. return;
  10541. }
  10542. let artist = this.currentSong.artist || '';
  10543. if (isApi2 === undefined) {
  10544. isApi2 = false;
  10545. }
  10546. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  10547. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  10548. this.setLyricToControllers(res, lyricPath);
  10549. } else {
  10550. this.clearLyricControllers();
  10551. if (isOnLineAndToast) {
  10552. ToastUtil.showShort('未获取到歌词!');
  10553. }
  10554. }
  10555. });
  10556. }
  10557. //初始化悬浮歌词的自定义设置
  10558. initPipLyricSetting() {
  10559. this.lyricControllerXF
  10560. .setTextSize(this.currentLyricSize)
  10561. .setCacheSize(4)
  10562. .setTextColor("#DDDDDD")
  10563. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  10564. .setEmptyHint("")
  10565. .setAnimationDuration(1000)
  10566. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  10567. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  10568. this.setBlurDegree(this.blurDegreePip, true)
  10569. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  10570. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  10571. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  10572. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  10573. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  10574. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  10575. this.lyricControllerXF.setHightLightCenter(true)
  10576. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  10577. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  10578. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  10579. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  10580. if (this.pipBgIndex === 0) {
  10581. if (this.cover) {
  10582. this.pipBg = this.cover
  10583. } else {
  10584. this.pipBg = this.imageColor
  10585. }
  10586. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  10587. }
  10588. }
  10589. //根据item返回歌词内容
  10590. async getLyricContent(item: VideoItem): Promise<string> {
  10591. let neiqianLrc = ''
  10592. let lyContent = item?.lyricContent
  10593. if(lyContent&&StrUtil.isNotEmpty(lyContent)){
  10594. neiqianLrc = lyContent
  10595. return neiqianLrc
  10596. }
  10597. try {
  10598. //取数据库里面的歌词lyContent
  10599. const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
  10600. if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
  10601. console.log("onecold Lyrics:", lyricContent);
  10602. neiqianLrc = lyricContent
  10603. return neiqianLrc
  10604. }
  10605. } catch (error) {
  10606. console.error("Error fetching lyrics:", error);
  10607. }
  10608. try {
  10609. let filePath = item.filePath;
  10610. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  10611. let realLyricPath = lyricPath;
  10612. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  10613. const stat = await fileIo.stat(file.fd);
  10614. const arrayBuffer = new ArrayBuffer(stat.size);
  10615. const readLen = await fs.read(file.fd, arrayBuffer);
  10616. console.info("read file data succeed");
  10617. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  10618. if (buf.length === 0) {
  10619. throw new Error("Buffer is empty after reading the file");
  10620. }
  10621. // let detectedEncoding = chardet.detect(buf);
  10622. let detectedEncoding = this.detect(arrayBuffer)
  10623. console.info("Detected encoding: " + detectedEncoding);
  10624. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  10625. let fileContent = textDecoder.decode(buf);
  10626. console.info(`onecold The content of file1: ${fileContent}`);
  10627. fs.closeSync(file);
  10628. return fileContent;
  10629. } catch (error) {
  10630. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  10631. return '';
  10632. }
  10633. }
  10634. async saveDataToFile(content: string, filePath: string) {
  10635. if (StrUtil.isEmpty(filePath)) {
  10636. return
  10637. }
  10638. try {
  10639. let lyricContent = ''
  10640. lyricContent = content
  10641. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  10642. // 清空文件内容
  10643. await fileIo.truncate(file.fd, 0);
  10644. await fileIo.write(file.fd, lyricContent);
  10645. await fileIo.close(file);
  10646. console.log('onecold lyric file Data saved successfully.');
  10647. } catch (error) {
  10648. console.error('onecold lyric file Failed to save data:', error);
  10649. }
  10650. }
  10651. // 定义开始旋转的方法
  10652. // 使用动画系统优化旋转性能,避免 setInterval 频繁更新导致卡顿
  10653. @State timer: number = 0
  10654. @State rotateAngle: number = 0
  10655. @State isRotationRunning: boolean = false // 旋转动画是否正在运行
  10656. @StorageProp('isPageVisible') @Watch('onPageVisibilityChange') isPageVisible: boolean = true // 页面可见性标志
  10657. // 页面可见性变化回调
  10658. onPageVisibilityChange() {
  10659. // 当页面可见性改变时,重新启动/停止旋转动画
  10660. this.animationRoFun()
  10661. }
  10662. //封面旋转动画
  10663. animationRoFun() {
  10664. if (this.isPlaying && !this.isCoverRectangle && this.isPageVisible) {
  10665. // 启动旋转动画
  10666. if (!this.isRotationRunning) {
  10667. this.isRotationRunning = true
  10668. this.startContinuousRotation()
  10669. }
  10670. this.startRotation()
  10671. } else {
  10672. // 停止旋转动画
  10673. this.isRotationRunning = false
  10674. clearInterval(this.timer)
  10675. this.stopRotation()
  10676. }
  10677. }
  10678. // 使用持续的动画进行旋转,避免频繁状态更新
  10679. private startContinuousRotation() {
  10680. clearInterval(this.timer)
  10681. // 改为每 1000ms 更新 36 度(10秒一圈),减少更新频率
  10682. // 不使用 % 360 取模,让角度持续累加,避免反转
  10683. this.timer = setInterval(() => {
  10684. if (this.isRotationRunning) {
  10685. this.rotateAngle = this.rotateAngle + 36
  10686. }
  10687. }, 1000)
  10688. }
  10689. // 定义开始旋转的方法
  10690. startRotation() {
  10691. if (this.isPlaying) {
  10692. animateTo({
  10693. duration: 777,
  10694. iterations: 1,
  10695. curve: Curve.Linear
  10696. }, () => {
  10697. this.rotateAngle2 = -9
  10698. })
  10699. }
  10700. }
  10701. // 回调,暂停和播放按钮回调,下一首和上一首
  10702. playChange() {
  10703. // if(this.isCoverRectangle){
  10704. // return
  10705. // }
  10706. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  10707. this.setIsPlaying(true)
  10708. this.animationState = AnimationStatus.Running
  10709. } else {
  10710. this.setIsPlaying(false)
  10711. this.animationState = AnimationStatus.Paused
  10712. }
  10713. AppStorage.setOrCreate('animationState', this.animationState);
  10714. }
  10715. // 定义停止旋转的方法
  10716. stopRotation() {
  10717. if (this.isCoverRectangle) {
  10718. this.rotateAngle = 0
  10719. } else {
  10720. //唱针以左上角为点选择逆时针40度
  10721. animateTo({
  10722. duration: 1000,
  10723. curve: Curve.Linear,
  10724. iterations: 1,
  10725. }, () => {
  10726. this.rotateAngle2 = -45;
  10727. });
  10728. }
  10729. }
  10730. @Builder
  10731. private LyricsTopItem() {
  10732. Row() {
  10733. Stack({ alignContent: Alignment.Center }) {
  10734. Image( StrUtil.isNotEmpty(this.cover)?
  10735. this.cover:$r('app.media.alt'))
  10736. .height(58)
  10737. .width(58)
  10738. .clip(true)
  10739. .sourceSize({width:38, height:38})
  10740. .alt($r('app.media.alt'))
  10741. .borderRadius(8)
  10742. .clickEffect({ level: ClickEffectLevel.HEAVY })
  10743. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  10744. .shadow({
  10745. radius: 22,
  10746. type: ShadowType.BLUR,
  10747. color: 'on_primary'
  10748. })
  10749. }
  10750. .width(62)
  10751. .height('100%')
  10752. Column() {
  10753. Column() {
  10754. Text(this.name)
  10755. .fontSize(16)
  10756. .maxLines(1)
  10757. .fontWeight(FontWeight.Bolder)
  10758. .fontColor(Color.White)
  10759. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  10760. Row() {
  10761. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  10762. .fontSize(13)
  10763. .fontWeight(FontWeight.Bolder)
  10764. .padding({ top: 8 })
  10765. .fontColor(Color.White)
  10766. .margin({ left: this.currentLyricAlignMode === 0 ? 8 : 0 })
  10767. Blank()
  10768. }
  10769. }
  10770. .height('100%')
  10771. .width('100%')
  10772. .justifyContent(FlexAlign.Center)
  10773. .alignItems(HorizontalAlign.Start)
  10774. }
  10775. .height('100%')
  10776. .layoutWeight(1)
  10777. .margin({ right: 8 })
  10778. Column() {
  10779. PointLightDefaultButton({
  10780. isSysBol:false,
  10781. pointColor:Color.White,
  10782. imageResource:$r('app.media.lyric'),
  10783. isPx: false,
  10784. builderHeight: 23,
  10785. builderWidth: 23,
  10786. })
  10787. .onClick(() => {
  10788. this.isLyricSetting = !this.isLyricSetting;
  10789. })
  10790. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  10791. height: '99%',
  10792. dragBar: true,
  10793. preferType: SheetType.CENTER,
  10794. showClose: true,
  10795. blurStyle: BlurStyle.Thin,
  10796. backgroundColor: Color.Transparent,
  10797. title: { title: $r('app.string.lyric_setting') }
  10798. })
  10799. }
  10800. .width(44)
  10801. .height('100%')
  10802. .justifyContent(FlexAlign.Center)
  10803. .alignItems(HorizontalAlign.End)
  10804. }
  10805. .width(this.currentLyricAlignModePip === 1?'98%':'90%%')
  10806. .padding({ left: 25, right: 25 })
  10807. .height(58)
  10808. .alignItems(VerticalAlign.Center)
  10809. }
  10810. //歌词显示
  10811. @Builder
  10812. PlayerLyrics() {
  10813. Column() {
  10814. Column() {
  10815. this.LyricsTopItem()
  10816. }
  10817. .height(this.isPuraWP() ? 15 : 58)
  10818. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  10819. Visibility.None : Visibility.Visible)
  10820. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  10821. .width("100%")
  10822. Column() {
  10823. LyricView2({
  10824. controller: this.lyricController,
  10825. enableSeek: true,
  10826. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  10827. seekLineColor: "#80ffffff", // 滑动定位线颜色
  10828. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  10829. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  10830. if (!this.isPlaying) {
  10831. console.info('onecold startPlayOrResumePlay 7527')
  10832. this.startPlayOrResumePlay()
  10833. }
  10834. else {
  10835. this.isSeekTo = true;
  10836. this.mDestroyPage = false;
  10837. // 只有播放网盘歌曲时才显示转圈圈
  10838. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  10839. this.showLoadIng();
  10840. }
  10841. this.seekTo(position + "");
  10842. }
  10843. return true
  10844. }
  10845. })
  10846. .width("100%")
  10847. .layoutWeight(1)
  10848. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  10849. .gesture(LongPressGesture()
  10850. .onAction(() => {
  10851. this.openLyricCopySheet();
  10852. }))
  10853. .bindSheet($$this.isShowLyricCopySheet, this.LyricCopySheetBuilder(), {
  10854. height: '99%',
  10855. dragBar: true,
  10856. showClose: true,
  10857. preferType: SheetType.CENTER,
  10858. blurStyle: BlurStyle.Thin,
  10859. title: { title: '歌词' }
  10860. })
  10861. if (this.isPhoneLan()) {
  10862. Column() {
  10863. if (this.isShowSpectrum) {
  10864. this.InlineSpectrumView()
  10865. }
  10866. this.playProgressView()
  10867. }
  10868. .margin({ bottom: 32, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  10869. }
  10870. }
  10871. .position({
  10872. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  10873. (this.isPuraWP() ? 58 : 99)
  10874. })
  10875. .justifyContent(FlexAlign.Center)
  10876. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  10877. }
  10878. }
  10879. @Builder
  10880. LyricCopySheetBuilder() {
  10881. LyricCopySheet({
  10882. lyricCopyLines: this.lyricCopyLines,
  10883. lyricSelectedIndexes: this.lyricSelectedIndexes,
  10884. isDarkMode: this.isDarkMode,
  10885. themeColor: this.themeColor,
  10886. bottomSafeHeight: this.bottomSafeHeight,
  10887. onToggleLyricLine: (index: number) => {
  10888. this.toggleLyricLineSelection(index);
  10889. },
  10890. onToggleSelectAll: () => {
  10891. this.toggleLyricSelectAll();
  10892. },
  10893. onCopySelectedLines: () => {
  10894. this.copySelectedLyricLines();
  10895. }
  10896. })
  10897. }
  10898. @Builder
  10899. SingleLyricView() {
  10900. Column() {
  10901. Column() {
  10902. LyricView2({
  10903. controller: this.lyricControllerSingle,
  10904. enableSeek: false,
  10905. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  10906. seekLineColor: "#80ffffff", // 滑动定位线颜色
  10907. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  10908. })
  10909. .gesture(LongPressGesture()
  10910. .onAction(() => {
  10911. this.openLyricCopySheet();
  10912. }))
  10913. }
  10914. .height(82)
  10915. .margin({ bottom: 20 })
  10916. }
  10917. .opacity(this.playDragUiOpacity)
  10918. }
  10919. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  10920. @Builder
  10921. BottomControl() {
  10922. Column() {
  10923. if (this.isShowSpectrum) {
  10924. this.InlineSpectrumView()
  10925. }
  10926. this.TopPlayProgressView()
  10927. //播放 暂停,下一首,上一首
  10928. this.playCenterView()
  10929. if(!this.curDisplayIsHiCar){
  10930. //播放进度条
  10931. this.BottomView()
  10932. }
  10933. }
  10934. .justifyContent(FlexAlign.Center)
  10935. .alignItems(HorizontalAlign.Center)
  10936. .opacity(this.playDragUiOpacity)
  10937. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  10938. }
  10939. @Builder
  10940. playMenuBuilder(){
  10941. Image($r('app.media.menu'))
  10942. .width(24)
  10943. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  10944. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  10945. height: '99%',
  10946. preferType:SheetType.CENTER,
  10947. dragBar: true,
  10948. showClose: true,
  10949. blurStyle: BlurStyle.Thin,
  10950. title: { title: $r('app.string.more') },
  10951. backgroundColor: Color.Transparent,
  10952. })
  10953. }
  10954. //播放控制上一首 下一首 暂停和播放
  10955. @Builder
  10956. playCenterView(){
  10957. Row() {
  10958. PointLightButton({
  10959. builder: () => {
  10960. this.playMenuBuilder()
  10961. },
  10962. isPx: false,
  10963. builderHeight: 26,
  10964. builderWidth: 26,
  10965. })
  10966. .onClick(async () =>{
  10967. this.isShowMoreView = !this.isShowMoreView;
  10968. })
  10969. PointLightButton({
  10970. builder: () => {
  10971. this.playPreviousBuilder()
  10972. },
  10973. isPx: false,
  10974. builderHeight: 26,
  10975. builderWidth: 26,
  10976. })
  10977. .onClick(async () =>{
  10978. await this.playPrevious()
  10979. })
  10980. PointLightButton({
  10981. builder: () => {
  10982. this.PlayOrPauseButton()
  10983. },
  10984. isPx: false,
  10985. builderHeight: this.isPhoneLan()?38:42,
  10986. builderWidth: this.isPhoneLan()?38:42,
  10987. })
  10988. .onClick(() =>{
  10989. this.playOrPause()
  10990. })
  10991. PointLightButton({
  10992. builder: () => {
  10993. this.playNextBuilder()
  10994. },
  10995. isPx: false,
  10996. builderHeight: 26,
  10997. builderWidth: 26,
  10998. })
  10999. .onClick(async () =>{
  11000. await this.playNext()
  11001. })
  11002. this.playModeButton()
  11003. }
  11004. .width('95%')
  11005. .margin({ bottom:this.isCoverOpacity()?0:15 })
  11006. .justifyContent(FlexAlign.SpaceEvenly)
  11007. }
  11008. @Builder
  11009. playPreviousBuilder(){
  11010. Image($r('app.media.ic_previous'))
  11011. .width(32)
  11012. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  11013. .aspectRatio(CommonConstants.ASPECT_RATIO)
  11014. }
  11015. @Builder
  11016. playNextBuilder(){
  11017. Image($r('app.media.ic_next'))
  11018. .width(32)
  11019. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  11020. .aspectRatio(CommonConstants.ASPECT_RATIO)
  11021. }
  11022. @Builder
  11023. PlayOrPauseButton(){
  11024. Stack() {
  11025. Column() {
  11026. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  11027. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  11028. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  11029. .width(this.isPhoneLan()?38:42)
  11030. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  11031. .fillColor(Color.White)
  11032. .aspectRatio(CommonConstants.ASPECT_RATIO)
  11033. }
  11034. // 加载进度圈
  11035. if (this.isPlayerLoading) {
  11036. Progress({value:0,total:100,type:ProgressType.Ring })
  11037. .width(this.isPhoneLan()?40:44)
  11038. .height(this.isPhoneLan()?40:44)
  11039. .color(Color.White)
  11040. .style({ strokeWidth: 4, status: ProgressStatus.LOADING })
  11041. }
  11042. }
  11043. .width(this.isPhoneLan()?39:43)
  11044. .height(this.isPhoneLan()?39:43)
  11045. }
  11046. @Builder
  11047. TopPlayProgressView(){
  11048. Column() {
  11049. Row(){
  11050. Stack(){
  11051. SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
  11052. .fontColor([Color.White])
  11053. .fontSize(21)
  11054. .effectStrategy(1)
  11055. Text(this.fastForwardSeconds)
  11056. .fontColor(Color.White)
  11057. .fontSize(10)
  11058. .fontWeight(FontWeight.Bold)
  11059. }
  11060. .padding({left:12,bottom:6})
  11061. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  11062. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  11063. .onClick(()=>{
  11064. this.backForward()
  11065. })
  11066. Slider({
  11067. value: this.progressValue,
  11068. min: 0,
  11069. max: this.PROGRESS_MAX_VALUE,
  11070. step: 1,
  11071. style: SliderStyle.InSet
  11072. })
  11073. .height(20)
  11074. .blockColor('rgba(255,255,255,1)')
  11075. .trackColor('rgba(255,255,255,0.3)')
  11076. .selectedColor(Color.White)
  11077. .trackThickness(4)
  11078. .showSteps(false)
  11079. .showTips(true)
  11080. .layoutWeight(1)
  11081. .enabled(this.slideEnable)
  11082. .onChange((value: number, mode: SliderChangeMode) => {
  11083. if (mode !== 2) {
  11084. return
  11085. }
  11086. if(this.isSeekTo)
  11087. return
  11088. this.isSeekTo = true;
  11089. this.mDestroyPage = false;
  11090. // 只有播放网盘歌曲时才显示转圈圈
  11091. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  11092. this.showLoadIng();
  11093. }
  11094. let seekValue = value * (this.getActiveDuration() / 100);
  11095. console.info("onecold this.currentSong.type:"+this.currentSong?.type)
  11096. this.seekTo(seekValue + "");
  11097. })
  11098. Stack(){
  11099. SymbolGlyph($r('sys.symbol.arrow_clockwise'))
  11100. .fontColor([Color.White])
  11101. .fontSize(21)
  11102. .effectStrategy(1)
  11103. Text(this.fastForwardSeconds)
  11104. .fontColor(Color.White)
  11105. .fontSize(10)
  11106. .fontWeight(FontWeight.Bold)
  11107. }
  11108. .padding({right:10,bottom:6})
  11109. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  11110. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  11111. .onClick(()=>{
  11112. this.fastForward()
  11113. })
  11114. }
  11115. .justifyContent(FlexAlign.Center)
  11116. .padding({left:20,right:20})
  11117. .width(this.isLandscape?'88%':'95%')
  11118. Row() {
  11119. Text(this.currentTime)
  11120. .fontSize(10)
  11121. .fontColor(Color.White)
  11122. .margin({left:25})
  11123. Blank()
  11124. Text(this.totalTime)
  11125. .fontSize(10)
  11126. .fontColor(Color.White)
  11127. .margin({right:25})
  11128. }
  11129. .width(this.isLandscape?'85%':'90%')
  11130. .height(10)
  11131. }
  11132. .width('100%')
  11133. .alignItems(HorizontalAlign.Center)
  11134. }
  11135. @Builder
  11136. playModeButton(){
  11137. PointLightButton({
  11138. builder: () => {
  11139. this.playModeBuilder()
  11140. },
  11141. isPx: false,
  11142. builderHeight: 26,
  11143. builderWidth: 26,
  11144. })
  11145. .onClick(async () =>{
  11146. this.setLoopMode()
  11147. })
  11148. }
  11149. @Builder
  11150. playModeBuilder(){
  11151. Column() {
  11152. if (this.playType === 0) {
  11153. Image($r('app.media.loop'))
  11154. .width(24)
  11155. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  11156. .aspectRatio(CommonConstants.ASPECT_RATIO)
  11157. } else if (this.playType === 1) {
  11158. Image($r('app.media.single'))
  11159. .width(24)
  11160. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  11161. .aspectRatio(CommonConstants.ASPECT_RATIO)
  11162. } else if (this.playType === 2) {
  11163. Image($r('app.media.normal_play'))
  11164. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  11165. .width(24)
  11166. .aspectRatio(CommonConstants.ASPECT_RATIO)
  11167. } else if (this.playType === 3) {
  11168. Image($r('app.media.random'))
  11169. .width(24)
  11170. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  11171. .aspectRatio(CommonConstants.ASPECT_RATIO)
  11172. } else if (this.playType === 4) {
  11173. Image($r('app.media.noloop'))
  11174. .width(24)
  11175. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  11176. .aspectRatio(CommonConstants.ASPECT_RATIO)
  11177. }
  11178. }
  11179. }
  11180. //播放进度条
  11181. @Builder
  11182. BottomView(){
  11183. Row() {
  11184. PointLightDefaultButton({
  11185. isSysBol:true,
  11186. pointColor:Color.White,
  11187. imageResource:$r('sys.symbol.rectangle_portrait_rotate'),
  11188. isPx: false,
  11189. builderHeight: 22,
  11190. builderWidth: 22,
  11191. })
  11192. .onClick(async () =>{
  11193. if (this.isLandscape) {
  11194. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  11195. } else {
  11196. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  11197. }
  11198. })
  11199. if(this.currentSong){
  11200. PointLightDefaultButton({
  11201. isSysBol:true,
  11202. pointColor:Color.White,
  11203. imageResource:$r('sys.symbol.rename'),
  11204. isPx: false,
  11205. builderHeight: 22,
  11206. builderWidth: 22,
  11207. })
  11208. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  11209. height: '99%',
  11210. dragBar: true,
  11211. showClose: true,
  11212. preferType: SheetType.BOTTOM,
  11213. title: { title: '编辑标签' }
  11214. })
  11215. .onClick(async () => {
  11216. this.initEditFields(this.currentSong)
  11217. this.tempLyricContent = this.lyricContent
  11218. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  11219. this.lyricConStr = this.tempLyricContent
  11220. }
  11221. this.isShowEdit = !this.isShowEdit;
  11222. })
  11223. }
  11224. PointLightDefaultButton({
  11225. isSysBol:true,
  11226. pointColor:Color.White,
  11227. imageResource:$r('sys.symbol.slider_vertical_3'),
  11228. isPx: false,
  11229. builderHeight: 22,
  11230. builderWidth: 22,
  11231. })
  11232. .onClick(async () => {
  11233. this.isEqualizerSheet = !this.isEqualizerSheet;
  11234. })
  11235. PointLightDefaultButton({
  11236. isSysBol:true,
  11237. pointColor:Color.White,
  11238. imageResource:Utility.getIsFav(this.favList,this.currentSong)?
  11239. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'),
  11240. isPx: false,
  11241. builderHeight: 22,
  11242. builderWidth: 22,
  11243. })
  11244. .onClick(async () => {
  11245. if(this.currentSong){
  11246. this.doFav(this.currentSong)
  11247. }
  11248. })
  11249. this.playListBuilder()
  11250. }
  11251. .width(this.isLandscape?'88%':'95%')
  11252. .justifyContent(FlexAlign.SpaceAround)
  11253. .visibility(this.showSimple?Visibility.None:Visibility.Visible)
  11254. .height(30)
  11255. .animation({
  11256. duration: 666,
  11257. curve: 'ease-in-out' // 可选动画曲线
  11258. })
  11259. }
  11260. @Builder
  11261. fullButton(){
  11262. Column() {
  11263. Image($r('app.media.full_4'))
  11264. .width(25)
  11265. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  11266. .aspectRatio(CommonConstants.ASPECT_RATIO)
  11267. }
  11268. }
  11269. @Builder
  11270. playListBuilder(){
  11271. PointLightDefaultButton({
  11272. isSysBol:true,
  11273. pointColor:Color.White,
  11274. imageResource:$r('sys.symbol.music_note_list'),
  11275. isPx: false,
  11276. builderHeight: 26,
  11277. builderWidth: 26,
  11278. })
  11279. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  11280. height: '95%',
  11281. dragBar: true,
  11282. showClose: true,
  11283. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11284. blurStyle: BlurStyle.Thin,
  11285. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  11286. title: {
  11287. title:this.getPlayListDisplayCount()==0?Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  11288. :Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  11289. + `(${this.getPlayListDisplayCount()}首)`
  11290. }
  11291. })
  11292. .onClick(() => {
  11293. this.isShowSheetView = !this.isShowSheetView;
  11294. if(this.isPlayListBgGrass){
  11295. this.isFrontWhite = true
  11296. }else{
  11297. this.isFrontWhite = false
  11298. }
  11299. this.scrollIndex()
  11300. // 只有在播放本地音乐时才自动加载完整列表
  11301. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_LOCAL) {
  11302. void this.hydrateFullMediaPlayListIfNeeded();
  11303. }
  11304. })
  11305. }
  11306. //旧版本播放进度条(现在是手机横屏的播放条)
  11307. @Builder
  11308. playProgressView() {
  11309. Row() {
  11310. Column(){
  11311. PointLightDefaultButton({
  11312. isSysBol:true,
  11313. pointColor:Color.White,
  11314. imageResource:$r('sys.symbol.rectangle_portrait_rotate'),
  11315. isPx: false,
  11316. builderHeight: 26,
  11317. builderWidth: 26,
  11318. })
  11319. .onClick(async () =>{
  11320. if (this.isLandscape) {
  11321. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  11322. } else {
  11323. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  11324. }
  11325. })
  11326. }
  11327. .margin({ right: 10,bottom:6})
  11328. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  11329. .animation({
  11330. duration: 666,
  11331. curve: 'ease-in-out' // 可选动画曲线
  11332. })
  11333. Text(this.currentTime)
  11334. .fontSize($r('app.float.slider_font_size'))
  11335. .fontColor(Color.White)
  11336. .margin(3)
  11337. Slider({
  11338. value: this.progressValue,
  11339. min: 0,
  11340. max: this.PROGRESS_MAX_VALUE,
  11341. step: 1,
  11342. style: SliderStyle.InSet
  11343. })
  11344. .width('600px')
  11345. .blockColor('rgba(255,255,255,1)')
  11346. .trackColor('rgba(255,255,255,0.3)')
  11347. .selectedColor(Color.White)
  11348. .trackThickness(5)
  11349. .layoutWeight(1)
  11350. .margin({top:4, left: PlayConstants.PROGRESS_MARGIN_LEFT })
  11351. .showSteps(false)
  11352. .showTips(true)
  11353. .enabled(this.slideEnable)
  11354. .onChange((value: number, mode: SliderChangeMode) => {
  11355. if (mode !== 2) {
  11356. return
  11357. }
  11358. this.isSeekTo = true;
  11359. this.mDestroyPage = false;
  11360. // 只有播放网盘歌曲时才显示转圈圈
  11361. console.info("onecold this.currentSong.type:"+this.currentSong?.type)
  11362. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  11363. console.info("onecold 开始转圈圈")
  11364. this.showLoadIng();
  11365. }
  11366. let seekValue = value * (this.getActiveDuration() / 100);
  11367. this.seekTo(seekValue + "");
  11368. })
  11369. Text(this.totalTime)
  11370. .fontSize($r('app.float.slider_font_size'))
  11371. .fontColor(Color.White)
  11372. .margin(3)
  11373. //播放列表
  11374. Column(){
  11375. this.playListBuilder()
  11376. }
  11377. .margin({ left: 10,bottom:6})
  11378. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  11379. .animation({
  11380. duration: 666,
  11381. curve: 'ease-in-out' // 可选动画曲线
  11382. })
  11383. }
  11384. //x5的竖屏模式需要99%
  11385. .width(this.isPhonePortrait() ? '93.4%'
  11386. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  11387. .height(this.isPhoneLan() ? 25 : 33)
  11388. .alignItems(VerticalAlign.Bottom)
  11389. .animation({
  11390. duration: 666,
  11391. curve: 'ease-in-out' // 可选动画曲线
  11392. })
  11393. }
  11394. isBigScreen() {
  11395. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  11396. return true
  11397. }
  11398. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  11399. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  11400. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  11401. return false
  11402. } else {
  11403. return true
  11404. }
  11405. return false
  11406. }
  11407. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  11408. // 添加控制缩放的状态变量
  11409. @State scaleValueImage: number = 1
  11410. @State scaleValueText: number = 1
  11411. @State playDragUiOpacity: number = 1
  11412. @Builder
  11413. CoverInfo() {
  11414. Column() {
  11415. Stack() {
  11416. Column() {
  11417. //方形封面布局
  11418. if (this.isCoverRectangle) {
  11419. this.RectangleCoverView()
  11420. } else {
  11421. //圆形封面布局
  11422. this.CicleCoverView()
  11423. }
  11424. this.musicNameInfo(false)
  11425. if (this.isPhoneLan()) {
  11426. Text(this.name)
  11427. .fontSize(18)
  11428. .fontWeight(FontWeight.Bold)
  11429. .margin({ top: 13 })
  11430. .textOverflow({ overflow: TextOverflow.Ellipsis })
  11431. .maxLines(1)
  11432. .width('99%')
  11433. .textAlign(TextAlign.Center)
  11434. .fontColor(Color.White)
  11435. }
  11436. }
  11437. .width('100%')
  11438. Column({ space: 8 }) {
  11439. Text(this.name)
  11440. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  11441. .fontWeight(FontWeight.Bold)
  11442. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  11443. .maxLines(1)
  11444. .width('85%')
  11445. .textAlign(TextAlign.Center)
  11446. .fontColor(Color.White)
  11447. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  11448. Text(this.artist)
  11449. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  11450. .fontColor(Color.White)
  11451. .fontWeight(FontWeight.Bold)
  11452. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  11453. }
  11454. .justifyContent(FlexAlign.Start)
  11455. .zIndex(1)
  11456. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  11457. }
  11458. .margin({
  11459. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  11460. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  11461. top: this.isCoverOpacity() ? 0 : 20
  11462. })
  11463. if (this.isShowSingleLineLyric&&this.isPhonePortrait()) {
  11464. this.SingleLyricView()
  11465. }
  11466. if (this.isPhoneLan()) {
  11467. Column() {
  11468. this.playCenterView()
  11469. }
  11470. .position({ left: 28, bottom: 35 })
  11471. } else {
  11472. this.BottomControl()
  11473. }
  11474. }
  11475. .width(CommonConstants.FULL_PERCENT)
  11476. .clip(true)
  11477. }
  11478. //方形封面布局
  11479. @Builder
  11480. RectangleCoverView(){
  11481. Stack({alignContent:Alignment.Center}){
  11482. Image( StrUtil.isNotEmpty(this.cover)?
  11483. this.cover:$r('app.media.alt'))
  11484. .height(this.isHiCar()?(px2vp(this.windowHeight)*0.4):
  11485. this.isCoverOpacity()?(px2vp(this.windowHeight)*0.54):'auto')
  11486. .width(this.isHiCar()||this.isCoverOpacity()?'auto':this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '88%')
  11487. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  11488. .alt($r('app.media.alt'))
  11489. .margin({ right: 8, left: 8, top: 5 })
  11490. .aspectRatio(1)
  11491. .geometryTransition('cover') // 绑定标识符
  11492. .opacity(this.opacityValueImage)
  11493. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  11494. .bindContextMenu(this.MenuImageBuilder(this.cover), ResponseType.LongPress,
  11495. {
  11496. preview: MenuPreviewMode.IMAGE,
  11497. previewAnimationOptions: { scale: [0.8, 1.0] },
  11498. })
  11499. .bindContextMenu(this.MenuImageBuilder(this.cover), ResponseType.RightClick,
  11500. {
  11501. preview: MenuPreviewMode.IMAGE,
  11502. previewAnimationOptions: { scale: [0.8, 1.0] },
  11503. })
  11504. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  11505. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  11506. .clip(true)
  11507. .rotate({
  11508. x: 0,
  11509. y: 0,
  11510. z: 1,
  11511. angle: this.rotateAngle
  11512. })
  11513. .animation({
  11514. duration: 1000, // 与 setInterval 同步
  11515. curve: Curve.Linear,
  11516. iterations: 1
  11517. })
  11518. .shadow({
  11519. radius: 22,
  11520. type: ShadowType.BLUR,
  11521. color: 'on_primary'
  11522. })
  11523. .onClick(() => {
  11524. this.isMusicBGCover = !this.isMusicBGCover
  11525. })
  11526. }
  11527. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  11528. // 设置左下角为缩放中心点
  11529. centerX: '0%',
  11530. centerY: '50%' })
  11531. }
  11532. @Builder
  11533. CicleCoverView() {
  11534. //圆形封面布局
  11535. Stack({alignContent:Alignment.Center}) {
  11536. Image($r('app.media.ic_music_disc'))
  11537. .width(245)
  11538. .height(245)
  11539. .margin({ right: 20, left: 20 ,top:this.isLandscape?0:50 })
  11540. .aspectRatio(1)
  11541. .opacity(this.isCoverOpacity() ? 0 : 1)
  11542. .visibility(this.isCoverOpacity() ? Visibility.None : Visibility.Visible)
  11543. .borderRadius('100%')
  11544. .align(Alignment.Center)
  11545. .clip(true)
  11546. .rotate({
  11547. angle: this.rotateAngle,
  11548. centerX: "50%",
  11549. centerY: "50%",
  11550. })
  11551. .animation({
  11552. duration: 1000, // 改为 1000ms 与 setInterval 同步
  11553. curve: Curve.Linear,
  11554. iterations: 1 // 只执行一次,下一次更新会触发新的动画
  11555. })
  11556. .shadow({
  11557. radius: 22,
  11558. type: ShadowType.BLUR,
  11559. color: 'on_primary'
  11560. })
  11561. Image( StrUtil.isNotEmpty(this.cover)?
  11562. this.cover:$r('app.media.alt'))
  11563. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
  11564. (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 168))
  11565. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  11566. .alt($r('app.media.alt'))
  11567. .margin({ right: 20, left: 20,
  11568. top:this.isCoverRectangle||this.isLandscape?0:50})
  11569. .aspectRatio(1)
  11570. .opacity(this.opacityValueImage)
  11571. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  11572. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  11573. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  11574. .align(Alignment.Center)//
  11575. .clip(true)
  11576. .shadow({
  11577. radius: 22,
  11578. type: ShadowType.BLUR,
  11579. color: 'on_primary'
  11580. })
  11581. .rotate({
  11582. x: 0,
  11583. y: 0,
  11584. z: 1,
  11585. angle: this.rotateAngle
  11586. })
  11587. .animation({
  11588. duration: 1000, // 与 setInterval 同步
  11589. curve: Curve.Linear,
  11590. iterations: 1
  11591. })
  11592. .onClick(() => {
  11593. this.isMusicBGCover = !this.isMusicBGCover
  11594. })
  11595. // 唱针以左上角为点选择逆时针40度
  11596. Image($r('app.media.ic_music_cover_hand'))
  11597. .height(130)
  11598. .margin({ bottom: 200, top: 0 })
  11599. // .position({ x: this.windowWidth/2, y: 0 })
  11600. .align(Alignment.Top)
  11601. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  11602. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  11603. .visibility(this.isHiCar()||this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  11604. }
  11605. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  11606. // 设置左下角为缩放中心点
  11607. centerX: '0%',
  11608. centerY: '100%' })
  11609. }
  11610. @Builder
  11611. MenuImageBuilder(cover: string|undefined) {
  11612. Menu(){
  11613. MenuItem({
  11614. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.picture_2')),
  11615. content: '查看封面'
  11616. })
  11617. .onClick(async() => {
  11618. if (StrUtil.isEmpty(cover)) {
  11619. ToastUtil.showToast('当前没有可用封面')
  11620. return;
  11621. }
  11622. this.getUIContext().getRouter().pushUrl({
  11623. url: 'pages/WallpaperPreviewPage',
  11624. params: {
  11625. imageUri: cover
  11626. }
  11627. })
  11628. })
  11629. MenuItem({
  11630. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.picture')),
  11631. content: '更换封面'
  11632. })
  11633. .onClick(async() => {
  11634. await this.replaceCurrentSongCoverByAlbum();
  11635. })
  11636. }
  11637. }
  11638. @Builder
  11639. private musicNameInfo(isHidden: boolean) {
  11640. Row(){
  11641. Column({ space: 8 }) {
  11642. Text(this.name)
  11643. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 20)
  11644. .fontWeight(FontWeight.Bold)
  11645. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  11646. .maxLines(1)
  11647. .width('99%')
  11648. .textAlign(TextAlign.Start)
  11649. .fontColor(Color.White)
  11650. Text(this.artist + ' ' + this.currentSong?.album)
  11651. .fontSize(this.isCoverOpacity() ? 12 : 15)
  11652. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  11653. .fontColor(Color.White)
  11654. .textAlign(TextAlign.Start)
  11655. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  11656. .width('99%')
  11657. .maxLines(1)
  11658. }
  11659. .zIndex(1)
  11660. .layoutWeight(1)
  11661. .margin({ left: 15 })
  11662. Blank()
  11663. Row(){
  11664. PointLightDefaultButton({
  11665. isSysBol:true,
  11666. pointColor:Color.White,
  11667. imageResource:this.showSimple?
  11668. $r('sys.symbol.sun_max'):$r('sys.symbol.moon'),
  11669. isPx: false,
  11670. builderHeight: 26,
  11671. builderWidth: 26,
  11672. })
  11673. .onClick(async () => {
  11674. this.showSimple = !this.showSimple
  11675. PreferencesUtil.put('showSimple', this.showSimple)
  11676. })
  11677. }
  11678. .margin({ left: 8,right:8 })
  11679. }
  11680. .width(this.isLandscape?'83%':'90%')
  11681. .scale({ x: this.scaleValueText, y: this.scaleValueText }) // 添加缩放效果
  11682. .opacity(this.playDragUiOpacity)
  11683. .margin({ top:this.isCoverRectangle?10: 0 })
  11684. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  11685. }
  11686. @Builder
  11687. private PlayTitle() {
  11688. Row() {
  11689. Row() {
  11690. Image($r('app.media.ic_back_down'))
  11691. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  11692. .hitTestBehavior(HitTestMode.Transparent)
  11693. }
  11694. .layoutWeight(1)
  11695. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11696. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  11697. .onClick(() => {
  11698. this.setShowPlayFalse()
  11699. })
  11700. Column() {
  11701. AVCastPicker({
  11702. normalColor: Color.White,
  11703. onStateChange: this.onStateVastChange
  11704. })
  11705. .width(24)
  11706. .height(24)
  11707. }
  11708. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  11709. }
  11710. .width(PlayConstants.ROW_WIDTH)
  11711. }
  11712. @Builder
  11713. lyricSettingSheet(isPip: boolean) {
  11714. Scroll() {
  11715. this.lyricSetting(isPip)
  11716. }
  11717. .width('100%')
  11718. .height('100%')
  11719. }
  11720. @Builder
  11721. lyricSetting(isPip: boolean) {
  11722. Column() {
  11723. // 时间调节模块
  11724. if (!isPip) {
  11725. this.BuildTimeControls()
  11726. }
  11727. // 字号控制模块
  11728. this.BuildFontControls(isPip)
  11729. }
  11730. }
  11731. // 歌词时间偏移状态
  11732. @State timeOffset: number = 0.0
  11733. @State currentLyricColor: string = '#FFFFFF'
  11734. @State currentLyricColorPip: string = '#FFFFFF'
  11735. @State currentHighLightLyricColor: string = '#FF4081'
  11736. @State currentHighLightLyricColorPip: string = '#FF4081'
  11737. // 歌词字号状态
  11738. @State currentLyricSize: number = 20
  11739. @State currentLyricSizePip: number = 20
  11740. // 高亮歌词放大倍数
  11741. @State currentHightLyricSize: number = 1.2
  11742. @State currentHightLyricSizePip: number = 1.2
  11743. @State currentLyricLineSpace: number = 10
  11744. @State currentLyricLineSpacePip: number = 10
  11745. @State currentLyricAlignMode: number = 1
  11746. @State currentLyricAlignModePip: number = 1
  11747. @State blurDegree: number = 2
  11748. @State blurDegreePip: number = 2
  11749. @State isShowSelectColor: boolean = false
  11750. @State isShowHLSelectColor: boolean = false
  11751. @State isShowPipBgSelectColor: boolean = false
  11752. @State pipLyWidth: number = 330
  11753. @State pipLyHeight: number = 120
  11754. // 构建颜色选择器
  11755. @Builder
  11756. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  11757. Row({ space: 10 }) {
  11758. HSBColorPicker({
  11759. color: '#FFFFFF',
  11760. radius: 8,
  11761. layout: HSBColorPickerLayout.COLUMN,
  11762. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  11763. '#fa7105'],
  11764. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  11765. this.changeLyricColor(value, isPip, isBGPip)
  11766. })
  11767. .height(250)
  11768. .layoutWeight(1)
  11769. .padding(25)
  11770. }
  11771. .width('66%')
  11772. }
  11773. @State isOpenPip: boolean = false
  11774. @State pipBgIndex: number = 0
  11775. // 构建字号控制器
  11776. @Builder
  11777. BuildFontControls(isPip: boolean) {
  11778. Column() {
  11779. if (isPip) {
  11780. Column() {
  11781. Row() {
  11782. Text('悬浮歌词')
  11783. .margin({ left: 18 })
  11784. .fontSize(15)
  11785. .fontColor(Color.White)
  11786. .fontWeight(480)
  11787. .layoutWeight(1)
  11788. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  11789. .selectedColor(this.themeColor)
  11790. .switchPointColor(Color.White)
  11791. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11792. .margin({ right: 18 })
  11793. .onChange((checked: boolean) => {
  11794. this.isOpenPip = checked;
  11795. if (this.isOpenPip) {
  11796. this.startPip()
  11797. } else {
  11798. this.stopPip()
  11799. }
  11800. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  11801. })
  11802. .width(50)
  11803. .height(30);
  11804. }
  11805. .height(55)
  11806. }
  11807. .backgroundColor(Color.Transparent)
  11808. .borderRadius(15)
  11809. .margin({
  11810. left: 30,
  11811. right: 30,
  11812. top: 0,
  11813. bottom: 20
  11814. })
  11815. .padding(0)
  11816. .border({
  11817. color: Color.White,
  11818. width: 1.8
  11819. })
  11820. }else{
  11821. Column() {
  11822. Row() {
  11823. Text('显示迷你歌词')
  11824. .margin({ left: 18 })
  11825. .fontSize(15)
  11826. .fontColor(Color.White)
  11827. .fontWeight(480)
  11828. .layoutWeight(1)
  11829. Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
  11830. .selectedColor(this.themeColor)
  11831. .switchPointColor(Color.White)
  11832. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11833. .margin({ right: 18 })
  11834. .onChange((checked: boolean) => {
  11835. this.isShowSingleLineLyric = checked;
  11836. PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
  11837. })
  11838. .width(50)
  11839. .height(30);
  11840. }
  11841. .height(55)
  11842. }
  11843. .backgroundColor(Color.Transparent)
  11844. .borderRadius(15)
  11845. .margin({
  11846. left: 30,
  11847. right: 30,
  11848. top: 10,
  11849. bottom: 10
  11850. })
  11851. .padding(0)
  11852. .border({
  11853. color: Color.White,
  11854. width: 1.8
  11855. })
  11856. }
  11857. if (!isPip) {
  11858. Row() {
  11859. Text(`逐字歌词:`)
  11860. .fontSize(14)
  11861. .fontColor(Color.White)
  11862. Column() {
  11863. Toggle({ type: ToggleType.Switch, isOn: this.isEnableWordByWordLyric })
  11864. .selectedColor(this.themeColor)
  11865. .switchPointColor(Color.White)
  11866. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11867. .onChange((checked: boolean) => {
  11868. this.isEnableWordByWordLyric = checked;
  11869. PreferencesUtil.putSync(SettingPage.IS_ENABLE_WORD_BY_WORD_LYRIC, this.isEnableWordByWordLyric)
  11870. this.syncWordByWordLyricMode()
  11871. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  11872. })
  11873. .width(50)
  11874. .height(30)
  11875. .alignSelf(ItemAlign.Start)
  11876. .margin({ left: 12 })
  11877. Blank()
  11878. }
  11879. .width('76%')
  11880. }
  11881. .margin({
  11882. left: 20,
  11883. right: 15,
  11884. top: 10,
  11885. bottom: 10
  11886. })
  11887. }
  11888. Row() {
  11889. Text(`歌词居中:`)
  11890. .fontSize(14)
  11891. .fontColor(Color.White)
  11892. .margin({ left: 2 })
  11893. Row() {
  11894. ForEach(['居中', '居左'], (size: string, index: number) => {
  11895. Button(size)
  11896. .width(60)
  11897. .height(28)
  11898. .fontSize(12)
  11899. .fontColor('#FFFFFF')
  11900. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  11901. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  11902. .border({
  11903. color: (!isPip && this.currentLyricAlignMode === index) ||
  11904. (isPip && this.currentLyricAlignModePip === index) ?
  11905. '#007DFF' : '#DDDDDD',
  11906. width: 1.8
  11907. })
  11908. .onClick(() => {
  11909. this.setLyricAlignMode(index, isPip)
  11910. })
  11911. .margin({ left: 10, right: 8 })
  11912. })
  11913. }
  11914. .width('76%')
  11915. Blank()
  11916. }
  11917. .margin({
  11918. top: 10,
  11919. bottom: 10,
  11920. right: 20,
  11921. left: 20
  11922. })
  11923. if (isPip) {
  11924. Row() {
  11925. Text(`悬浮背景:`)
  11926. .fontSize(14)
  11927. .fontColor(Color.White)
  11928. Select([
  11929. { value: CommonConstants.PIP_LYRIC_BG[0] },
  11930. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  11931. .font({ size: 13, weight: FontWeight.Medium })
  11932. .fontColor(Color.White)
  11933. .margin({ left: 10 })
  11934. .selected(this.pipBgIndex)
  11935. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  11936. .onSelect(async (_index: number, text?: string | undefined) => {
  11937. this.pipBgIndex = _index
  11938. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  11939. if (this.pipBgIndex === 0) {
  11940. if (this.cover) {
  11941. this.pipBg = this.cover
  11942. } else {
  11943. this.pipBg = this.imageColor
  11944. }
  11945. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  11946. } else {
  11947. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  11948. }
  11949. })
  11950. Column() {
  11951. }
  11952. .backgroundColor(this.pipBg)
  11953. .margin({ left: 10, right: 10 })
  11954. .borderRadius(20)
  11955. .height(28)
  11956. .width(28)
  11957. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  11958. Row() {
  11959. SymbolGlyph($r('sys.symbol.paintbrush'))
  11960. .fontColor([Color.White])
  11961. .effectStrategy(1)
  11962. Text(`选择颜色`)
  11963. .fontSize(13)
  11964. .margin({ left: 10 })
  11965. .fontColor(Color.White)
  11966. }
  11967. }
  11968. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  11969. .backgroundColor(Color.Transparent)
  11970. .border({
  11971. color: '#FFFFFF',
  11972. radius: 20,
  11973. width: 1.8
  11974. })
  11975. .height(36)
  11976. .width(110)
  11977. .onClick(() => {
  11978. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  11979. })
  11980. .bindPopup(this.isShowPipBgSelectColor, {
  11981. builder: this.SelectColor(false, isPip, true),
  11982. placement: Placement.Top,
  11983. mask: { color: '#33000000' },
  11984. enableArrow: false, //是否显示箭头
  11985. showInSubWindow: false,
  11986. onStateChange: (e) => {
  11987. if (!e.isVisible) {
  11988. this.isShowPipBgSelectColor = false
  11989. }
  11990. }
  11991. })
  11992. }
  11993. .width('76%')
  11994. .margin({ bottom: 5, right: 45, left: 20 })
  11995. }
  11996. if (!isPip) {
  11997. Row() {
  11998. Text(`高亮居中:`)
  11999. .fontSize(14)
  12000. .fontColor(Color.White)
  12001. Column() {
  12002. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  12003. .selectedColor(this.themeColor)
  12004. .switchPointColor(Color.White)
  12005. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  12006. .onChange((checked: boolean) => {
  12007. this.isHightLightCenter = checked;
  12008. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  12009. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  12010. })
  12011. .width(50)
  12012. .height(30)
  12013. .alignSelf(ItemAlign.Start)
  12014. .margin({ left: 12 })
  12015. Blank()
  12016. }
  12017. .width('76%')
  12018. }
  12019. .margin({
  12020. left: 20,
  12021. right: 15,
  12022. top: 10,
  12023. bottom: 10
  12024. })
  12025. }
  12026. Row() {
  12027. Text(`歌词颜色:`)
  12028. .fontSize(14)
  12029. .fontColor(Color.White)
  12030. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  12031. .fontSize(15)
  12032. .fontColor(Color.White)
  12033. .margin({ left: 12, right: 12 })
  12034. Column() {
  12035. }
  12036. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  12037. .margin({ right: 12 })
  12038. .borderRadius(20)
  12039. .height(28)
  12040. .width(28)
  12041. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  12042. Row() {
  12043. SymbolGlyph($r('sys.symbol.paintbrush'))
  12044. .fontColor([Color.White])
  12045. .effectStrategy(1)
  12046. Text(`选择颜色`)
  12047. .fontSize(13)
  12048. .margin({ left: 10 })
  12049. .fontColor(Color.White)
  12050. }
  12051. }
  12052. .backgroundColor(Color.Transparent)
  12053. .border({
  12054. color: '#FFFFFF',
  12055. radius: 20,
  12056. width: 1.8
  12057. })
  12058. .height(36)
  12059. .width(110)
  12060. .onClick(() => {
  12061. this.isShowSelectColor = !this.isShowSelectColor
  12062. })
  12063. .bindPopup(this.isShowSelectColor, {
  12064. builder: this.SelectColor(false, isPip),
  12065. placement: Placement.Top,
  12066. mask: { color: '#33000000' },
  12067. enableArrow: false, //是否显示箭头
  12068. showInSubWindow: false,
  12069. onStateChange: (e) => {
  12070. if (!e.isVisible) {
  12071. this.isShowSelectColor = false
  12072. }
  12073. }
  12074. })
  12075. }
  12076. .width('76%')
  12077. .margin({
  12078. top: 10,
  12079. bottom: 10,
  12080. right: 45,
  12081. left: 20
  12082. })
  12083. Row() {
  12084. Text(`高亮颜色:`)
  12085. .fontSize(14)
  12086. .fontColor(Color.White)
  12087. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  12088. .fontSize(15)
  12089. .fontColor(Color.White)
  12090. .margin({ left: 12, right: 12 })
  12091. Column() {
  12092. }
  12093. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  12094. .margin({ right: 12 })
  12095. .borderRadius(20)
  12096. .height(28)
  12097. .width(28)
  12098. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  12099. Row() {
  12100. SymbolGlyph($r('sys.symbol.paintbrush'))
  12101. .fontColor([Color.White])
  12102. .effectStrategy(1)
  12103. Text(`选择颜色`)
  12104. .fontSize(13)
  12105. .margin({ left: 10 })
  12106. .fontColor(Color.White)
  12107. }
  12108. }
  12109. .backgroundColor(Color.Transparent)
  12110. .border({
  12111. color: '#FFFFFF',
  12112. radius: 20,
  12113. width: 1.8
  12114. })
  12115. .height(36)
  12116. .width(110)
  12117. .onClick(() => {
  12118. this.isShowHLSelectColor = !this.isShowHLSelectColor
  12119. })
  12120. .bindPopup(this.isShowHLSelectColor, {
  12121. builder: this.SelectColor(true, isPip),
  12122. placement: Placement.Top,
  12123. mask: { color: '#33000000' },
  12124. enableArrow: false, //是否显示箭头
  12125. showInSubWindow: false,
  12126. onStateChange: (e) => {
  12127. if (!e.isVisible) {
  12128. this.isShowHLSelectColor = false
  12129. }
  12130. }
  12131. })
  12132. }
  12133. .width('76%')
  12134. .margin({
  12135. top: 10,
  12136. bottom: 10,
  12137. right: 45,
  12138. left: 20
  12139. })
  12140. if (isPip) {
  12141. Row() {
  12142. Text(`显示宽度:`)
  12143. .fontSize(14)
  12144. .fontColor(Color.White)
  12145. Slider({
  12146. value: this.pipLyWidth,
  12147. min: 10,
  12148. max: 800,
  12149. step: 1,
  12150. style: SliderStyle.OutSet
  12151. })
  12152. .blockColor(this.themeColor)
  12153. .trackColor($r('app.color.speed_text_color'))
  12154. .selectedColor(Color.White)
  12155. .trackThickness(6)
  12156. .onChange((value: number) => {
  12157. this.pipLyWidth = value
  12158. if (this.pipController) {
  12159. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  12160. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  12161. }
  12162. })
  12163. .width('76%')
  12164. }
  12165. .margin({
  12166. left: 20,
  12167. right: 15,
  12168. top: 5,
  12169. bottom: 5
  12170. })
  12171. Row() {
  12172. Text(`显示高度:`)
  12173. .fontSize(14)
  12174. .fontColor(Color.White)
  12175. Slider({
  12176. value: this.pipLyHeight,
  12177. min: 10,
  12178. max: 1000,
  12179. step: 1,
  12180. style: SliderStyle.OutSet
  12181. })
  12182. .blockColor(this.themeColor)
  12183. .trackColor($r('app.color.speed_text_color'))
  12184. .selectedColor(Color.White)
  12185. .trackThickness(6)
  12186. .onChange((value: number) => {
  12187. this.pipLyHeight = value
  12188. if (this.pipController) {
  12189. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  12190. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  12191. }
  12192. })
  12193. .width('76%')
  12194. }
  12195. .margin({
  12196. left: 20,
  12197. right: 15,
  12198. top: 5,
  12199. bottom: 5
  12200. })
  12201. }
  12202. Row() {
  12203. Text(`歌词字号:`)
  12204. .fontSize(14)
  12205. .fontColor(Color.White)
  12206. .margin({ right: 12 })
  12207. Slider({
  12208. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  12209. min: 12,
  12210. max: 30,
  12211. step: 0.1,
  12212. style: SliderStyle.OutSet
  12213. })
  12214. .blockColor(this.themeColor)
  12215. .trackColor($r('app.color.speed_text_color'))
  12216. .selectedColor(Color.White)
  12217. .trackThickness(6)
  12218. .onChange((value: number) => {
  12219. this.setLyricTextSize(value, isPip)
  12220. })
  12221. .layoutWeight(1)
  12222. .margin({ right: 3 })
  12223. Text(this.getLyricSizeDisplayValue(isPip))
  12224. .fontSize(13)
  12225. .fontColor(Color.White)
  12226. .width(44)
  12227. .textAlign(TextAlign.End)
  12228. }
  12229. .width('76%')
  12230. .margin({
  12231. left: 20,
  12232. right: 45,
  12233. top: 5,
  12234. bottom: 5
  12235. })
  12236. Row() {
  12237. Text(`高亮倍数:`)
  12238. .fontSize(14)
  12239. .fontColor(Color.White)
  12240. .margin({ right: 12 })
  12241. Slider({
  12242. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  12243. min: 1,
  12244. max: 2,
  12245. step: 0.1,
  12246. style: SliderStyle.OutSet
  12247. })
  12248. .blockColor(this.themeColor)
  12249. .trackColor($r('app.color.speed_text_color'))
  12250. .selectedColor(Color.White)
  12251. .trackThickness(6)
  12252. .onChange((value: number) => {
  12253. this.setHighLyricTextSize(value, isPip)
  12254. })
  12255. .layoutWeight(1)
  12256. .margin({ right: 3 })
  12257. Text(this.getHighLyricSizeDisplayValue(isPip))
  12258. .fontSize(13)
  12259. .fontColor(Color.White)
  12260. .width(44)
  12261. .textAlign(TextAlign.End)
  12262. }
  12263. .width('76%')
  12264. .margin({
  12265. left: 20,
  12266. right: 45,
  12267. top: 5,
  12268. bottom: 5
  12269. })
  12270. Row() {
  12271. Text(`歌词间隙:`)
  12272. .fontSize(14)
  12273. .fontColor(Color.White)
  12274. .margin({ right: 12 })
  12275. Slider({
  12276. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  12277. min: 0,
  12278. max: 100,
  12279. step: 1,
  12280. style: SliderStyle.OutSet
  12281. })
  12282. .blockColor(this.themeColor)
  12283. .trackColor($r('app.color.speed_text_color'))
  12284. .selectedColor(Color.White)
  12285. .trackThickness(6)
  12286. .onChange((value: number) => {
  12287. this.setLyricLineSpace(value, isPip)
  12288. })
  12289. .layoutWeight(1)
  12290. .margin({ right: 3 })
  12291. Text(this.getLyricLineSpaceDisplayValue(isPip))
  12292. .fontSize(13)
  12293. .fontColor(Color.White)
  12294. .width(44)
  12295. .textAlign(TextAlign.End)
  12296. }
  12297. .width('76%')
  12298. .margin({
  12299. left: 20,
  12300. right: 45,
  12301. top: 5,
  12302. bottom: 5
  12303. })
  12304. //取值间隔为100,默认为400,取值越大,字体越粗
  12305. Row() {
  12306. Text(`歌词字重:`)
  12307. .fontSize(14)
  12308. .fontColor(Color.White)
  12309. .margin({ right: 12 })
  12310. Slider({
  12311. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  12312. min: 100,
  12313. max: 900,
  12314. step: 100,
  12315. style: SliderStyle.OutSet
  12316. })
  12317. .blockColor(this.themeColor)
  12318. .trackColor($r('app.color.speed_text_color'))
  12319. .selectedColor(Color.White)
  12320. .trackThickness(6)
  12321. .onChange((value: number) => {
  12322. if (isPip) {
  12323. this.lyricTextWeightPip = value
  12324. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  12325. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  12326. } else {
  12327. this.lyricTextWeight = value
  12328. this.lyricController.setTextWeight(this.lyricTextWeight)
  12329. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  12330. }
  12331. })
  12332. .layoutWeight(1)
  12333. .margin({ right: 3 })
  12334. Text(this.getLyricTextWeightDisplayValue(isPip))
  12335. .fontSize(13)
  12336. .fontColor(Color.White)
  12337. .width(44)
  12338. .textAlign(TextAlign.End)
  12339. }
  12340. .width('76%')
  12341. .margin({
  12342. left: 20,
  12343. right: 45,
  12344. top: 5,
  12345. bottom: 5
  12346. })
  12347. Row() {
  12348. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  12349. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  12350. // this.pushLyricButton($r('app.media.white_search'), 1, '繁体转简体')
  12351. }
  12352. .justifyContent(FlexAlign.Center)
  12353. .margin({ top: 3, bottom: 10 })
  12354. }
  12355. }
  12356. private getLyricSizeDisplayValue(isPip: boolean): string {
  12357. const lyricSize = isPip ? this.currentLyricSizePip : this.currentLyricSize;
  12358. return lyricSize.toFixed(1);
  12359. }
  12360. private getHighLyricSizeDisplayValue(isPip: boolean): string {
  12361. const highLyricSize = isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize;
  12362. return highLyricSize.toFixed(1);
  12363. }
  12364. private getLyricLineSpaceDisplayValue(isPip: boolean): string {
  12365. const lyricLineSpace = isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace;
  12366. return Math.round(lyricLineSpace).toString();
  12367. }
  12368. private getLyricTextWeightDisplayValue(isPip: boolean): string {
  12369. const lyricTextWeightValue = isPip ? this.lyricTextWeightPip : this.lyricTextWeight;
  12370. return Math.round(lyricTextWeightValue).toString();
  12371. }
  12372. private setBlurDegree(index: number, isPip: boolean) {
  12373. if (isPip) {
  12374. this.blurDegreePip = index
  12375. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  12376. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  12377. } else {
  12378. this.blurDegree = index
  12379. this.lyricController.setBlurDegree(this.blurDegree)
  12380. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  12381. }
  12382. }
  12383. private setLyricAlignMode(index: number, isPip: boolean) {
  12384. if (isPip) {
  12385. this.currentLyricAlignModePip = index
  12386. if (this.currentLyricAlignModePip === 1) {
  12387. this.lyricControllerXF.setAlignMode("left")
  12388. } else {
  12389. this.lyricControllerXF.setAlignMode("center")
  12390. }
  12391. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  12392. } else {
  12393. this.currentLyricAlignMode = index
  12394. if (this.currentLyricAlignMode === 1) {
  12395. this.lyricController.setAlignMode("left")
  12396. } else {
  12397. this.lyricController.setAlignMode("center")
  12398. }
  12399. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  12400. }
  12401. }
  12402. private setLyricTextSize(index: number, isPip: boolean) {
  12403. if (isPip) {
  12404. this.currentLyricSizePip = index
  12405. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  12406. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  12407. } else {
  12408. this.currentLyricSize = index
  12409. this.lyricController.setTextSize(this.currentLyricSize)
  12410. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  12411. }
  12412. }
  12413. private setHighLyricTextSize(scale: number, isPip: boolean) {
  12414. if (isPip) {
  12415. this.currentHightLyricSizePip = scale
  12416. this.lyricControllerXF
  12417. .setHighlightScale(this.currentHightLyricSizePip)
  12418. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  12419. } else {
  12420. this.currentHightLyricSize = scale
  12421. this.lyricController
  12422. .setHighlightScale(this.currentHightLyricSize)
  12423. PreferencesUtil.putSync('HighLyricTextSize', scale)
  12424. }
  12425. }
  12426. private setLyricLineSpace(index: number, isPip: boolean) {
  12427. if (isPip) {
  12428. this.currentLyricLineSpacePip = index
  12429. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  12430. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  12431. } else {
  12432. this.currentLyricLineSpace = index
  12433. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  12434. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  12435. }
  12436. }
  12437. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  12438. LogUtil.info('onecold isBG = ' + isBG)
  12439. if (isBG) { //如果是设置悬浮背景
  12440. this.pipBg = color
  12441. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  12442. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  12443. return
  12444. }
  12445. if (isPip) {
  12446. this.currentLyricColorPip = color
  12447. this.lyricControllerXF
  12448. .setTextColor(this.currentLyricColorPip)
  12449. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  12450. } else {
  12451. this.currentLyricColor = color
  12452. this.lyricController
  12453. .setTextColor(this.currentLyricColor)
  12454. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  12455. }
  12456. }
  12457. private changeLyricHightLightColor(color: string, isPip: boolean) {
  12458. if (isPip) {
  12459. this.currentHighLightLyricColorPip = color
  12460. this.lyricControllerXF
  12461. .setHighlightColor(this.currentHighLightLyricColorPip)
  12462. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  12463. } else {
  12464. this.currentHighLightLyricColor = color
  12465. this.lyricController
  12466. .setHighlightColor(this.currentHighLightLyricColor)
  12467. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  12468. }
  12469. }
  12470. // 构建时间控制器
  12471. @Builder
  12472. BuildTimeControls() {
  12473. Column() {
  12474. // 时间显示
  12475. Text(this.getTimeText())
  12476. .fontSize(18)
  12477. .fontColor(Color.White)
  12478. .margin({ bottom: 10 })
  12479. Row() {
  12480. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  12481. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  12482. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  12483. }
  12484. .justifyContent(FlexAlign.Center)
  12485. }
  12486. .margin({ top: 12, bottom: 8 })
  12487. }
  12488. // 精度按钮组件
  12489. @Builder
  12490. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  12491. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  12492. Column() {
  12493. Image(icon)
  12494. .width(28)
  12495. .margin({ bottom: 5 })
  12496. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  12497. Text(label)
  12498. .fontSize(12)
  12499. .fontColor('#FFFFFF')
  12500. }
  12501. }
  12502. .backgroundColor(Color.Transparent)
  12503. .enabled(!this.isButtonDisabled(step))
  12504. .onClick(() => this.handlePrecisionAdjust(step))
  12505. .padding(5)
  12506. .width(66)
  12507. .height(66)
  12508. .margin({ left: 18, right: 18 })
  12509. .border({
  12510. color: '#FFFFFF',
  12511. width: 1.8
  12512. })
  12513. }
  12514. private handlePrecisionAdjust(step: number) {
  12515. if (step === 0) {
  12516. this.timeOffset = 0
  12517. this.saveLyricTimeOffset()
  12518. return
  12519. }
  12520. // 精度处理:保留1位小数
  12521. const newOffset = Number((this.timeOffset + step).toFixed(5))
  12522. // 边界保护(±15.0秒)
  12523. if (newOffset < -30.0 || newOffset > 30.0) {
  12524. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  12525. return
  12526. }
  12527. // 状态更新
  12528. this.timeOffset = newOffset
  12529. // 保存歌词时间偏移
  12530. this.saveLyricTimeOffset()
  12531. }
  12532. // 按钮禁用逻辑
  12533. private isButtonDisabled(step: number): boolean {
  12534. const futureOffset = this.timeOffset + step
  12535. return (futureOffset < -30.0) || (futureOffset > 30.0)
  12536. }
  12537. // 时间显示文本升级
  12538. private getTimeText(): string {
  12539. const absValue = Math.abs(this.timeOffset)
  12540. return this.timeOffset === 0
  12541. ? '歌词时间已重置'
  12542. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  12543. }
  12544. /**
  12545. * 获取当前歌曲的唯一标识key
  12546. * 使用歌曲的filePath作为唯一标识
  12547. */
  12548. private getLyricOffsetKey(): string {
  12549. if (this.currentSong && StrUtil.isNotEmpty(this.currentSong.filePath)) {
  12550. // 使用MD5对filePath进行加密,作为存储key
  12551. return 'lyric_offset_' + MD5.digestSync(this.currentSong.filePath)
  12552. }
  12553. return ''
  12554. }
  12555. /**
  12556. * 保存当前歌曲的歌词时间偏移
  12557. */
  12558. private saveLyricTimeOffset(): void {
  12559. try {
  12560. const key = this.getLyricOffsetKey()
  12561. if (StrUtil.isEmpty(key)) {
  12562. console.warn('heanup saveLyricTimeOffset: key is empty')
  12563. return
  12564. }
  12565. PreferencesUtil.putSync(key, this.timeOffset)
  12566. console.info('heanup saveLyricTimeOffset: key=' + key + ', offset=' + this.timeOffset)
  12567. } catch (e) {
  12568. console.error('heanup saveLyricTimeOffset error: ' + JSON.stringify(e))
  12569. }
  12570. }
  12571. /**
  12572. * 加载当前歌曲的歌词时间偏移
  12573. */
  12574. private loadLyricTimeOffset(): void {
  12575. try {
  12576. const key = this.getLyricOffsetKey()
  12577. if (StrUtil.isEmpty(key)) {
  12578. console.warn('heanup loadLyricTimeOffset: key is empty')
  12579. return
  12580. }
  12581. const savedOffset = PreferencesUtil.getNumberSync(key, 0)
  12582. if (savedOffset !== 0) {
  12583. this.timeOffset = savedOffset
  12584. console.info('heanup loadLyricTimeOffset: key=' + key + ', offset=' + savedOffset)
  12585. }else{
  12586. this.timeOffset = 0
  12587. }
  12588. } catch (e) {
  12589. console.error('heanup loadLyricTimeOffset error: ' + JSON.stringify(e))
  12590. }
  12591. }
  12592. // 导入 本地歌词 搜索歌词
  12593. @Builder
  12594. pushLyricButton(icon: Resource, step: number, label: string) {
  12595. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  12596. Row() {
  12597. Image(icon)
  12598. .width(14)
  12599. .margin({ left: 13 })
  12600. Text(label)
  12601. .fontSize(12)
  12602. .margin({ left: 6 })
  12603. .fontColor('#FFFFFF')
  12604. }
  12605. }
  12606. .onClick(() => {
  12607. switch (step) {
  12608. case 0:
  12609. this.callFilePickerSelectFileForLyric()
  12610. break;
  12611. case 1:
  12612. //判断有没有设置api
  12613. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  12614. this.isLyricSetting = false
  12615. this.showTipsDialog()
  12616. return
  12617. }
  12618. if (StrUtil.isNotEmpty(this.videoUrl)) {
  12619. ToastUtil.showToast('正在获取')
  12620. this.isLyricSetting = false
  12621. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  12622. this.initLyric(lyricPath, true);
  12623. }
  12624. break;
  12625. }
  12626. })
  12627. .padding(5)
  12628. .width(110)
  12629. .backgroundColor(Color.Transparent)
  12630. .height(40)
  12631. .margin({ left: 6, right: 6 })
  12632. .border({
  12633. color: '#FFFFFF',
  12634. radius: 20,
  12635. width: 1.8
  12636. })
  12637. }
  12638. showVipDialog() {
  12639. DialogHelper.showCustomContentDialog({
  12640. dialogId: 'vip',
  12641. title: "友情提示",
  12642. autoCancel: false, //点击遮障层时,不关闭弹窗
  12643. backCancel: true, //点击返回键,不关闭弹窗
  12644. contentBuilder: () => {
  12645. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  12646. },
  12647. buttons: [],
  12648. })
  12649. }
  12650. //去赞助的自定义内容
  12651. @Builder
  12652. customVipBuilder(content: string) {
  12653. Column() {
  12654. Text(content)
  12655. .fontColor(Color.Gray)
  12656. .fontSize(16)
  12657. .alignSelf(ItemAlign.Start)
  12658. .margin({ bottom: 15 })
  12659. .fontSize(16)
  12660. Row() {
  12661. Button('取消')
  12662. .fontColor(Color.White)
  12663. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  12664. .height(50)
  12665. .layoutWeight(1)
  12666. .stateEffect(true)
  12667. .margin({ right: 6 })
  12668. .onClick(() => {
  12669. DialogHelper.closeDialog('vip'); //关闭弹框
  12670. })
  12671. Button('开通')
  12672. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  12673. .layoutWeight(1)
  12674. .height(50)
  12675. .backgroundColor(this.themeColor)
  12676. .stateEffect(true)
  12677. .margin({ left: 6 })
  12678. .onClick(() => {
  12679. DialogHelper.closeDialog('vip'); //关闭弹框
  12680. this.isShowPlay = false
  12681. this.mType = 1 //跳转到用户中心
  12682. // router.pushUrl({
  12683. // url: 'pages/VipPage'
  12684. // }, router.RouterMode.Single);
  12685. })
  12686. }
  12687. }
  12688. .width("100%")
  12689. .padding(10)
  12690. }
  12691. showTipsDialog() {
  12692. DialogHelper.showCustomContentDialog({
  12693. dialogId: 'tips',
  12694. title: "友情提示",
  12695. autoCancel: false, //点击遮障层时,不关闭弹窗
  12696. backCancel: true, //点击返回键,不关闭弹窗
  12697. contentBuilder: () => {
  12698. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  12699. },
  12700. buttons: [],
  12701. })
  12702. }
  12703. @Builder
  12704. customTipsBuilder(content: string) {
  12705. Column() {
  12706. Text(content)
  12707. .fontColor(Color.Gray)
  12708. .fontSize(16)
  12709. .alignSelf(ItemAlign.Start)
  12710. .margin({ bottom: 15 })
  12711. .fontSize(16)
  12712. Row() {
  12713. Button('取消')
  12714. .fontColor(Color.White)
  12715. .backgroundColor(this.themeColor)
  12716. .height(50)
  12717. .layoutWeight(1)
  12718. .stateEffect(true)
  12719. .margin({ right: 6 })
  12720. .onClick(() => {
  12721. DialogHelper.closeDialog('tips'); //关闭弹框
  12722. })
  12723. Button('跳转')
  12724. .fontColor(Color.White)//
  12725. .layoutWeight(1)
  12726. .height(50)
  12727. .backgroundColor(this.themeColor)
  12728. .stateEffect(true)
  12729. .margin({ left: 6 })
  12730. .onClick(() => {
  12731. DialogHelper.closeDialog('tips'); //关闭弹框
  12732. this.isShowEdit = false
  12733. this.longItemFilePath = ''
  12734. // if(this.isGridMusic&&!this.isShowPlay){
  12735. // this.longItemFilePath== ''
  12736. // }else{
  12737. // this.isShowEdit = false
  12738. // }
  12739. this.isShowMoreView = false;
  12740. this.isShowPlay = false
  12741. this.mType = 4
  12742. // router.pushUrl({
  12743. // url: 'pages/SettingPage'
  12744. // }, router.RouterMode.Single);
  12745. })
  12746. }
  12747. }
  12748. .width("100%")
  12749. .padding(10)
  12750. }
  12751. @Builder
  12752. PlayMoreSheet() {
  12753. Column() {
  12754. this.MoreList()
  12755. }
  12756. .width('100%')
  12757. .height('100%')
  12758. }
  12759. @Builder
  12760. MoreList() {
  12761. Scroll() {
  12762. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  12763. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  12764. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  12765. Row() {
  12766. if (more.id === 3&&this.currentSong) {
  12767. Image(more.image)
  12768. .width(24)
  12769. .height(24)
  12770. .margin({ left: 10, right: 10 })
  12771. Text(more.title)
  12772. .fontSize(16)
  12773. .fontColor(Color.White)
  12774. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  12775. height: '99%',
  12776. dragBar: true,
  12777. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  12778. showClose: true,
  12779. blurStyle: BlurStyle.Thin,
  12780. backgroundColor: Color.Transparent,
  12781. title: { title: '歌曲信息' }
  12782. })
  12783. } else if (more.id === 15 && this.currentSong) { //编辑标签
  12784. Image(more.image)
  12785. .width(24)
  12786. .height(24)
  12787. .margin({ left: 10, right: 10 })
  12788. Text(more.title)
  12789. .fontSize(16)
  12790. .fontColor(Color.White)
  12791. } else if (more.id === 5) { //定时关闭
  12792. Image(more.image)
  12793. .width(24)
  12794. .height(24)
  12795. .margin({ left: 10, right: 10 })
  12796. Text(more.title)
  12797. .fontSize(16)
  12798. .fontColor(Color.White)
  12799. .onClick(() => {
  12800. this.doMore(more.id)
  12801. })
  12802. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  12803. height: this.isCoverOpacity() ? '95%' : '95%',
  12804. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  12805. dragBar: true,
  12806. showClose: true,
  12807. title: { title: $r('app.string.time_close') }
  12808. })
  12809. } else if (more.id === 2) { //歌词设置
  12810. Image(more.image)
  12811. .width(24)
  12812. .height(24)
  12813. .margin({ left: 10, right: 10 })
  12814. Text(more.title)
  12815. .fontSize(16)
  12816. .fontColor(Color.White)
  12817. } else if (more.id === 16) { //悬浮歌词设置
  12818. Image(more.image)
  12819. .width(24)
  12820. .height(24)
  12821. .margin({ left: 10, right: 10 })
  12822. Text(more.title)
  12823. .fontSize(16)
  12824. .fontColor(Color.White)
  12825. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  12826. height: '99%',
  12827. dragBar: true,
  12828. preferType: SheetType.CENTER,
  12829. showClose: true,
  12830. blurStyle: BlurStyle.Thin,
  12831. backgroundColor: Color.Transparent,
  12832. title: { title: '悬浮歌词' }
  12833. })
  12834. } else if (more.id === 11) {
  12835. Image(more.image)
  12836. .width(24)
  12837. .height(24)
  12838. .margin({ left: 10, right: 10 })
  12839. Text(more.title)
  12840. .fontSize(16)
  12841. .fontColor(Color.White)
  12842. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  12843. height: this.isCoverOpacity() ? '95%' : '60%',
  12844. dragBar: true,
  12845. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  12846. showClose: true,
  12847. blurStyle: BlurStyle.Thin,
  12848. backgroundColor: Color.Transparent,
  12849. title: { title: '跳过头尾' }
  12850. })
  12851. } else if (more.id === 12) { //投播
  12852. AVCastPicker({
  12853. customPicker: (): void => this.TPImageBuilder(more),
  12854. onStateChange: (state) => {
  12855. if (state == AVCastPickerState.STATE_APPEARING) {
  12856. console.log(' The picker starts showing.');
  12857. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  12858. console.log(' The picker finishes presenting.');
  12859. }
  12860. },
  12861. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  12862. sessionType: 'video'
  12863. })
  12864. .id('AVCastPicker')
  12865. } else {
  12866. if(more.id >= 22){
  12867. SymbolGlyph(more.image)
  12868. .fontSize(24)
  12869. .fontColor([Color.White])
  12870. .alignSelf(ItemAlign.Center)
  12871. .margin({ left: 10, right: 10,bottom:5})
  12872. // .padding({bottom:4})
  12873. .onClick(() => {
  12874. this.doMore(more.id)
  12875. })
  12876. }else{
  12877. Image(more.image)
  12878. .width(24)
  12879. .height(24)
  12880. .fillColor(Color.White)
  12881. .margin({ left: 10, right: 10 })
  12882. .onClick(() => {
  12883. this.doMore(more.id)
  12884. })
  12885. }
  12886. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  12887. .fontSize(16)
  12888. .margin({top:more.id >= 22?3:0})
  12889. .fontColor(Color.White)
  12890. .onClick(() => {
  12891. this.doMore(more.id)
  12892. })
  12893. Select([//倍速
  12894. { value: '0.25x' },
  12895. { value: '0.5x' },
  12896. { value: '0.75x' },
  12897. { value: '1x' },
  12898. { value: '1.25x' },
  12899. { value: '1.5x' },
  12900. { value: '1.75x' },
  12901. { value: '2x' },
  12902. { value: '3x' }])
  12903. .font({ size: 16, weight: FontWeight.Medium })
  12904. .fontColor($r('sys.color.white'))
  12905. .margin({ left: 25 })
  12906. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  12907. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  12908. .value(Utility.optimizedFormat(this.playSpeed))
  12909. .onSelect(async (_index: number, text?: string | undefined) => {
  12910. let speed = parseFloat(text?.replace('x', '') || '1');
  12911. if (!CommonConstants.video_speed_list.includes(speed)) {
  12912. speed = 1;
  12913. }
  12914. this.playSpeed = speed
  12915. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  12916. })
  12917. Slider({
  12918. value: this.volume,
  12919. min: 0,
  12920. max: 1,
  12921. step: 0.1,
  12922. style: SliderStyle.OutSet
  12923. })
  12924. .margin({ left: 18, right: 8 })
  12925. .blockColor(this.themeColor)
  12926. .trackColor($r('app.color.speed_text_color'))
  12927. .selectedColor(Color.White)
  12928. .trackThickness(9)
  12929. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  12930. .onChange((value: number) => {
  12931. this.volume = value;
  12932. this.applyCurrentVolume();
  12933. PreferencesUtil.putSync('DefalutVolume',this.volume)
  12934. })
  12935. .layoutWeight(1)
  12936. Slider({
  12937. value: this.volumeBoostPercent,
  12938. min: 0,
  12939. max: this.volumeBoostMaxPercent,
  12940. step: 1,
  12941. style: SliderStyle.OutSet
  12942. })
  12943. .margin({ left: 18, right: 8 })
  12944. .blockColor(this.themeColor)
  12945. .trackColor($r('app.color.speed_text_color'))
  12946. .selectedColor(Color.White)
  12947. .trackThickness(9)
  12948. .visibility(more.id === 28 ? Visibility.Visible : Visibility.None)
  12949. .onChange((value: number) => {
  12950. this.volumeBoostPercent = Math.round(value);
  12951. this.applyCurrentVolume();
  12952. PreferencesUtil.putSync(this.volumeBoostPreferenceKey, this.volumeBoostPercent);
  12953. })
  12954. .layoutWeight(1)
  12955. Text(`${Math.round(this.volumeBoostPercent)}%`)
  12956. .fontSize(13)
  12957. .fontColor(Color.White)
  12958. .margin({ left: 8, right: 8 })
  12959. .visibility(more.id === 28 ? Visibility.Visible : Visibility.None)
  12960. Text(`${Math.round(this.volume*100)}%`)
  12961. .fontSize(13)
  12962. .fontColor(Color.White)
  12963. .margin({ left: 8, right: 8 })
  12964. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  12965. Blank()
  12966. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  12967. .selectedColor(this.themeColor)
  12968. .switchPointColor(Color.White)
  12969. .margin({ right: 15 })
  12970. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  12971. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  12972. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  12973. if (more.id == 6) {
  12974. this.isMusicMemoryPlay = checked;
  12975. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  12976. if (this.isMusicMemoryPlay) {
  12977. ToastUtil.showToast('记忆播放已开启')
  12978. } else {
  12979. ToastUtil.showToast('记忆播放已关闭')
  12980. }
  12981. }
  12982. })
  12983. .width(48)
  12984. .height(24);
  12985. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  12986. .selectedColor(this.themeColor)
  12987. .switchPointColor(Color.White)
  12988. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  12989. .margin({ right: 15 })
  12990. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  12991. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  12992. if (more.id == 7) {
  12993. this.isMusicBGCover = checked;
  12994. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  12995. if (this.isMusicBGCover) {
  12996. ToastUtil.showToast('播放背景随音乐封面已开启')
  12997. } else {
  12998. ToastUtil.showToast('播放背景随音乐封面已关闭')
  12999. }
  13000. }
  13001. })
  13002. .width(48)
  13003. .height(24);
  13004. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  13005. .selectedColor(this.themeColor)
  13006. .switchPointColor(Color.White)
  13007. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13008. .margin({ right: 15 })
  13009. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  13010. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  13011. if (more.id == 8) {
  13012. this.isSavePlayMode = checked;
  13013. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  13014. if (this.isSavePlayMode) {
  13015. ToastUtil.showToast('保存播放模式已开启')
  13016. } else {
  13017. ToastUtil.showToast('保存播放模式已关闭')
  13018. }
  13019. }
  13020. })
  13021. .width(48)
  13022. .height(24);
  13023. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  13024. .selectedColor(this.themeColor)
  13025. .switchPointColor(Color.White)
  13026. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13027. .margin({ right: 15 })
  13028. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  13029. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  13030. if (more.id == 13) {
  13031. this.isCoverRectangle = checked;
  13032. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  13033. if (this.isCoverRectangle) {
  13034. ToastUtil.showToast('封面方形已开启')
  13035. this.animationRoFun()
  13036. } else {
  13037. ToastUtil.showToast('封面圆形已开启')
  13038. this.animationRoFun()
  13039. }
  13040. }
  13041. })
  13042. .width(48)
  13043. .height(24);
  13044. Toggle({ type: ToggleType.Switch, isOn: this.isShowSpectrum })
  13045. .selectedColor(this.themeColor)
  13046. .switchPointColor(Color.White)
  13047. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13048. .margin({ right: 15 })
  13049. .visibility(more.id == 25 ? Visibility.Visible : Visibility.None)
  13050. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  13051. if (more.id == 25) {
  13052. this.isShowSpectrum = checked;
  13053. PreferencesUtil.put("isShowSpectrum", this.isShowSpectrum)
  13054. }
  13055. })
  13056. .width(48)
  13057. .height(24);
  13058. // 频谱特效类型选择器
  13059. Select([
  13060. { value: '柱状' },
  13061. { value: '波形' },
  13062. { value: '圆形' },
  13063. { value: '粒子' },
  13064. { value: '脉冲' },
  13065. { value: '镜像柱' },
  13066. { value: '影子柱' },
  13067. { value: '轨道线' },
  13068. { value: '点阵' },
  13069. { value: '星爆' }
  13070. ])
  13071. .font({ size: 14, weight: FontWeight.Medium })
  13072. .fontColor(Color.White)
  13073. .margin({ left: 25 })
  13074. .margin({top:more.id >= 22?3:0})
  13075. .visibility(more.id === 26 ? Visibility.Visible : Visibility.None)
  13076. .selected(this.spectrumModeIndex)
  13077. .value(['柱状', '波形', '圆形', '粒子', '脉冲', '镜像柱', '影子柱', '轨道线', '点阵', '星爆'][this.spectrumModeIndex])
  13078. .onSelect((index: number, _text?: string) => {
  13079. this.spectrumModeIndex = index;
  13080. // 使用同步方法保存,确保立即生效
  13081. PreferencesUtil.putSync('spectrumModeIndex', this.spectrumModeIndex);
  13082. AppStorage.setOrCreate<number>('spectrumMode', this.spectrumModeIndex);
  13083. const modeNames = ['柱状', '波形', '圆形', '粒子', '脉冲', '镜像柱', '影子柱', '轨道线', '点阵', '星爆'];
  13084. Logger.info('heanup-LocalMusic', '频谱特效已切换为: ' + modeNames[index]);
  13085. });
  13086. Toggle({ type: ToggleType.Switch, isOn: this.showSimple })
  13087. .selectedColor(this.themeColor)
  13088. .switchPointColor(Color.White)
  13089. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13090. .margin({ right: 15 })
  13091. .visibility(more.id == 22 ? Visibility.Visible : Visibility.None)
  13092. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  13093. if (more.id == 22) {
  13094. this.showSimple = checked;
  13095. PreferencesUtil.put('showSimple', this.showSimple)
  13096. }
  13097. })
  13098. .width(48)
  13099. .height(24);
  13100. Toggle({ type: ToggleType.Switch, isOn: this.enablePointLight })
  13101. .selectedColor(this.themeColor)
  13102. .switchPointColor(Color.White)
  13103. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13104. .margin({ right: 15 })
  13105. .visibility(more.id == 23 ? Visibility.Visible : Visibility.None)
  13106. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  13107. if (more.id == 23) {
  13108. this.enablePointLight = checked;
  13109. PreferencesUtil.put('enablePointLight', this.enablePointLight)
  13110. AppStorage.setOrCreate('EnablePointLight', this.enablePointLight);
  13111. }
  13112. })
  13113. .width(48)
  13114. .height(24);
  13115. Toggle({ type: ToggleType.Switch, isOn: this.isGeKongPlayNext })
  13116. .selectedColor(this.themeColor)
  13117. .switchPointColor(Color.White)
  13118. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13119. .margin({ right: 15 })
  13120. .visibility(more.id == 27 ? Visibility.Visible : Visibility.None)
  13121. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  13122. if (more.id == 27) {
  13123. this.isGeKongPlayNext = checked;
  13124. PreferencesUtil.put('isGeKongPlayNext', this.isGeKongPlayNext)
  13125. }
  13126. })
  13127. .width(48)
  13128. .height(24);
  13129. Toggle({ type: ToggleType.Switch, isOn: this.isShowBgLiuGUANG })
  13130. .selectedColor(this.themeColor)
  13131. .switchPointColor(Color.White)
  13132. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  13133. .margin({ right: 15 })
  13134. .visibility(more.id == 21 ? Visibility.Visible : Visibility.None)
  13135. .onChange((checked: boolean) => { // 是否开启背景流光效果
  13136. if (more.id == 21) {
  13137. this.isShowBgLiuGUANG = checked;
  13138. PreferencesUtil.putSync('isShowBgLiuGUANG',this.isShowBgLiuGUANG)
  13139. }
  13140. })
  13141. .width(48)
  13142. .height(24);
  13143. }
  13144. }
  13145. .width('100%')
  13146. .height(45)
  13147. .padding(15)
  13148. .backgroundColor(Color.Transparent)
  13149. .borderRadius(12)
  13150. .margin({ bottom: 6 })
  13151. }
  13152. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  13153. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  13154. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  13155. .backgroundColor(Color.Transparent)
  13156. .onClick(() => {
  13157. this.doMore(more.id)
  13158. })
  13159. });
  13160. }
  13161. .width('100%')
  13162. .padding(16)
  13163. }.margin({ bottom: 18 })
  13164. }
  13165. @Builder
  13166. TPImageBuilder(more: MoreItem): void {
  13167. Row() {
  13168. Image($r('app.media.tuoping'))
  13169. .width(22)
  13170. .height(22)
  13171. .margin({ left: 10, right: 10 })
  13172. Text(more.title)
  13173. .fontSize(16)
  13174. .fontColor(Color.White)
  13175. }
  13176. .width('100%')
  13177. .layoutWeight(1)
  13178. .alignItems(VerticalAlign.Center)
  13179. .justifyContent(FlexAlign.Start)
  13180. }
  13181. private moreItems: MoreItem[] = [
  13182. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  13183. { id: 30, image: $r('sys.symbol.lyrics_square'), title: '歌词' },
  13184. { id: 24, image: $r('sys.symbol.slider_vertical_3'), title: '均衡器' },
  13185. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  13186. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  13187. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  13188. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  13189. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  13190. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  13191. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  13192. { id:20,image: $r("app.media.a_b"), title: 'AB循环' },
  13193. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  13194. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  13195. { id: 4, image: $r('app.media.share2'), title: '分享' },
  13196. { id: 9, image: $r('app.media.volume_white'), title: '音量减弱' },
  13197. { id: 28, image: $r('sys.symbol.speaker_wave_3'), title: '音量增强' },
  13198. { id: 25, image: $r('sys.symbol.ranking'), title: '音乐频谱' },
  13199. { id: 26, image: $r('sys.symbol.eight_diagram'), title: '频谱类型' },
  13200. // { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  13201. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  13202. { id : 22, image: $r('sys.symbol.satellite_map'), title: '沉浸式' },
  13203. { id : 23, image: $r('sys.symbol.lightbulb'), title: '点光源效果' },
  13204. { id : 21, image: $r('app.media.kp_music'), title: '背景双边流光' },
  13205. { id : 27, image: $r('sys.symbol.hand'), title: '隔空手势切歌' },
  13206. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  13207. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  13208. ];
  13209. @State isShowBgLiuGUANG: boolean = false;
  13210. @State isShowMoreView: boolean = false;
  13211. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  13212. @State isShowTimeCloseMore: boolean = false
  13213. @State isShowDetailMore: boolean = false
  13214. @State isMusicBGCover: boolean = true
  13215. @State isSavePlayMode: boolean = true
  13216. @State isLyricSetting: boolean = false
  13217. @State isJumpSetting: boolean = false
  13218. @State isShowEdit: boolean = false
  13219. @State showPipLyric: boolean = false
  13220. @State isShowSpectrum: boolean = false//是否显示频谱
  13221. @State spectrumModeIndex: number = 0 //选中的频谱特效索引
  13222. private getSafeBoostPercent(): number {
  13223. const rawBoostPercent = Math.max(0, Math.min(this.volumeBoostPercent, this.volumeBoostMaxPercent));
  13224. if (rawBoostPercent <= 150) {
  13225. return rawBoostPercent;
  13226. }
  13227. if (rawBoostPercent <= 300) {
  13228. return 150 + (rawBoostPercent - 150) * 0.45;
  13229. }
  13230. return 217.5 + (rawBoostPercent - 300) * 0.15;
  13231. }
  13232. private getVolumeBoostFactor(): number {
  13233. return 1 + this.getSafeBoostPercent() / 100;
  13234. }
  13235. private getCurrentOutputVolume(): number {
  13236. const baseVolume = Math.max(0, Math.min(this.volume, 1));
  13237. const boostedVolume = baseVolume * this.getVolumeBoostFactor();
  13238. const maxOutputVolume = this.getVolumeBoostFactor();
  13239. return Math.max(0, Math.min(boostedVolume, maxOutputVolume));
  13240. }
  13241. private applyCurrentVolume(forceDsfSafeVolume: boolean = false): void {
  13242. if (!this.mIjkMediaPlayer) {
  13243. return;
  13244. }
  13245. if (forceDsfSafeVolume && this.volumeSmall && this.videoUrl.toLowerCase().endsWith('.dsf')) {
  13246. this.mIjkMediaPlayer.setVolume('1', '1');
  13247. return;
  13248. }
  13249. const outputVolume = this.getCurrentOutputVolume();
  13250. this.mIjkMediaPlayer.setVolume(outputVolume.toString(), outputVolume.toString());
  13251. }
  13252. async setRingTone() {
  13253. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  13254. return
  13255. }
  13256. // 确定后的逻辑
  13257. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  13258. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  13259. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  13260. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  13261. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  13262. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  13263. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  13264. , this.videoUrl, this.name).then(res => {
  13265. LogUtil.info('onecold setFlag :' + res);
  13266. });
  13267. }
  13268. doMore(moreId: number) {
  13269. switch (moreId) {
  13270. case 30: //歌词
  13271. this.isLyricSetting = !this.isLyricSetting;
  13272. this.isShowMoreView = false
  13273. break;
  13274. case 3: //详情
  13275. this.isShowDetailMore = !this.isShowDetailMore;
  13276. break;
  13277. case 4: //分享
  13278. if (this.currentSong !== undefined) {
  13279. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  13280. }
  13281. this.isShowMoreView = false
  13282. break;
  13283. case 5: //定时关闭
  13284. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  13285. break;
  13286. case 10: //设为铃声
  13287. this.setRingTone()
  13288. this.isShowMoreView = false
  13289. break;
  13290. case 11: //跳过头尾
  13291. this.isJumpSetting = !this.isJumpSetting;
  13292. break;
  13293. case 13: //倍速
  13294. break;
  13295. case 14: //搜索封面
  13296. if (this.currentSong !== undefined) {
  13297. this.doSearchCover(this.currentSong)
  13298. }
  13299. this.isShowMoreView = false
  13300. break;
  13301. case 15: //编辑标签
  13302. this.initEditFields(this.currentSong)
  13303. this.tempLyricContent = this.lyricContent
  13304. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  13305. this.lyricConStr = this.tempLyricContent
  13306. }
  13307. this.isShowEdit = !this.isShowEdit;
  13308. break;
  13309. case 16: //悬浮歌词
  13310. this.showPipLyric = !this.showPipLyric;
  13311. break;
  13312. case 17: //横屏模式
  13313. if (this.isLandscape) {
  13314. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  13315. } else {
  13316. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  13317. }
  13318. this.isShowMoreView = false
  13319. break;
  13320. case 20://AB循环
  13321. this.isABSheet = !this.isABSheet
  13322. break;
  13323. case 24://均衡器
  13324. this.isEqualizerSheet = !this.isEqualizerSheet
  13325. break;
  13326. }
  13327. }
  13328. //AB循环
  13329. @State isOpenAB:boolean = false
  13330. @State jumpATime:number = 0
  13331. @State jumpBTime:number = 0
  13332. @State isABSheet:boolean = false
  13333. @State isEqualizerSheet: boolean = false
  13334. @State eqApplying: boolean = false
  13335. @State eqAppliedAt: number = 0
  13336. @State eqCurrentPresetName: string = '正常'
  13337. @State eqCurrentEnabled: boolean = false
  13338. @Builder
  13339. ABLoopSheet() {
  13340. ABLoopComptent({
  13341. jumpATime:this.jumpATime,
  13342. jumpBTime:this.jumpBTime,
  13343. onClickAItem: async ()=>{
  13344. if(this.mIjkMediaPlayer){
  13345. this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
  13346. }
  13347. },
  13348. onClickBItem: async ()=>{
  13349. if(this.mIjkMediaPlayer){
  13350. this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
  13351. if(this.jumpBTime<=this.jumpATime){
  13352. ToastUtil.showToast('设置B点时间不能小于A点时间')
  13353. this.jumpBTime = 0
  13354. }
  13355. }
  13356. },
  13357. onCancleButtonClick: async ()=>{
  13358. this.isOpenAB = false
  13359. this.isABSheet = false
  13360. },
  13361. onStartButtonClick: async ()=>{
  13362. if(this.jumpBTime<=this.jumpATime||this.stringForTime(this.jumpATime)==this.stringForTime(this.jumpBTime)){
  13363. ToastUtil.showToast('设置B点时间不能小于或等于A点时间')
  13364. return
  13365. }
  13366. this.isABSheet = false
  13367. this.startABLoop()
  13368. },
  13369. })
  13370. }
  13371. private syncEqualizerUi(): void {
  13372. const equalizerManager = EqualizerManager.getInstance();
  13373. this.eqCurrentEnabled = equalizerManager.enabled;
  13374. this.eqCurrentPresetName = equalizerManager.getPresetDisplayName(equalizerManager.currentPresetId);
  13375. if (this.CONTROL_PlayStatus === PlayStatus.INIT) {
  13376. this.eqAppliedAt = 0;
  13377. }
  13378. }
  13379. private markEqualizerApplied(): void {
  13380. const equalizerManager = EqualizerManager.getInstance();
  13381. this.eqCurrentEnabled = equalizerManager.enabled;
  13382. this.eqCurrentPresetName = equalizerManager.getPresetDisplayName(equalizerManager.currentPresetId);
  13383. this.eqAppliedAt = Date.now();
  13384. this.eqApplying = false;
  13385. }
  13386. private applyEqualizerToCurrentPlayback(): void {
  13387. if (this.eqApplying) {
  13388. return;
  13389. }
  13390. if (this.castControllerWrapper && this.isCastPlaying) {
  13391. ToastUtil.showToast('投播模式暂不支持实时均衡器');
  13392. return;
  13393. }
  13394. if (!this.currentSong || !this.mIjkMediaPlayer) {
  13395. ToastUtil.showToast('暂无可应用的播放');
  13396. return;
  13397. }
  13398. this.eqApplying = true;
  13399. try {
  13400. const equalizerManager = EqualizerManager.getInstance();
  13401. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  13402. this.markEqualizerApplied();
  13403. ToastUtil.showToast('均衡器已实时生效');
  13404. } catch (error) {
  13405. this.eqApplying = false;
  13406. Logger.warn(TAG, `heanup 应用均衡器失败: ${(error as Error).message}`);
  13407. }
  13408. }
  13409. @Builder
  13410. private EqualizerApplyStatusBar(): void {
  13411. Row() {
  13412. Column() {
  13413. Text(`均衡器:${this.eqCurrentEnabled ? '开' : '关'} · ${this.eqCurrentPresetName}`)
  13414. .fontSize(12)
  13415. .fontColor($r('app.color.text_color'))
  13416. Text(this.eqAppliedAt > 0 ? '当前播放:已生效' : '当前播放:未应用')
  13417. .fontSize(10)
  13418. .fontColor(this.eqAppliedAt > 0 ? this.themeColor : Color.Gray)
  13419. }
  13420. .alignItems(HorizontalAlign.Start)
  13421. Blank()
  13422. Button('重新应用')
  13423. .fontSize(12)
  13424. .fontColor(Color.White)
  13425. .backgroundColor('#666666')
  13426. .height(28)
  13427. .padding({ left: 14, right: 14 })
  13428. .borderRadius(14)
  13429. .enabled(!this.eqApplying && this.CONTROL_PlayStatus !== PlayStatus.INIT)
  13430. .onClick(() => {
  13431. this.applyEqualizerToCurrentPlayback();
  13432. })
  13433. }
  13434. .width('100%')
  13435. .padding({ left: 12, right: 12, top: 8, bottom: 8 })
  13436. .backgroundColor($r('app.color.settings_background_main'))
  13437. .borderRadius(12)
  13438. }
  13439. @Builder
  13440. EqualizerSheet() {
  13441. Column() {
  13442. Column() {
  13443. EqualizerViewWithCallback({
  13444. onEqualizerChanged: () => {
  13445. this.syncEqualizerUi();
  13446. if (this.mIjkMediaPlayer) {
  13447. const equalizerManager = EqualizerManager.getInstance();
  13448. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  13449. this.markEqualizerApplied();
  13450. }
  13451. }
  13452. })
  13453. }
  13454. .margin({ top: 8 })
  13455. Column() {
  13456. this.EqualizerApplyStatusBar()
  13457. }
  13458. .margin({ top: 8 })
  13459. }
  13460. .padding({ left: 12, right: 12, bottom: 20 })
  13461. .width('100%')
  13462. }
  13463. //开始AB循环
  13464. startABLoop(){
  13465. if(this.mIjkMediaPlayer){
  13466. this.seekTo(this.jumpATime+'')
  13467. this.isOpenAB = true
  13468. }
  13469. }
  13470. /**
  13471. * 切换横竖屏
  13472. *
  13473. */
  13474. setOrientation(orientation: number) {
  13475. this.windowClass.setPreferredOrientation(orientation).then(() => {
  13476. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  13477. }).catch((err: BusinessError) => {
  13478. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  13479. });
  13480. }
  13481. /**
  13482. * 画中画功能(悬浮歌词功能)
  13483. *
  13484. */
  13485. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  13486. pipController?: PiPWindow.PiPController;
  13487. navigationId: string = '';
  13488. @State curState: string = '';
  13489. @State curError: ResourceStr = '';
  13490. @State pipBg: string = '#E8E8E8'
  13491. @State buttonAction: string = '';
  13492. //开启画中画功能
  13493. async startPip() {
  13494. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  13495. if (!this.pipController) {
  13496. await this.createPipController();
  13497. }
  13498. if (!this.pipController) {
  13499. Logger.info(`[${TAG}] pipController create error`);
  13500. return;
  13501. }
  13502. await this.pipController.startPiP();
  13503. }
  13504. async stopPip() {
  13505. if (!this.pipController) {
  13506. Logger.info(`[${TAG}] pipController is not exist`);
  13507. return;
  13508. }
  13509. this.isOpenPip = false
  13510. await this.pipController.stopPiP();
  13511. }
  13512. async createPipController() {
  13513. this.pipController = await PiPWindow.create({
  13514. context: getContext(this),
  13515. componentController: this.xcomponentController,
  13516. navigationId: this.navigationId,
  13517. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  13518. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  13519. customUIController: this.nodeController,
  13520. });
  13521. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  13522. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  13523. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  13524. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  13525. this.onStateChange(state, reason);
  13526. });
  13527. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  13528. this.onActionEvent(event, status);
  13529. });
  13530. }
  13531. destroyPipController() {
  13532. if (!this.pipController) {
  13533. return;
  13534. }
  13535. this.pipController.off('stateChange');
  13536. this.pipController.off('controlPanelActionEvent');
  13537. this.pipController = undefined;
  13538. }
  13539. onStateChange(state: PiPWindow.PiPState, reason: string) {
  13540. switch (state) {
  13541. case PiPWindow.PiPState.ABOUT_TO_START:
  13542. this.curState = 'ABOUT_TO_START';
  13543. this.curError = $r('app.string.current_error_hint');
  13544. break;
  13545. case PiPWindow.PiPState.STARTED:
  13546. this.curState = 'STARTED';
  13547. this.curError = $r('app.string.current_error_hint');
  13548. break;
  13549. case PiPWindow.PiPState.ABOUT_TO_STOP:
  13550. this.curState = 'ABOUT_TO_STOP';
  13551. this.curError = $r('app.string.current_error_hint');
  13552. break;
  13553. case PiPWindow.PiPState.STOPPED:
  13554. this.curState = 'STOPPED';
  13555. this.curError = $r('app.string.current_error_hint');
  13556. this.stopPip()
  13557. this.destroyPipController()
  13558. break;
  13559. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  13560. this.curState = 'ABOUT_TO_RESTORE';
  13561. this.curError = $r('app.string.current_error_hint');
  13562. break;
  13563. case PiPWindow.PiPState.ERROR:
  13564. this.curState = 'ERROR';
  13565. this.curError = reason;
  13566. break;
  13567. default:
  13568. break;
  13569. }
  13570. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  13571. }
  13572. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  13573. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  13574. switch (event) {
  13575. case 'playbackStateChanged':
  13576. if (status === 0) {
  13577. this.pause();
  13578. } else {
  13579. console.info('onecold startPlayOrResumePlay 9869')
  13580. this.startPlayOrResumePlay();
  13581. }
  13582. break;
  13583. case 'nextVideo':
  13584. // 切换到下一个视频
  13585. this.playNext().catch(() => {
  13586. Logger.error('heanup onActionEvent playNext', `播放下一首失败`);
  13587. });
  13588. break;
  13589. case 'previousVideo':
  13590. // 切换到上一个视频
  13591. this.playPrevious().catch(() => {
  13592. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败`);
  13593. });
  13594. break;
  13595. case 'previousVideo':
  13596. // 切换到上一个视频
  13597. this.playPrevious().catch(() => {
  13598. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败:`);
  13599. });
  13600. break;
  13601. default:
  13602. }
  13603. this.buttonAction = event + `-status:${status}`;
  13604. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  13605. }
  13606. /**
  13607. * 画中画功能(悬浮歌词功能)结束
  13608. *
  13609. */
  13610. async doSearchCover(item: VideoItem,title?:string,artist?:string): Promise<string> {
  13611. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  13612. this.isShowMoreView = false;
  13613. this.showTipsDialog();
  13614. return ''; // Return empty string when no API is configured
  13615. }
  13616. if (!item) {
  13617. return ''; // Return empty string if item is undefined
  13618. }
  13619. const titleS = title||item?.name || '';
  13620. const artistS = artist||item?.artist || ''; // Use empty string if artist is missing
  13621. return this.searchCover(item, titleS, artistS); // Await is not needed here as we return the promise directly
  13622. }
  13623. /**
  13624. *api搜索封面
  13625. *item,根据title和artist
  13626. */
  13627. searchCover(item: VideoItem, title: string, artist: string): Promise<string> {
  13628. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  13629. LogUtil.debug("onecold res =" + res);
  13630. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  13631. if (item.filePath == this.currentSong?.filePath) {
  13632. this.cover = res;
  13633. if (this.currentSong) {
  13634. this.currentSong.pixelMapPath = res;
  13635. }
  13636. }
  13637. if (isRemoteCloudType(item.type)) {
  13638. item.pixelMapPath = res;
  13639. this.syncRemoteManagerSong(item);
  13640. try {
  13641. await this.persistRemoteMetadataToDb(item);
  13642. this.emitRemoteMetadataUpdated(item);
  13643. } catch (error) {
  13644. Logger.error(TAG, `searchCover 持久化网盘封面失败: ${(error as Error).message}`);
  13645. }
  13646. } else {
  13647. // Update pixel map path but always return res regardless of success
  13648. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  13649. if (success) {
  13650. this.doUpdateData();
  13651. console.log("onecold 更新音乐封面成功,数据库已同步");
  13652. } else {
  13653. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  13654. }
  13655. // Note: We don't resolve/reject here because we already returned res
  13656. });
  13657. }
  13658. LogUtil.debug("onecold this.cover =" + this.cover);
  13659. }
  13660. return res; // Always return res regardless of updatePixelMapPath result
  13661. });
  13662. }
  13663. @State jumpTopTime: number = 0
  13664. @State jumpEndTime: number = 0
  13665. @State isOpenJump: boolean = false
  13666. @Builder
  13667. JumpTopEndSheet() {
  13668. Scroll() {
  13669. Column() {
  13670. Column() {
  13671. Text('仅对本播放列表有效')
  13672. .fontSize(16)
  13673. .fontColor($r('app.color.text_color'))
  13674. // 跳过头尾
  13675. Column() {
  13676. Row() {
  13677. Text('跳过片头:')
  13678. .fontSize(16)
  13679. .fontColor($r('app.color.text_color'))
  13680. Text(this.jumpTopTime + 's')
  13681. .fontSize(16)
  13682. .fontColor($r('app.color.text_color'))
  13683. }
  13684. .margin({ bottom: 5 })
  13685. Row() {
  13686. Slider({
  13687. value: this.jumpTopTime,
  13688. min: 0,
  13689. max: 120,
  13690. step: 1,
  13691. style: SliderStyle.OutSet
  13692. })
  13693. .blockColor(this.themeColor)
  13694. .trackColor($r('app.color.speed_text_color'))
  13695. .selectedColor(Color.White)
  13696. .trackThickness(8)
  13697. .onChange((value: number) => {
  13698. this.jumpTopTime = value;
  13699. })
  13700. .width('85%')
  13701. }
  13702. .alignItems(VerticalAlign.Top)
  13703. }
  13704. .margin({ top: 10, bottom: 10 })
  13705. // 跳过头尾
  13706. Column() {
  13707. Row() {
  13708. Text('跳过片尾:')
  13709. .fontSize(16)
  13710. .fontColor($r('app.color.text_color'))
  13711. Text(this.jumpEndTime + 's')
  13712. .fontSize(16)
  13713. .fontColor($r('app.color.text_color'))
  13714. }
  13715. .margin({ bottom: 5 })
  13716. Row() {
  13717. Slider({
  13718. value: this.jumpEndTime,
  13719. min: 0,
  13720. max: 120,
  13721. step: 1,
  13722. style: SliderStyle.OutSet
  13723. })
  13724. .blockColor(this.themeColor)
  13725. .trackColor($r('app.color.speed_text_color'))
  13726. .selectedColor(Color.White)
  13727. .trackThickness(8)
  13728. .onChange((value: number) => {
  13729. this.jumpEndTime = value;
  13730. })
  13731. .width('85%')
  13732. }
  13733. .alignItems(VerticalAlign.Top)
  13734. }
  13735. .margin({ top: 10, bottom: 10 })
  13736. Row() {
  13737. Button('保存设置')
  13738. .fontColor(Color.White)
  13739. .layoutWeight(1)
  13740. .height(40)
  13741. .width(80)
  13742. .backgroundColor(this.themeColor)
  13743. .stateEffect(true)
  13744. .margin({ left: 0, bottom: 20 })
  13745. .onClick(async () => {
  13746. if (!Utility.isNoble()) {
  13747. this.isJumpSetting = false
  13748. this.isShowMoreView = false
  13749. this.showVipDialog()
  13750. return
  13751. }
  13752. if (this.currentSong === undefined) {
  13753. return
  13754. }
  13755. if (this.modeType === 0) {
  13756. let parentPath = FileUtil.getParentPath(this.videoUrl)
  13757. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  13758. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  13759. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  13760. } else if (this.modeType === 1) { //媒体库
  13761. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  13762. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  13763. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  13764. } else if (this.modeType === 2) { //艺术家
  13765. if (this.currentSong?.artist) {
  13766. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  13767. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  13768. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  13769. }
  13770. } else if (this.modeType === 3) { //专辑
  13771. if (this.currentSong?.album) {
  13772. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  13773. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  13774. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  13775. }
  13776. }
  13777. ToastUtil.showShort("保存成功")
  13778. this.isJumpSetting = false
  13779. })
  13780. }
  13781. .margin({
  13782. left: 38,
  13783. right: 38,
  13784. top: 10,
  13785. bottom: 10
  13786. })
  13787. .width(120)
  13788. .height(50)
  13789. }
  13790. }
  13791. }
  13792. .width('100%')
  13793. .height('100%')
  13794. }
  13795. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  13796. private onStateVastChange(state: AVCastPickerState) {
  13797. if (state == AVCastPickerState.STATE_APPEARING) {
  13798. console.log('The picker starts showing.');
  13799. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  13800. console.log('The picker finishes presenting.');
  13801. }
  13802. }
  13803. private showSelectLyric() {
  13804. DialogHelper.showActionSheetDialog({
  13805. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  13806. // sheets: ["本地歌词", "搜索歌词"],
  13807. sheets: [
  13808. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  13809. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  13810. ],
  13811. maskColor: Color.Transparent,
  13812. backgroundColor: $r('app.color.bg_card'),
  13813. transition: AnimationHelper.transitionInDown(666),
  13814. onAction: (index) => {
  13815. switch (index) {
  13816. case 0:
  13817. this.callFilePickerSelectFileForLyric()
  13818. break;
  13819. case 1:
  13820. if (StrUtil.isNotEmpty(this.videoUrl)) {
  13821. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  13822. this.initLyric(lyricPath);
  13823. }
  13824. break;
  13825. }
  13826. }
  13827. })
  13828. }
  13829. // 拉起picker选择文件管理器
  13830. async callFilePickerSelectFileForLyric(): Promise<void> {
  13831. try {
  13832. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  13833. DocumentSelectOptions.maxSelectNumber = 1
  13834. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  13835. let documentPicker = new picker.DocumentViewPicker();
  13836. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  13837. Logger.info(TAG,
  13838. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  13839. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  13840. this.saveVideoDatasLyric(DocumentSelectResult)
  13841. }
  13842. }).catch((err: BusinessError) => {
  13843. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  13844. });
  13845. } catch (err) {
  13846. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  13847. }
  13848. }
  13849. async saveVideoDatasLyric(uris: string[]) {
  13850. if (ArrayUtil.isEmpty(uris)) {
  13851. return
  13852. }
  13853. let newUris: string[] = [];
  13854. for (let i = 0; i < uris.length; i++) {
  13855. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  13856. Logger.info(TAG, 'filePath uri: ' + filePath);
  13857. newUris.push(filePath)
  13858. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  13859. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  13860. fileIo.copyFileSync(file.fd, file2.fd)
  13861. fileIo.closeSync(file);
  13862. fileIo.closeSync(file2);
  13863. this.initLyric(filePath,false,false,true)
  13864. }
  13865. }
  13866. private initDelayPlay(context: object) {
  13867. this.mContext = context;
  13868. }
  13869. startPipLyric() {
  13870. if (this.pipController) {
  13871. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  13872. PiPWindow.PiPControlStatus.PLAY);
  13873. }
  13874. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  13875. if (this.isOpenPip) {
  13876. this.startPip()
  13877. } else {
  13878. this.stopPip()
  13879. }
  13880. }
  13881. //startOffset 从cue分轨时间开始播
  13882. private startPlayOrResumePlay(startOffset?:number) {
  13883. //新版本ijkplayer可以直接播放dsf歌,不需要转格式了。所以注释掉代码
  13884. //针对dsf文件高采样率,统一转wav播放
  13885. // const sampleRate = this.currentSong?.sampleRate||0
  13886. // if(this.videoUrl.toLowerCase().endsWith('.dsf')&&sampleRate>=441000){
  13887. // console.info('onecold 采样率 ='+sampleRate)
  13888. // let newDsfPath = this.context.filesDir + '/'+FileUtil.getFileName(this.videoUrl)+'.wav'
  13889. // console.info('onecold newDsfPath ='+newDsfPath)
  13890. // if(!FileUtil.accessSync(newDsfPath)){
  13891. // const task = new taskpool.Task(convertDsfToWav,this.videoUrl,newDsfPath);
  13892. // taskpool.execute(task, taskpool.Priority.HIGH).then((data)=>{
  13893. // this.videoUrl = newDsfPath
  13894. // this.startPlay(startOffset)
  13895. // }).catch((e:object)=>{
  13896. // console.info("task1 catch e: " + e);
  13897. // })
  13898. // }else{
  13899. // this.videoUrl = newDsfPath
  13900. // this.startPlay(startOffset)
  13901. // }
  13902. //
  13903. // }else{
  13904. // this.startPlay(startOffset)
  13905. // }
  13906. this.startPlay(startOffset)
  13907. // 仅当前播放的是网盘歌曲时,才提前缓存下一首
  13908. // 排除用户拖动进度条的情况
  13909. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !this.isSeekTo) {
  13910. void this.preloadNextSongInternal();
  13911. }
  13912. }
  13913. startPlay(startOffset?:number) {
  13914. this.startPipLyric()
  13915. this.mDestroyPage = false;
  13916. this.animationState = AnimationStatus.Running
  13917. LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  13918. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  13919. this.stopProgressTask();
  13920. this.startProgressTask();
  13921. this.clearInitialSeekGuardTimer();
  13922. this.activePlaybackMemoryKey = this.getPlaybackMemoryKey();
  13923. this.remoteRestoreSeekToken++;
  13924. const shouldMemoryPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)
  13925. || (this.isMemoryLastPlay && this.isFirstStartPlay);
  13926. this.pendingMemorySeekPosition = shouldMemoryPlay ? PreferencesUtil.getNumberSync(this.getPlaybackMemoryKey(), 0) : 0;
  13927. const isRemoteStreamSong = this.currentSong && isRemoteCloudType(this.currentSong.type) &&
  13928. this.videoUrl.includes('://');
  13929. this.waitInitialSeekBeforeStart = !!isRemoteStreamSong && this.pendingMemorySeekPosition > 0;
  13930. // 判断是否是HTTP或在线网盘视频,显示加载进度
  13931. this.isPlayerLoading = this.waitInitialSeekBeforeStart;
  13932. this.play(this.videoUrl.toString(),startOffset);
  13933. }
  13934. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  13935. this.mIjkMediaPlayer.start();
  13936. this.setProgress()
  13937. this.CONTROL_PlayStatus = PlayStatus.PLAY
  13938. }
  13939. this.setIsPlaying(true)
  13940. this.updateSessionPlayState(true)
  13941. this.watchStatus();
  13942. this.updateLastPlayTimeStr(this.videoUrl)
  13943. }
  13944. updateLastPlayTimeStr(filePath: string) {
  13945. // 检查是否为网络音频(WebDAV),如果是则不更新本地数据库
  13946. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  13947. Logger.info(`heanup 检测到网络音频播放,跳过数据库更新: ${filePath}`)
  13948. return;
  13949. }
  13950. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  13951. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  13952. if (success) {
  13953. this.getHistoryList(false)
  13954. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  13955. } else {
  13956. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  13957. }
  13958. });
  13959. }
  13960. private completionNum(num: number): string | number {
  13961. if (num < 10) {
  13962. return '0' + num;
  13963. } else {
  13964. return num;
  13965. }
  13966. }
  13967. private parseDurationToMs(duration?: string): number {
  13968. if (!duration) {
  13969. return 0;
  13970. }
  13971. const parts = duration.split(':').map((item) => Number(item));
  13972. if (parts.some((item) => Number.isNaN(item))) {
  13973. return 0;
  13974. }
  13975. if (parts.length === 2) {
  13976. return Math.floor((parts[0] * 60 + parts[1]) * 1000);
  13977. }
  13978. if (parts.length === 3) {
  13979. return Math.floor((parts[0] * 3600 + parts[1] * 60 + parts[2]) * 1000);
  13980. }
  13981. return 0;
  13982. }
  13983. private stringForTime(timeMs: number): string {
  13984. let totalSeconds: number | string = (timeMs / 1000);
  13985. let newSeconds: number | string = totalSeconds % 60;
  13986. let minutes: number | string = (totalSeconds / 60) % 60;
  13987. let hours: number | string = totalSeconds / 3600;
  13988. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  13989. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  13990. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  13991. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  13992. if (this.isCurrentTime) {
  13993. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  13994. this.oldSeconds = newSeconds
  13995. } else {
  13996. newSeconds = this.oldSeconds
  13997. }
  13998. }
  13999. newSeconds = this.completionNum(newSeconds);
  14000. if (hours > 0) {
  14001. return hours + ":" + minutes + ":" + newSeconds;
  14002. } else {
  14003. return minutes + ":" + newSeconds;
  14004. }
  14005. }
  14006. private getPlayerSwiperDisplayCount(): number {
  14007. return new BreakpointType<number>({
  14008. sm: 1,
  14009. md: 2,
  14010. lg: 2,
  14011. xl: 2,
  14012. xxl: 2
  14013. }).getValue(this.currentBreakpoint) ?? 1
  14014. }
  14015. private shouldUpdateMainLyricPanel(): boolean {
  14016. return this.getPlayerSwiperDisplayCount() > 1 || this.currentSwiperIndex === 1
  14017. }
  14018. private getActivePlaybackPositionMs(): number {
  14019. if (this.castControllerWrapper && this.isCastPlaying) {
  14020. return this.currentTime2 * 1000
  14021. }
  14022. return this.mIjkMediaPlayer.getCurrentPosition()
  14023. }
  14024. private syncLyricPositionNow(): void {
  14025. const position = this.getActivePlaybackPositionMs()
  14026. if (position < 0) {
  14027. return
  14028. }
  14029. this.updateLyricPosition(position + this.timeOffset * 1000)
  14030. }
  14031. private updateLyricPosition(lyricPosition: number): void {
  14032. if (!this.isAppForeground || !this.isPageVisible) {
  14033. return;
  14034. }
  14035. const shouldUpdateMainLyric = this.shouldUpdateMainLyricPanel()
  14036. const shouldUpdatePipLyric = this.showPipLyric
  14037. const shouldUpdateSingleLineLyric = this.isShowSingleLineLyric
  14038. if (!shouldUpdateMainLyric && !shouldUpdatePipLyric && !shouldUpdateSingleLineLyric) {
  14039. return
  14040. }
  14041. if (!Number.isNaN(this.lastLyricRenderPosition) &&
  14042. Math.abs(lyricPosition - this.lastLyricRenderPosition) < this.lyricUpdateMinDeltaMs) {
  14043. return;
  14044. }
  14045. this.lastLyricRenderPosition = lyricPosition;
  14046. if (shouldUpdateMainLyric) {
  14047. this.lyricController.updatePosition(lyricPosition);
  14048. }
  14049. if (shouldUpdatePipLyric) {
  14050. this.lyricControllerXF.updatePosition(lyricPosition);
  14051. }
  14052. if (shouldUpdateSingleLineLyric) {
  14053. this.lyricControllerSingle.updatePosition(lyricPosition);
  14054. }
  14055. }
  14056. private setProgress() {
  14057. if (this.castControllerWrapper && this.isCastPlaying) {
  14058. return;
  14059. }
  14060. const shouldRefreshUi = this.isAppForeground && this.isPageVisible;
  14061. let position = this.mIjkMediaPlayer.getCurrentPosition();
  14062. let duration = this.mIjkMediaPlayer.getDuration();
  14063. if (duration <= 0 && this.duration > 0) {
  14064. duration = this.duration;
  14065. }
  14066. let pos = 0;
  14067. if (duration > 0) {
  14068. this.slideEnable = true;
  14069. let curPercent = position / duration;
  14070. pos = curPercent * 100;
  14071. if (shouldRefreshUi) {
  14072. if (pos > this.PROGRESS_MAX_VALUE) {
  14073. this.progressValue = this.PROGRESS_MAX_VALUE
  14074. } else {
  14075. this.progressValue = pos;
  14076. }
  14077. }
  14078. }
  14079. // LogUtils.getInstance()
  14080. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  14081. if (shouldRefreshUi) {
  14082. this.totalTime = this.stringForTime(duration);
  14083. }
  14084. if (position > duration) {
  14085. position = duration;
  14086. }
  14087. if (shouldRefreshUi) {
  14088. const lyricPosition = position + this.timeOffset * 1000;
  14089. this.isCurrentTime = true;
  14090. this.updateLyricPosition(lyricPosition);
  14091. // 蓝牙歌词更新逻辑
  14092. if (this.bluetoothLyricEnabled && this.isBluetoothConnected && this.lyricContent && this.currentSong) {
  14093. const currentLyricLine = LyricUtil.getCurrentLyricLine(this.lyricContent, lyricPosition);
  14094. // 仅在歌词行变化时更新,避免频繁调用
  14095. if (currentLyricLine !== this.lastBluetoothLyricLine) {
  14096. this.lastBluetoothLyricLine = currentLyricLine;
  14097. this.avSessionController.updateBluetoothLyric(
  14098. currentLyricLine,
  14099. this.currentSong.name || '',
  14100. this.currentSong.artist || '',
  14101. this.bluetoothLyricMode
  14102. );
  14103. }
  14104. }
  14105. this.currentTime = this.stringForTime(position);
  14106. this.isCurrentTime = false
  14107. }
  14108. if (this.mIjkMediaPlayer.isPlaying()) {
  14109. //如果是开启AB循环
  14110. if(this.isOpenAB){
  14111. if(position >=this.jumpBTime){
  14112. this.seekTo(this.jumpATime+'')
  14113. return
  14114. }
  14115. }
  14116. // 判断是否播放到结束时间
  14117. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  14118. if (position >= duration - this.jumpEndTime * 1000) {
  14119. if(this.playType == 1){//跳过尾部如果是单曲循环就选择单曲循环
  14120. this.CONTROL_PlayStatus = PlayStatus.INIT
  14121. this.startPlayOrResumePlay();
  14122. }else if (this.playType == 2) { //2:正常播放,单片播完
  14123. this.showRePlay();
  14124. this.currentTime = this.stringForTime(this.mIjkMediaPlayer.getDuration());
  14125. this.progressValue = this.PROGRESS_MAX_VALUE;
  14126. this.slideEnable = false;
  14127. this.stop();
  14128. // ToastUtil.showToast('开始重新播放')
  14129. }else if (this.playType == 4) { //4:连续播放不循环
  14130. // 检查是否是最后一首
  14131. if (this.curIndex >= this.songList.length - 1) {
  14132. // 已经是最后一首,停止播放
  14133. Logger.info('heanup setProgress', '连续播放不循环模式:已到达最后一首,停止播放');
  14134. ToastUtil.showToast('已经是最后一首了');
  14135. this.showRePlay();
  14136. this.currentTime = this.stringForTime(this.mIjkMediaPlayer.getDuration());
  14137. this.progressValue = this.PROGRESS_MAX_VALUE;
  14138. this.slideEnable = false;
  14139. this.stop();
  14140. } else {
  14141. // 不是最后一首,继续播放下一首
  14142. this.playNext().catch(() => {
  14143. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  14144. });
  14145. }
  14146. }else{
  14147. this.playNext().catch(() => {
  14148. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  14149. });
  14150. }
  14151. }
  14152. }
  14153. }
  14154. }
  14155. private startProgressTask() {
  14156. let that = this;
  14157. if (this.updateProgressTimer) {
  14158. clearInterval(this.updateProgressTimer);
  14159. this.updateProgressTimer = 0;
  14160. }
  14161. this.updateProgressTimer = setInterval(() => {
  14162. //LogUtils.getInstance().LOGI("startProgressTask");
  14163. if (!that.mDestroyPage) {
  14164. that.setProgress();
  14165. }
  14166. }, this.progressUpdateIntervalMs);
  14167. }
  14168. private stopProgressTask() {
  14169. LogUtils.getInstance().LOGI("stopProgressTask");
  14170. clearInterval(this.updateProgressTimer);
  14171. this.updateProgressTimer = 0;
  14172. }
  14173. private showLoadIng() {
  14174. this.loadingVisible = Visibility.Visible;
  14175. this.replayVisible = Visibility.None;
  14176. }
  14177. private hideLoadIng() {
  14178. this.loadingVisible = Visibility.None;
  14179. this.replayVisible = Visibility.None;
  14180. }
  14181. private showRePlay() {
  14182. this.loadingVisible = Visibility.None;
  14183. this.replayVisible = Visibility.Visible;
  14184. }
  14185. private clearInitialSeekGuardTimer(): void {
  14186. if (this.initialSeekGuardTimer) {
  14187. clearTimeout(this.initialSeekGuardTimer);
  14188. this.initialSeekGuardTimer = 0;
  14189. }
  14190. }
  14191. private ensurePlayerStartedAfterInitialSeek(reason: string): void {
  14192. try {
  14193. if (!this.mIjkMediaPlayer.isPlaying()) {
  14194. this.mIjkMediaPlayer.start();
  14195. }
  14196. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  14197. this.setIsPlaying(true);
  14198. this.updateSessionPlayState(true);
  14199. Logger.info(TAG, `记忆播放恢复开播: ${reason}`);
  14200. } catch (error) {
  14201. Logger.error(TAG, `记忆播放恢复开播失败(${reason}): ${(error as Error).message}`);
  14202. }
  14203. }
  14204. private finishInitialSeekWait(reason: string, shouldStart: boolean): void {
  14205. this.clearInitialSeekGuardTimer();
  14206. const wasWaiting = this.waitInitialSeekBeforeStart;
  14207. this.waitInitialSeekBeforeStart = false;
  14208. this.pendingMemorySeekPosition = 0;
  14209. this.isPlayerLoading = false;
  14210. this.hideLoadIng();
  14211. if (wasWaiting) {
  14212. Logger.info(TAG, `结束记忆seek等待: ${reason}`);
  14213. }
  14214. if (shouldStart) {
  14215. this.ensurePlayerStartedAfterInitialSeek(reason);
  14216. }
  14217. }
  14218. private startInitialSeekGuardTimer(scene: string): void {
  14219. this.clearInitialSeekGuardTimer();
  14220. if (!this.waitInitialSeekBeforeStart || this.pendingMemorySeekPosition <= 0) {
  14221. return;
  14222. }
  14223. const token = this.remoteRestoreSeekToken;
  14224. this.initialSeekGuardTimer = setTimeout(() => {
  14225. if (token !== this.remoteRestoreSeekToken || !this.waitInitialSeekBeforeStart) {
  14226. return;
  14227. }
  14228. Logger.warn(TAG, `记忆seek超时兜底开播, scene=${scene}, pos=${this.pendingMemorySeekPosition}`);
  14229. this.finishInitialSeekWait('seek-timeout', true);
  14230. }, this.initialSeekGuardTimeoutMs);
  14231. }
  14232. private async play(url: string,startOffset?:number) {
  14233. this.lyricController.setLyric(null)
  14234. this.lyricControllerSingle.setLyric(null)
  14235. this.lastLyricRenderPosition = Number.NaN;
  14236. this.isShowBgLiuGUANG = PreferencesUtil.getBooleanSync('isShowBgLiuGUANG', false)
  14237. console.info('onecold this.url 1= '+url)
  14238. if(!url.toLowerCase().startsWith('http')){
  14239. let hasPermission = await PermissionUtil.activatePermission(url)
  14240. console.info('onecold this.hasPermission 1= '+hasPermission)
  14241. if(!url.includes(this.packName)){
  14242. const file = fs.openSync(url)
  14243. this.videoUrl = file.path
  14244. url= this.videoUrl
  14245. }
  14246. console.info('onecold this.hasPermission 1= '+hasPermission)
  14247. console.info('onecold this.videoUrl 1= '+this.videoUrl)
  14248. }
  14249. let that = this;
  14250. if (this.waitInitialSeekBeforeStart) {
  14251. that.showLoadIng();
  14252. } else {
  14253. that.hideLoadIng();
  14254. }
  14255. const startOnPreparedOption = this.waitInitialSeekBeforeStart ? "0" : "1";
  14256. this.isOpenAB = false
  14257. //设置XComponent回调的context
  14258. if (!!this.mContext) {
  14259. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  14260. }
  14261. // 每次播放前都先 reset,防止快速切换歌曲时崩溃
  14262. // 修复 SIGSEGV 崩溃:确保播放器在设置新数据源前完全停止并释放资源
  14263. try {
  14264. this.mIjkMediaPlayer.reset();
  14265. Logger.info(TAG, 'IjkPlayer reset 成功');
  14266. } catch (error) {
  14267. Logger.error(TAG, `IjkPlayer reset 失败: ${(error as Error).message}`);
  14268. }
  14269. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  14270. //设置debug模式(用于EQ日志采集)
  14271. this.mIjkMediaPlayer.setDebug(true);
  14272. //初始化配置
  14273. this.mIjkMediaPlayer.native_setup();
  14274. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  14275. this.applyCurrentVolume(true);
  14276. // 构建规范的HTTP请求头(统一一次性设置,避免未带认证提前发起连接)
  14277. const headers = new Map<string, string>();
  14278. headers.set("User-Agent", "TTMusic-WebDAV/1.0");
  14279. headers.set("Accept", "*/*");
  14280. if (this.currentSong&&StrUtil.isEmpty(this.currentSong.pixelMapPath)
  14281. &&PreferencesUtil.getStringSync('COVER_API', '') != '') {
  14282. //如果封面为空,则搜索封面
  14283. this.searchCover(this.currentSong, this.currentSong.name, this.currentSong.artist||'')
  14284. }
  14285. // 如果是WebDAV网络音频,使用webdav_account_id获取认证信息(等待完成后再设置一次性头部)
  14286. // SMB类型通过本地HTTP代理播放,不需要认证头,排除SMB和百度类型
  14287. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !isBaiduType(this.currentSong.type) && !isSmbType(this.currentSong.type)) {
  14288. Logger.info(`heanup WebDAV歌曲认证 - 歌曲名: ${this.currentSong.name}, webdav_account_id: ${this.currentSong.webdav_account_id || '未设置'}`);
  14289. if (this.currentSong.webdav_account_id) {
  14290. try {
  14291. const webdavManager = RemoteDriveManager.getInstance();
  14292. const webDavHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  14293. if (webDavHeaders && webDavHeaders.size > 0) {
  14294. webDavHeaders.forEach((value, key) => headers.set(key, value));
  14295. Logger.info(`heanup 成功通过webdav_account_id获取并合并WebDAV认证头`);
  14296. } else {
  14297. Logger.warn(`heanup 通过webdav_account_id获取认证头失败,播放可能无法继续`);
  14298. }
  14299. } catch (error) {
  14300. const err = error as Error;
  14301. Logger.error(`heanup 获取WebDAV认证头时出错: ${err.message}`);
  14302. }
  14303. } else {
  14304. Logger.error(`heanup WebDAV歌曲 "${this.currentSong.name}" 缺少webdav_account_id,无法进行认证`);
  14305. }
  14306. } else if (this.currentSong && isSmbType(this.currentSong.type)) {
  14307. Logger.info(`heanup SMB歌曲通过HTTP代理播放,无需认证头`);
  14308. }
  14309. // 统一设置带认证的请求头
  14310. // 百度类型也需要特殊请求头
  14311. if (this.currentSong && isBaiduType(this.currentSong.type)) {
  14312. try {
  14313. const webdavManager = RemoteDriveManager.getInstance();
  14314. const baiduHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  14315. baiduHeaders.forEach((value, key) => headers.set(key, value));
  14316. const headerSnapshot: Record<string, string> = {};
  14317. headers.forEach((value, key) => headerSnapshot[key] = value);
  14318. Logger.info(TAG, `Baidu播放请求头: ${JSON.stringify(headerSnapshot)}`);
  14319. } catch (error) {
  14320. Logger.error(`heanup 构建百度请求头失败: ${(error as Error).message}`);
  14321. }
  14322. }
  14323. //设置视频源(先准备好认证头,再设置数据源)
  14324. Logger.info(TAG, `IjkPlayer setDataSource url=${url}`);
  14325. this.mIjkMediaPlayer.setDataSource(url);
  14326. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  14327. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !isBaiduType(this.currentSong.type)) {
  14328. console.log(`heanup 为WebDAV播放设置IjkPlayer选项`);
  14329. // 网络超时设置(单位:微秒,文档显示应该是字符串格式)
  14330. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "30000000"); // 30秒
  14331. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "30000000"); // 连接超时30秒
  14332. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "listen_timeout", "30000000"); // 监听超时30秒
  14333. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "30000000"); // DNS缓存超时30秒
  14334. // 缓冲和播放优化设置
  14335. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "1024000"); // 增大缓冲区
  14336. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "50"); // 减少最小帧数
  14337. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", startOnPreparedOption); // 预加载启动
  14338. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0"); // 无缓冲播放
  14339. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "30000"); // 最大缓存30秒
  14340. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1"); // 无限制收流
  14341. // 网络相关设置
  14342. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1"); // 启用HTTP重定向
  14343. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", "TTMusic-WebDAV/1.0"); // 用户代理
  14344. // 重连设置
  14345. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "reconnect", "3"); // 重连3次
  14346. console.log(`heanup WebDAV IjkPlayer选项设置完成`);
  14347. } else if (this.currentSong && isBaiduType(this.currentSong.type)) {
  14348. console.log(`heanup 为百度网盘播放设置IjkPlayer选项`);
  14349. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "15000000");
  14350. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "15000000");
  14351. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1");
  14352. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "1");
  14353. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "2097152");
  14354. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "25");
  14355. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", BaiduConstants.USER_AGENT);
  14356. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", "3");
  14357. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http-detect-range-support", "1");
  14358. console.log(`heanup 百度网盘 IjkPlayer 选项设置完成`);
  14359. }
  14360. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  14361. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  14362. // }
  14363. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  14364. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  14365. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  14366. let bufferSize = 50 * 1024 ; // 默认缓冲区大小为1MB
  14367. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  14368. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  14369. //停止预读的最小帧数
  14370. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  14371. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  14372. // 设置其他缓冲相关选项
  14373. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  14374. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  14375. //启动预加载
  14376. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", startOnPreparedOption);
  14377. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  14378. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  14379. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  14380. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  14381. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  14382. // 因此需要播放器丢包,才不会累积延时
  14383. // 这个和第三个参数packet-buffering无关。
  14384. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  14385. // 无限制收流
  14386. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  14387. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  14388. // 屏幕常亮
  14389. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  14390. // 开启hls起播优化 默认是关闭的
  14391. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "fetch_first", "on");
  14392. // 设置超时
  14393. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  14394. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  14395. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  14396. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  14397. // 变速播放
  14398. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  14399. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  14400. let Speed = this.mIjkMediaPlayer.getSpeed()
  14401. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  14402. //是否开启循环播放
  14403. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  14404. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = new ImplOnVideoSizeChangedListener(
  14405. (width: number, height: number, sar_num: number, sar_den: number) => {
  14406. if (height === 0) {
  14407. return;
  14408. }
  14409. const va = width / height;
  14410. const vpa = that.videoParentAspectRatio;
  14411. if (vpa > va) {
  14412. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  14413. } else {
  14414. that.videoWidth = '100%';
  14415. }
  14416. if (width && height) {
  14417. that.videoAspectRatio = width / height;
  14418. }
  14419. LogUtils.getInstance()
  14420. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  14421. if (!that.waitInitialSeekBeforeStart) {
  14422. that.hideLoadIng();
  14423. }
  14424. }
  14425. );
  14426. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  14427. let mOnPreparedListener: OnPreparedListener = new ImplOnPreparedListener(
  14428. async () => {
  14429. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  14430. if (!this.waitInitialSeekBeforeStart) {
  14431. // 无记忆seek时,prepared后可直接隐藏加载
  14432. this.isPlayerLoading = false;
  14433. }
  14434. try {
  14435. //保存碰一碰分享的当前的歌曲
  14436. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  14437. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  14438. await this.initLyric(lyricPath);
  14439. const applyDuration = (durationMs: number): void => {
  14440. if (durationMs <= 0) {
  14441. return;
  14442. }
  14443. this.duration = durationMs;
  14444. this.durationTime = Math.floor(durationMs / 1000);
  14445. this.durationStringTime = secondToTime(this.durationTime);
  14446. this.totalTime = this.stringForTime(durationMs);
  14447. if (this.currentSong) {
  14448. this.currentSong.duration = this.totalTime;
  14449. try {
  14450. this.avSessionController.setAVMetadataMusic(this.currentSong, durationMs, this.lyricContent);
  14451. } catch (metaError) {
  14452. Logger.warn(TAG, `heanup 首次播放写入AVSession失败: ${(metaError as Error).message}`);
  14453. }
  14454. }
  14455. };
  14456. const fetchBaiduM3u8Duration = async (url: string): Promise<number> => {
  14457. if (!url || !isBaiduType(this.currentSong?.type ?? -1)) {
  14458. return 0;
  14459. }
  14460. const httpRequest = http.createHttp();
  14461. try {
  14462. const response = await httpRequest.request(url, {
  14463. method: http.RequestMethod.GET,
  14464. connectTimeout: 8000,
  14465. readTimeout: 8000,
  14466. expectDataType: http.HttpDataType.STRING,
  14467. header: {
  14468. 'User-Agent': BaiduConstants.STREAMING_USER_AGENT,
  14469. 'Host': 'pan.baidu.com',
  14470. 'Referer': 'https://pan.baidu.com/disk/home',
  14471. 'Accept-Encoding': 'identity'
  14472. }
  14473. });
  14474. if (response.responseCode !== 200 || typeof response.result !== 'string') {
  14475. return 0;
  14476. }
  14477. const text = response.result;
  14478. if (text.indexOf('#EXTM3U') < 0) {
  14479. return 0;
  14480. }
  14481. const lines = text.split('\n');
  14482. let totalSeconds = 0;
  14483. for (let i = 0; i < lines.length; i++) {
  14484. const line = lines[i].trim();
  14485. if (line.startsWith('#EXTINF:')) {
  14486. const colonIndex = line.indexOf(':');
  14487. if (colonIndex < 0) {
  14488. continue;
  14489. }
  14490. const content = line.substring(colonIndex + 1);
  14491. const commaIndex = content.indexOf(',');
  14492. const numberPart = commaIndex >= 0 ? content.substring(0, commaIndex) : content;
  14493. const seconds = Number(numberPart);
  14494. if (!Number.isNaN(seconds) && seconds > 0) {
  14495. totalSeconds += seconds;
  14496. }
  14497. }
  14498. }
  14499. if (totalSeconds > 0) {
  14500. return Math.floor(totalSeconds * 1000);
  14501. }
  14502. return 0;
  14503. } catch (fetchError) {
  14504. Logger.warn(TAG, `heanup 解析百度M3U8时长失败: ${(fetchError as Error).message}`);
  14505. return 0;
  14506. } finally {
  14507. httpRequest.destroy();
  14508. }
  14509. };
  14510. const fetchDurationFallback = async (): Promise<void> => {
  14511. const durationMs = await fetchBaiduM3u8Duration(this.videoUrl);
  14512. if (durationMs > 0) {
  14513. Logger.info(TAG, `heanup 通过M3U8推导出时长: ${durationMs}ms`);
  14514. applyDuration(durationMs);
  14515. return;
  14516. }
  14517. Logger.warn(TAG, 'heanup 首次播放未拿到时长,保持未知');
  14518. };
  14519. const preparedDuration = this.mIjkMediaPlayer.getDuration();
  14520. console.info("onecold preparedDuration--" + preparedDuration)
  14521. if (preparedDuration > 0) {
  14522. applyDuration(preparedDuration);
  14523. if (this.videoUrl.includes('method=streaming') && isBaiduType(this.currentSong?.type ?? -1)) {
  14524. const durationMs = await fetchBaiduM3u8Duration(this.videoUrl);
  14525. if (durationMs > 0 && Math.abs(durationMs - preparedDuration) > 1000) {
  14526. Logger.info(TAG, `heanup 使用M3U8时长覆盖播放器时长: ${preparedDuration}ms -> ${durationMs}ms`);
  14527. applyDuration(durationMs);
  14528. }
  14529. }
  14530. } else {
  14531. const metaDurationMs = this.parseDurationToMs(this.currentSong?.duration);
  14532. if (metaDurationMs > 0) {
  14533. Logger.info(TAG, `heanup 使用元数据时长: ${metaDurationMs}ms`);
  14534. applyDuration(metaDurationMs);
  14535. } else {
  14536. fetchDurationFallback();
  14537. }
  14538. }
  14539. setTimeout(() => {
  14540. this.avSessionController.initAvSession(false);
  14541. if (this.duration > 0) {
  14542. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  14543. }
  14544. this.setAvSessionListener();
  14545. this.updateSessionPlayState(true)
  14546. this.setCurrentPlayMode()
  14547. if(startOffset&&startOffset>0){//cue分轨播放
  14548. this.seekTo(startOffset + "");
  14549. this.saveLastPlayList()
  14550. return
  14551. }
  14552. }, 500)
  14553. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  14554. let timeoutPlay = 0
  14555. if (StrUtil.isNotEmpty(this.videoUrl) &&
  14556. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  14557. timeoutPlay = 400
  14558. }
  14559. // 网盘流地址在prepare后立刻seek容易触发底层不稳定,统一延后记忆恢复
  14560. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.videoUrl.includes('://')) {
  14561. timeoutPlay = Math.max(timeoutPlay,
  14562. this.waitInitialSeekBeforeStart ? this.remoteMemorySeekInitialDelayMs : 700);
  14563. }
  14564. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  14565. if (this.modeType === 0) { //文件夹
  14566. let parentPath = FileUtil.getParentPath(this.videoUrl)
  14567. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  14568. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  14569. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  14570. } else if (this.modeType === 1) { //媒体库
  14571. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  14572. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  14573. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  14574. } else if (this.modeType === 2) { //艺术家
  14575. if (this.currentSong?.artist) {
  14576. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  14577. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  14578. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  14579. }
  14580. } else if (this.modeType === 3) { //专辑
  14581. if (this.currentSong?.album) {
  14582. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  14583. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  14584. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  14585. }
  14586. }
  14587. const playerDuration = this.mIjkMediaPlayer.getDuration()
  14588. if (playerDuration > 0) {
  14589. this.duration = playerDuration
  14590. }
  14591. const memoryPosition = this.pendingMemorySeekPosition > 0 ?
  14592. this.pendingMemorySeekPosition : PreferencesUtil.getNumberSync(this.getPlaybackMemoryKey(), 0);
  14593. if (this.waitInitialSeekBeforeStart && memoryPosition > 0) {
  14594. let targetSeekPosition = memoryPosition;
  14595. if (this.isOpenJump) {
  14596. targetSeekPosition = Math.max(targetSeekPosition, this.jumpTopTime * 1000);
  14597. }
  14598. this.pendingMemorySeekPosition = targetSeekPosition;
  14599. this.startInitialSeekGuardTimer('prepared-memory-seek');
  14600. Logger.info(TAG, `准备记忆播放seek: ${targetSeekPosition}ms, timeout=${timeoutPlay}ms`);
  14601. setTimeout(() => {
  14602. if (!this.waitInitialSeekBeforeStart) {
  14603. return;
  14604. }
  14605. this.restorePlaybackPosition();
  14606. }, timeoutPlay);
  14607. this.isFirstStartPlay = false
  14608. this.saveLastPlayList()
  14609. return
  14610. }
  14611. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  14612. if (this.mIjkMediaPlayer != null) {
  14613. let jumpTopTimeMs = this.jumpTopTime*1000;
  14614. if (jumpTopTimeMs <= this.duration) {
  14615. // 调用 seekTo 方法,跳到指定时间
  14616. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  14617. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  14618. this.seekTo(jumpTopTimeMs + ""); // 跳到开头或记忆进度中更靠后的位置
  14619. }
  14620. }, timeoutPlay)
  14621. } else {
  14622. // 提示用户无法跳过
  14623. ToastUtil.showToast('跳过时间超过视频时长');
  14624. }
  14625. }
  14626. } else {
  14627. this.jumpTopTime = 0
  14628. this.jumpEndTime = 0
  14629. // console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  14630. // console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  14631. // console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  14632. // PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  14633. //记忆播放(每一首都会记忆播放)
  14634. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  14635. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  14636. if (this.pendingMemorySeekPosition > 0 ||
  14637. PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  14638. this.restorePlaybackPosition() //读取播放记忆功能
  14639. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  14640. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  14641. this.restorePlaybackPosition() //读取播放记忆功能
  14642. }
  14643. this.isFirstStartPlay = false
  14644. }, timeoutPlay)
  14645. } else {
  14646. this.isFirstStartPlay = false
  14647. }
  14648. }
  14649. this.saveLastPlayList()
  14650. } catch (error) {
  14651. let err: BusinessError = error as BusinessError;
  14652. console.error('onecold failed with err: ' + JSON.stringify(err));
  14653. if (this.waitInitialSeekBeforeStart) {
  14654. this.finishInitialSeekWait('prepared-exception', true);
  14655. }
  14656. }
  14657. }
  14658. );
  14659. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  14660. let mOnTimedTextListener: OnTimedTextListener = new ImplOnTimedTextListener(
  14661. (text: string) => {
  14662. }
  14663. );
  14664. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  14665. let mOnCompletionListener: OnCompletionListener = new ImplOnCompletionListener(
  14666. () => {
  14667. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  14668. if (this.playType == 0) { //0:连续循环播放 1:单片重复播放 2:正常播放 4:连续播放不循环
  14669. // 异步调用playNext
  14670. this.playNext().catch(() => {
  14671. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  14672. });
  14673. } else if (this.playType == 1) { //1:单片重复播放
  14674. this.CONTROL_PlayStatus = PlayStatus.INIT
  14675. that.startPlayOrResumePlay();
  14676. } else if (this.playType == 2) { //2:正常播放,单曲播完
  14677. that.showRePlay();
  14678. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  14679. that.progressValue = this.PROGRESS_MAX_VALUE;
  14680. that.slideEnable = false;
  14681. that.stop();
  14682. // ToastUtil.showToast('开始重新播放')
  14683. } else if (this.playType == 3) { //3:随机播放
  14684. // 异步调用randomPlay
  14685. this.randomPlay().catch(() => {
  14686. Logger.error('heanup OnCompletionListener randomPlay', `随机播放失败`);
  14687. });
  14688. } else if (this.playType == 4) { //4:连续播放不循环
  14689. // 异步调用playNext
  14690. this.playNext().catch(() => {
  14691. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  14692. });
  14693. }
  14694. }
  14695. );
  14696. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  14697. let mOnBufferingUpdateListener: OnBufferingUpdateListener = new ImplOnBufferingUpdateListener(
  14698. (percent: number) => {
  14699. if (this.isDebug) {
  14700. const now = Date.now();
  14701. if (now - this.lastBufferingLogTs > this.bufferingLogIntervalMs) {
  14702. this.lastBufferingLogTs = now;
  14703. Logger.info(TAG, `OnBufferingUpdateListener percent=${percent}`);
  14704. }
  14705. }
  14706. }
  14707. );
  14708. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  14709. let mOnSeekCompleteListener: OnSeekCompleteListener = new ImplOnSeekCompleteListener(
  14710. () => {
  14711. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  14712. // seek 完成,延迟恢复播放,确保 ijkplayer 内部状态完全稳定
  14713. setTimeout(() => {
  14714. const waitingInitialSeek = that.waitInitialSeekBeforeStart;
  14715. that.isSeekTo = false;
  14716. if (waitingInitialSeek) {
  14717. that.finishInitialSeekWait('seek-complete', true);
  14718. } else {
  14719. that.hideLoadIng();
  14720. }
  14721. }, 200); // 延迟200ms,确保ijkplayer内部状态稳定
  14722. }
  14723. );
  14724. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  14725. let mOnInfoListener: OnInfoListener = new ImplOnInfoListener(
  14726. (what: number, extra: number) => {
  14727. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  14728. if (!that.waitInitialSeekBeforeStart) {
  14729. that.hideLoadIng();
  14730. }
  14731. }
  14732. );
  14733. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  14734. let mOnErrorListener: OnErrorListener = new ImplOnErrorListener(
  14735. (what: number, extra: number) => {
  14736. this.finishInitialSeekWait('player-error', false);
  14737. this.stopProgressTask();
  14738. console.info("heanup OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  14739. console.info('heanup 播放错误,歌曲详情:' + JSON.stringify(this.currentSong))
  14740. // 检查是否为WebDAV播放错误
  14741. let isWebDavError = false;
  14742. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.currentSong.filePath) {
  14743. try {
  14744. const globalContext = GlobalContext.getContext();
  14745. const webDavAuthInfo = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
  14746. if (webDavAuthInfo) {
  14747. isWebDavError = true;
  14748. }
  14749. } catch (error) {
  14750. console.error('OnErrorListener-->go: 获取WebDAV认证信息失败');
  14751. }
  14752. }
  14753. if (isWebDavError) {
  14754. console.info(`heanup WebDAV播放错误 - what: ${what}, extra: ${extra}, URL: ${this.videoUrl}`);
  14755. // 播放失败时清空实例变量中的WebDAV认证信息,防止错误账户持续使用
  14756. // this.currentWebDavAuthInfo = null;
  14757. console.info('heanup WebDAV播放失败,保留认证信息用于后续歌曲切换');
  14758. // 根据错误代码提供更具体的错误信息
  14759. let errorMessage = "WebDAV播放失败";
  14760. if (what === -1) { // 网络错误
  14761. errorMessage = "网络连接失败,请检查WebDAV服务器连接";
  14762. } else if (what === -1004) { // HTTP 404
  14763. errorMessage = "文件未找到,请检查WebDAV服务器上的文件";
  14764. } else if (what === -1001) { // 超时
  14765. errorMessage = "连接超时,请检查网络或WebDAV服务器状态";
  14766. } else if (what === -1003) { // 无法解析主机
  14767. errorMessage = "无法连接到WebDAV服务器";
  14768. }
  14769. ToastUtil.showToast(errorMessage);
  14770. } else {
  14771. if (StrUtil.isNotEmpty(this.videoUrl) &&
  14772. !this.videoUrl.startsWith('http') &&
  14773. this.currentSong &&this.currentSong.type==CommonConstants.TYPE_LOCAL&&
  14774. !FileUtil.accessSync(this.videoUrl)) {
  14775. console.info('heanup 播放.文件不存在');
  14776. ToastUtil.showToast(Utility.resourceToString(this.context, $r('app.string.file_not_exist')))
  14777. }
  14778. }
  14779. that.hideLoadIng();
  14780. }
  14781. );
  14782. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  14783. this.mIjkMediaPlayer.setMessageListener();
  14784. // 应用均衡器设置
  14785. try {
  14786. const equalizerManager = EqualizerManager.getInstance();
  14787. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  14788. Logger.info(TAG, 'heanup 均衡器设置已应用');
  14789. this.markEqualizerApplied();
  14790. } catch (eqError) {
  14791. Logger.warn(TAG, `heanup 应用均衡器失败: ${(eqError as Error).message}`);
  14792. this.eqApplying = false;
  14793. }
  14794. this.mIjkMediaPlayer.prepareAsync();
  14795. this.mIjkMediaPlayer.start();
  14796. }
  14797. //保存最后播放的那首歌和已经对应的播放列表
  14798. saveLastPlayList() {
  14799. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  14800. PreferencesUtil.putSync('LastMusicList', this.songList)
  14801. PreferencesUtil.putSync('LastPlayQueueScope', this.playQueueScope)
  14802. PreferencesUtil.putSync('LastPlayModeType', this.modeType)
  14803. PreferencesUtil.putSync('LastPlayTotalCount', this.totalCount)
  14804. }
  14805. // 清空播放记录
  14806. clearVideoHistory() {
  14807. this.table.clearPlayHistory((success: boolean, error?: string) => {
  14808. if (success) {
  14809. this.historyList = [];
  14810. this.updateListData(this.historyList)
  14811. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  14812. ToastUtil.showToast('清空播放记录成功')
  14813. } else {
  14814. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  14815. }
  14816. });
  14817. }
  14818. public async setAvSessionListener() {
  14819. if (!this.avSessionController) {
  14820. return;
  14821. }
  14822. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  14823. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  14824. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  14825. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  14826. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  14827. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  14828. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  14829. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  14830. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  14831. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  14832. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  14833. }
  14834. setLoopMode() {
  14835. let itype = this.playType + 1
  14836. if (itype >= 5) {
  14837. this.playType = 0
  14838. ToastUtil.showToast('连续循环播放')
  14839. } else if (itype === 1) {
  14840. this.playType = 1
  14841. ToastUtil.showToast('单曲循环')
  14842. } else if (itype === 2) {
  14843. this.playType = 2
  14844. ToastUtil.showToast('单曲播完')
  14845. } else if (itype === 3) {
  14846. this.playType = 3
  14847. ToastUtil.showToast('随机播放')
  14848. } else if (itype === 4) {
  14849. this.playType = 4
  14850. ToastUtil.showToast('连续播放不循环')
  14851. } else if (itype === 0) {
  14852. this.playType = 0
  14853. ToastUtil.showToast('连续循环播放')
  14854. }
  14855. PreferencesUtil.putSync('musicPlayType', this.playType)
  14856. this.setCurrentPlayMode()
  14857. }
  14858. private sessionSetLoopModeCallback = (mode: number) => {
  14859. if (this.mIjkMediaPlayer != null) {
  14860. ToastUtil.showToast('当前播放模式:' + mode)
  14861. Logger.info('onecold 当前播放模式= ' + mode)
  14862. let hmPlayMode = mode + 1
  14863. if (hmPlayMode >= 4) {
  14864. hmPlayMode = 0
  14865. }
  14866. if (hmPlayMode === 1) {
  14867. this.playType = 1
  14868. ToastUtil.showToast('单曲循环')
  14869. } else if (hmPlayMode === 0) {
  14870. this.playType = 2
  14871. ToastUtil.showToast('单曲播完')
  14872. } else if (hmPlayMode === 3) {
  14873. this.playType = 3
  14874. ToastUtil.showToast('随机播放')
  14875. } else if (hmPlayMode === 2) {
  14876. this.playType = 0
  14877. ToastUtil.showToast('连续循环播放')
  14878. } else if (hmPlayMode === 4) {
  14879. this.playType = 4
  14880. ToastUtil.showToast('连续播放不循环')
  14881. }
  14882. PreferencesUtil.putSync('musicPlayType', this.playType)
  14883. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  14884. let playBackState: avSession.AVPlaybackState = {
  14885. loopMode: hmPlayMode,
  14886. };
  14887. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  14888. console.info(`set setLoopMode AVPlaybackState successfully`);
  14889. }).catch((err: BusinessError) => {
  14890. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  14891. });
  14892. }
  14893. }
  14894. setCurrentPlayMode() {
  14895. if (!this.avSessionController) {
  14896. return;
  14897. }
  14898. let mLoopMode = 0
  14899. switch (this.playType) {
  14900. case 0:
  14901. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续循环播放
  14902. break;
  14903. case 1:
  14904. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  14905. break;
  14906. case 2:
  14907. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  14908. break;
  14909. case 3:
  14910. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  14911. break;
  14912. case 4:
  14913. mLoopMode = avSession.LoopMode.LOOP_MODE_CUSTOM //连续播放不循环
  14914. break;
  14915. }
  14916. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  14917. let playBState: avSession.AVPlaybackState = {
  14918. loopMode: mLoopMode,
  14919. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  14920. };
  14921. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  14922. console.info(`set setLoopMode AVPlaybackState successfully`);
  14923. }).catch((err: BusinessError) => {
  14924. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  14925. });
  14926. }
  14927. private sessionToggleFavoriteCallback = (assetId: string) => {
  14928. if (this.mIjkMediaPlayer != null && this.currentSong) {
  14929. console.info(`on toggleFavorite `);
  14930. // 应用收到收藏命令,进行收藏处理。
  14931. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  14932. this.doFav(this.currentSong)
  14933. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  14934. let playbackState: avSession.AVPlaybackState = {
  14935. isFavorite: !this.isFac,
  14936. };
  14937. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  14938. console.info(`SetAVPlaybackState successfully`);
  14939. }).catch((err: BusinessError) => {
  14940. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  14941. });
  14942. }
  14943. }
  14944. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  14945. device: avSession.OutputDeviceInfo) => {
  14946. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  14947. // 将 connectState 转换为可读的字符串
  14948. let stateName = 'UNKNOWN';
  14949. switch (connectState) {
  14950. case avSession.ConnectionState.STATE_CONNECTED:
  14951. stateName = 'CONNECTED(1)';
  14952. break;
  14953. case avSession.ConnectionState.STATE_DISCONNECTED:
  14954. stateName = 'DISCONNECTED(2)';
  14955. break;
  14956. case avSession.ConnectionState.STATE_CONNECTING:
  14957. stateName = 'CONNECTING(3)';
  14958. break;
  14959. default:
  14960. stateName = `OTHER(${connectState})`;
  14961. }
  14962. Logger.info('heanup sessionOutputDeviceChange', `设备状态变化: connectState=${stateName}, castCategory=${currentDevice?.castCategory}, isCastPlaying=${this.isCastPlaying}`);
  14963. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  14964. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  14965. await this.startCasting();
  14966. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  14967. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  14968. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  14969. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  14970. if (device) {
  14971. Logger.info('heanup sessionOutputDeviceChange', '设备断开连接');
  14972. Logger.info('heanup sessionOutputDeviceChange', '用户主动断开连接或已停止播放,调用endCasting');
  14973. this.endCasting();
  14974. }
  14975. }
  14976. };
  14977. private async startCasting() {
  14978. try {
  14979. Logger.info('heanup startCasting', '========== 开始投播初始化 ==========');
  14980. // 获取原始的 AVCastController
  14981. let avCastCtrl = await this.avSessionController.getAvSession()?.getAVCastController();
  14982. if (!avCastCtrl) {
  14983. Logger.error('heanup startCasting', '获取 AVCastController 失败');
  14984. return;
  14985. }
  14986. this.castController = avCastCtrl;
  14987. Logger.info('heanup startCasting', '✅ 获取 AVCastController 成功');
  14988. // 创建新的 CastController 封装器
  14989. this.castControllerWrapper = new CastController(avCastCtrl);
  14990. Logger.info('heanup startCasting', '✅ 创建 CastController 成功');
  14991. // 设置回调函数
  14992. let callbacks: CastControllerCallbacks = {
  14993. onPlayNext: () => {
  14994. Logger.info('heanup CastController', '收到 playNext 回调');
  14995. this.playNext();
  14996. },
  14997. onPlayPrevious: () => {
  14998. Logger.info('heanup CastController', '收到 playPrevious 回调');
  14999. this.playPrevious();
  15000. },
  15001. onPositionChanged: (position: number) => {
  15002. this.positionChange(position);
  15003. },
  15004. onDurationChanged: (duration: number) => {
  15005. this.playDurationChange(duration);
  15006. }
  15007. };
  15008. this.castControllerWrapper.setCallbacks(callbacks);
  15009. Logger.info('heanup startCasting', '✅ 设置回调成功');
  15010. // 暂停本地播放
  15011. this.pause();
  15012. Logger.info('heanup startCasting', '✅ 暂停本地播放成功');
  15013. // 初始化投播会话
  15014. Logger.info('heanup startCasting', `准备调用 initAVCast: songList.length=${this.songList.length}, curIndex=${this.curIndex}, videoUrl=${this.videoUrl}`);
  15015. await this.castControllerWrapper.initAVCast(
  15016. this.songList,
  15017. this.curIndex,
  15018. this.mIjkMediaPlayer.getCurrentPosition(),
  15019. this.videoUrl,
  15020. this.getActiveDuration()
  15021. );
  15022. Logger.info('heanup startCasting', '✅ initAVCast 调用完成');
  15023. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  15024. refToIsCasting?.set(true);
  15025. this.castSeek = true;
  15026. // 从 CastController 获取投播状态
  15027. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  15028. if (this.isCastPlaying) {
  15029. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  15030. this.setIsPlaying(true);
  15031. this.updateSessionPlayState(true);
  15032. }
  15033. Logger.info('heanup startCasting', `✅ 投播初始化完成, isCastPlaying=${this.isCastPlaying}`);
  15034. } catch (error) {
  15035. Logger.error('heanup startCasting', `❌ 投播初始化失败: ${error}`);
  15036. }
  15037. }
  15038. async changeCasting() {
  15039. Logger.info('heanup changeCasting', '切换投播');
  15040. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  15041. this.initQueueItem();
  15042. await this.prepare();
  15043. this.setPlaybackStateChangeListener();
  15044. // isCastPlaying 会在 playbackStateChangeListener 中根据实际状态更新
  15045. this.castSeek = true;
  15046. }
  15047. public endCasting() {
  15048. Logger.info('heanup endCasting', 'endCasting被调用');
  15049. this.avSessionController.getAvSession()?.stopCasting();
  15050. this.stopCast();
  15051. // 关闭文件描述符
  15052. if (this.castFile) {
  15053. try {
  15054. fs.closeSync(this.castFile);
  15055. this.castFile = undefined;
  15056. Logger.info('heanup endCasting', '关闭投播文件描述符');
  15057. } catch (error) {
  15058. Logger.warn('heanup endCasting', `关闭文件描述符失败: ${error}`);
  15059. }
  15060. }
  15061. this.isCastPlaying = false;
  15062. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  15063. refToIsCasting?.set(false);
  15064. this.pause();
  15065. this.setIsPlaying(false);
  15066. // if (this.curIndex === this.curSource.index) {
  15067. // this.play
  15068. // this.seek(this.currentTime * 1000);
  15069. // this.setIsPlaying(true);
  15070. // } else {
  15071. // this.pauseVideo();
  15072. // this.setIsPlaying(false);
  15073. // }
  15074. }
  15075. public setIsPlaying(isPlayer: boolean) {
  15076. this.isPlaying = isPlayer;
  15077. // 发送播放状态变化事件给歌单详情页面
  15078. try {
  15079. const eventPlaybackStatus: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYBACK_STATUS }
  15080. const currentFilePath = this.currentSong?.filePath || ''
  15081. const eventData: emitter.EventData = {
  15082. data: {
  15083. isPlaying: this.isPlaying,
  15084. curIndex: this.curIndex,
  15085. currentFilePath: currentFilePath
  15086. }
  15087. };
  15088. emitter.emit(eventPlaybackStatus, eventData)
  15089. Logger.info(`heanup 发送播放状态变化事件: isPlaying=${this.isPlaying}, curIndex=${this.curIndex}, currentFilePath=${currentFilePath}`)
  15090. } catch (error) {
  15091. Logger.error('heanup 发送播放状态变化事件失败: ' + error)
  15092. }
  15093. }
  15094. private setPlaybackStateChangeListener(): void {
  15095. // 注意: HarmonyOS 的投播控制器可能不返回 state 字段
  15096. // 我们需要通过其他方式来判断播放状态
  15097. // 1. 监听位置变化
  15098. this.castController?.on('playbackStateChange', ['position'], (playbackState: avSession.AVPlaybackState) => {
  15099. if (playbackState.position && typeof playbackState.position.elapsedTime !== 'undefined') {
  15100. Logger.info('heanup playbackStateChange[position]', `elapsedTime=${playbackState.position.elapsedTime}`);
  15101. this.positionChange(playbackState.position.elapsedTime);
  15102. }
  15103. });
  15104. // 2. 监听时长变化
  15105. this.castController?.on('playbackStateChange', ['extras'], (playbackState: avSession.AVPlaybackState) => {
  15106. const duration = playbackState?.extras?.duration;
  15107. if (typeof duration === 'number') {
  15108. this.playDurationChange(duration);
  15109. }
  15110. });
  15111. // 3. 监听所有状态变化(用于调试和状态判断)
  15112. this.castController?.on('playbackStateChange', 'all', (playbackState: avSession.AVPlaybackState) => {
  15113. Logger.info('heanup playbackStateChange[all]', `完整状态=${JSON.stringify(playbackState)}`);
  15114. // 检查是否有 state 字段(某些设备可能返回)
  15115. if (playbackState.state !== undefined) {
  15116. Logger.info('heanup playbackStateChange', `state字段存在: ${playbackState.state}`);
  15117. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  15118. this.isCastPlaying = true;
  15119. }
  15120. }
  15121. });
  15122. // 4. 监听播放完成事件
  15123. this.castController?.on('endOfStream', this.playNextCallback);
  15124. this.castController?.on('playNext', this.playNextCallback);
  15125. this.castController?.on('playPrevious', this.playPreviousCallback);
  15126. // 5. 监听错误事件
  15127. this.castController?.on('error', (error: BusinessError) => {
  15128. Logger.error('heanup playbackStateChange', `投播错误: code=${error.code}, message=${error.message}`);
  15129. this.isCastPlaying = false;
  15130. });
  15131. }
  15132. private updateSessionPlayState(isPlay: boolean): void {
  15133. // if(!this.isBgPlayOpen)
  15134. // return
  15135. const elapsedTime = (this.castControllerWrapper && this.isCastPlaying) ? this.currentTime2 * 1000
  15136. : this.mIjkMediaPlayer.getCurrentPosition();
  15137. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  15138. this.setAVSessionPlayState({
  15139. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  15140. position: {
  15141. elapsedTime: elapsedTime,
  15142. updateTime: new Date().getTime()
  15143. }
  15144. });
  15145. }
  15146. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  15147. this.avSessionController.setAvSessionPlayState(playbackState)
  15148. }
  15149. private positionChange(position: number) {
  15150. this.currentTime2 = position / 1000;
  15151. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  15152. if (this.castControllerWrapper && this.isCastPlaying) {
  15153. this.updateCastProgress(position);
  15154. if (this.isSeekTo) {
  15155. this.isSeekTo = false;
  15156. }
  15157. }
  15158. }
  15159. private playDurationChange(duration: number) {
  15160. this.duration = duration;
  15161. this.durationTime = Math.floor(this.duration / 1000);
  15162. this.durationStringTime = secondToTime((this.durationTime));
  15163. if (this.castControllerWrapper && this.isCastPlaying) {
  15164. this.totalTime = this.stringForTime(this.duration);
  15165. }
  15166. }
  15167. // playbackStateChangeListener 方法已被删除,改用 setPlaybackStateChangeListener 中的内联函数
  15168. private reloadCasting = async () => {
  15169. Logger.info('heanup reloadCasting', '重新加载投播');
  15170. // 使用 initQueueItem() 方法来准备投播项目,保持逻辑一致
  15171. this.initQueueItem();
  15172. await this.prepare();
  15173. };
  15174. public playNextCallback = (): void => {
  15175. this.playNext().catch(() => {
  15176. Logger.error('heanup playNextCallback', `播放下一首失败`);
  15177. });
  15178. };
  15179. public playPreviousCallback = (): void => {
  15180. this.playPrevious().catch(() => {
  15181. Logger.error('heanup playNextCallback', `播放上一首失败`);
  15182. });
  15183. };
  15184. async prepare() {
  15185. try {
  15186. Logger.info('heanup prepare', `开始准备投播: ${this.castItem?.description?.title}`);
  15187. await this.castController?.prepare(this.castItem);
  15188. Logger.info('heanup prepare', '投播prepare成功');
  15189. await this.castController?.start(this.castItem);
  15190. Logger.info('heanup prepare', '投播start成功');
  15191. // 投播启动成功,设置为投播状态
  15192. this.isCastPlaying = true;
  15193. Logger.info('heanup prepare', '投播启动成功,设置isCastPlaying=true');
  15194. } catch (error) {
  15195. Logger.error('heanup prepare', `投播准备失败: ${error}`);
  15196. this.isCastPlaying = false;
  15197. }
  15198. }
  15199. public initQueueItem() {
  15200. let item = this.songList[this.curIndex];
  15201. // 判断是否是流媒体地址 - 使用 videoUrl 判断而不是 filePath
  15202. // 因为 filePath 可能是 navidrome:// 等自定义协议,而 videoUrl 才是真实的流地址
  15203. let isStreaming = this.isUrl(this.videoUrl);
  15204. Logger.info('heanup initQueueItem', `准备投播歌曲: ${item.name}, 是否流媒体: ${isStreaming}, videoUrl: ${this.videoUrl}`);
  15205. // 关闭之前的文件描述符
  15206. if (this.castFile) {
  15207. try {
  15208. fs.closeSync(this.castFile);
  15209. Logger.info('heanup initQueueItem', '关闭之前的文件描述符');
  15210. } catch (error) {
  15211. Logger.warn('heanup initQueueItem', `关闭文件描述符失败: ${error}`);
  15212. }
  15213. }
  15214. let description: avSession.AVMediaDescription = {
  15215. assetId: 'AUDIO-' + item.filePath,
  15216. title: item.name,
  15217. artist: item.artist || '',
  15218. // 该字段大写,音频'AUDIO',视频'VIDEO'
  15219. mediaType: 'AUDIO',
  15220. mediaSize: item.videoSize,
  15221. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  15222. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  15223. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  15224. duration: this.duration,
  15225. albumCoverUri: item.pixelMapPath, // 本地路径电视可能无法访问,暂时注释
  15226. appName: this.appName,
  15227. lyricContent: item.lyricContent,
  15228. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  15229. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  15230. };
  15231. console.log('heanup initQueueItem this.lyricContent', item.lyricContent);
  15232. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  15233. if (isStreaming) {
  15234. // 流媒体地址使用 mediaUri
  15235. description.mediaUri = this.videoUrl;
  15236. Logger.info('heanup initQueueItem', `使用流媒体地址投播: ${this.videoUrl}`);
  15237. } else {
  15238. // 本地文件使用 fdSrc
  15239. const localPath = this.videoUrl || item.filePath;
  15240. let uri = fileUri.getUriFromPath(localPath);
  15241. this.castFile = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  15242. let fdSrc: media.AVFileDescriptor = {
  15243. fd: this.castFile.fd
  15244. };
  15245. description.fdSrc = fdSrc;
  15246. Logger.info('heanup initQueueItem', `使用本地文件投播: ${localPath}, fd: ${this.castFile.fd}`);
  15247. }
  15248. this.castItem = {
  15249. itemId: this.curIndex,
  15250. description: description
  15251. };
  15252. Logger.info('heanup initQueueItem', `投播项目创建完成: ${JSON.stringify({
  15253. title: description.title,
  15254. mediaType: description.mediaType,
  15255. hasMediaUri: !!description.mediaUri,
  15256. hasFdSrc: !!description.fdSrc,
  15257. duration: description.duration
  15258. })}`);
  15259. }
  15260. // 判断是否是 URL 或流媒体地址
  15261. private isUrl(str: string): boolean {
  15262. if (!str) {
  15263. return false;
  15264. }
  15265. // 检查常见的流媒体协议
  15266. if (str.startsWith('http://') || str.startsWith('https://') ||
  15267. str.startsWith('rtmp://') || str.startsWith('rtsp://') ||
  15268. str.startsWith('rtp://') || str.startsWith('mms://')) {
  15269. return true;
  15270. }
  15271. // 扩展的URL正则表达式,支持多种协议
  15272. const urlPattern = new RegExp(
  15273. '^((https?|ftp|rtmp|rtsp|mms|ws|rtp|wss):\\/\\/)?' + // 支持多种协议
  15274. '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // 域名
  15275. '((\\d{1,3}\\.){3}\\d{1,3})|' + // 或IPv4地址
  15276. '\\[([a-f\\d]{1,4}:){7}[a-f\\d]{1,4}\\]|' + // 或IPv6地址
  15277. 'localhost)' + // 或localhost
  15278. '(\\:\\d+)?' + // 端口号(可选)
  15279. '(\\/[-a-z\\d%_.~+]*)*' + // 路径
  15280. '(\\?[;&a-z\\d%_.~+=-]*)?' + // 查询字符串(可选)
  15281. '(\\#[-a-z\\d_]*)?$', // 片段标识符(可选)
  15282. 'i' // 不区分大小写
  15283. );
  15284. return urlPattern.test(str);
  15285. }
  15286. async stopCast() {
  15287. try {
  15288. // 使用 CastController 释放资源
  15289. if (this.castControllerWrapper) {
  15290. await this.castControllerWrapper.releaseAVCast();
  15291. Logger.info('heanup stopCast', 'CastController 释放投播控制器成功');
  15292. }
  15293. // 清空引用
  15294. this.castControllerWrapper = undefined;
  15295. this.castController = undefined;
  15296. this.castItem = undefined;
  15297. this.castFile = undefined;
  15298. } catch (error) {
  15299. Logger.error('heanup stopCast', `停止投播失败: ${error}`);
  15300. }
  15301. }
  15302. private sessionPlayCallback = (): void => {
  15303. this.playOrPause()
  15304. };
  15305. private sessionPauseCallback = (): void => {
  15306. this.pause()
  15307. };
  15308. private async playOrPause() {
  15309. if (!this.debounce()) {
  15310. return;
  15311. }
  15312. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  15313. await this.pause();
  15314. } else {
  15315. // 如果是投播模式,使用 CastController 的 play 方法
  15316. if (this.castControllerWrapper && this.isCastPlaying) {
  15317. try {
  15318. Logger.info('heanup playOrPause', '投播模式播放');
  15319. await this.castControllerWrapper.setPlaying();
  15320. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  15321. this.setIsPlaying(true);
  15322. this.updateSessionPlayState(true);
  15323. Logger.info('heanup playOrPause', '投播播放成功');
  15324. this.playChange();
  15325. } catch (error) {
  15326. Logger.error('heanup playOrPause', `投播播放失败: ${error}`);
  15327. }
  15328. } else {
  15329. console.info('onecold startPlayOrResumePlay 11064')
  15330. this.startPlayOrResumePlay();
  15331. this.playChange()
  15332. }
  15333. }
  15334. }
  15335. private sessionPlayNextCallback = (): void => {
  15336. this.playNext().catch(() => {
  15337. Logger.error('heanup sessionPlayPreviousCallback', `播放下 一首失败`);
  15338. });
  15339. };
  15340. private sessionPlayPreviousCallback = (): void => {
  15341. this.playPrevious().catch(() => {
  15342. Logger.error('heanup sessionPlayPreviousCallback', `播放上一首失败`);
  15343. });
  15344. };
  15345. private sessionStopCallback = (): void => {
  15346. this.stop()
  15347. };
  15348. private sessionFastForwardCallback = async (time?: number) => {
  15349. if (!time) {
  15350. return;
  15351. }
  15352. let curPosition: number;
  15353. if (this.castController && this.isCastPlaying) {
  15354. // 投播模式,使用UI显示的时间
  15355. curPosition = this.currentTime2 * 1000;
  15356. } else if (this.mIjkMediaPlayer != null) {
  15357. // 本地播放器模式
  15358. curPosition = this.mIjkMediaPlayer.getCurrentPosition();
  15359. } else {
  15360. return;
  15361. }
  15362. let seeTime = curPosition + time * 1000;
  15363. // 限制 seekValue 在合法范围内
  15364. if (seeTime < 0) {
  15365. seeTime = 0;
  15366. } else if (seeTime > this.duration) {
  15367. seeTime = this.duration;
  15368. }
  15369. Logger.info('heanup sessionFastForwardCallback', `快进: ${time}秒, 目标位置: ${seeTime}ms`);
  15370. this.setSeekToActionProgress(seeTime);
  15371. await this.seekTo(seeTime + "");
  15372. };
  15373. private getActiveDuration(): number {
  15374. let duration = this.mIjkMediaPlayer.getDuration();
  15375. if (this.castControllerWrapper && this.isCastPlaying) {
  15376. return this.duration > 0 ? this.duration : duration;
  15377. }
  15378. if (duration <= 0 && this.duration > 0) {
  15379. duration = this.duration;
  15380. }
  15381. return duration;
  15382. }
  15383. @Builder
  15384. InlineSpectrumView() {
  15385. SpectrumView({
  15386. isVisible: this.currentSwiperIndex === 0,
  15387. isPlaying: this.CONTROL_PlayStatus === PlayStatus.PLAY
  15388. })
  15389. .width( '83%')
  15390. .height(this.isCoverOpacity() ? 80 : 100)
  15391. .margin({bottom: 3 })
  15392. .clip(true)
  15393. }
  15394. private getSongDurationMs(song?: VideoItem): number {
  15395. if (!song || !song.duration) {
  15396. return 0;
  15397. }
  15398. const raw = song.duration.trim();
  15399. if (!raw) {
  15400. return 0;
  15401. }
  15402. const parts = raw.split(':').map((part) => Number(part));
  15403. if (parts.some((part) => Number.isNaN(part))) {
  15404. return 0;
  15405. }
  15406. let seconds = 0;
  15407. if (parts.length === 3) {
  15408. seconds = parts[0] * 3600 + parts[1] * 60 + parts[2];
  15409. } else if (parts.length === 2) {
  15410. seconds = parts[0] * 60 + parts[1];
  15411. } else if (parts.length === 1) {
  15412. seconds = parts[0];
  15413. }
  15414. return seconds > 0 ? seconds * 1000 : 0;
  15415. }
  15416. private updateCastProgress(position: number): void {
  15417. const duration = this.getActiveDuration();
  15418. if (duration <= 0) {
  15419. return;
  15420. }
  15421. this.slideEnable = true;
  15422. let pos = (position / duration) * 100;
  15423. if (pos > this.PROGRESS_MAX_VALUE) {
  15424. this.progressValue = this.PROGRESS_MAX_VALUE;
  15425. } else if (pos < 0) {
  15426. this.progressValue = 0;
  15427. } else {
  15428. this.progressValue = pos;
  15429. }
  15430. this.totalTime = this.stringForTime(duration);
  15431. if (position > duration) {
  15432. position = duration;
  15433. }
  15434. this.isCurrentTime = true;
  15435. this.currentTime = this.stringForTime(position);
  15436. this.isCurrentTime = false;
  15437. const lyricPosition = position + this.timeOffset * 1000;
  15438. this.updateLyricPosition(lyricPosition);
  15439. }
  15440. /**
  15441. * Gesture method onActionUpdate.
  15442. *
  15443. * @param event Gesture event.手势拖动设置快进和后退
  15444. */
  15445. private setSeekToActionProgress(position: number) {
  15446. // 投播模式使用this.duration,本地模式使用播放器获取
  15447. let duration = this.getActiveDuration();
  15448. let pos = 0;
  15449. if (duration > 0) {
  15450. this.slideEnable = true;
  15451. let curPercent = position / duration;
  15452. pos = curPercent * 100;
  15453. if (pos > this.PROGRESS_MAX_VALUE) {
  15454. this.progressValue = this.PROGRESS_MAX_VALUE
  15455. } else {
  15456. this.progressValue = pos;
  15457. }
  15458. }
  15459. // LogUtils.getInstance()
  15460. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  15461. this.totalTime = this.stringForTime(duration);
  15462. if (position > duration) {
  15463. position = duration;
  15464. }
  15465. this.isCurrentTime = true;
  15466. this.currentTime = this.stringForTime(position);
  15467. this.isCurrentTime = false
  15468. }
  15469. private sessionRewindCallback = async (time?: number) => {
  15470. if (!time) {
  15471. return;
  15472. }
  15473. let curPosition: number;
  15474. if (this.castController && this.isCastPlaying) {
  15475. // 投播模式,使用UI显示的时间
  15476. curPosition = this.currentTime2 * 1000;
  15477. } else if (this.mIjkMediaPlayer != null) {
  15478. // 本地播放器模式
  15479. curPosition = this.mIjkMediaPlayer.getCurrentPosition();
  15480. } else {
  15481. return;
  15482. }
  15483. let seeTime = curPosition - time * 1000;
  15484. // 限制 seekValue 在合法范围内
  15485. if (seeTime < 0) {
  15486. seeTime = 0;
  15487. } else if (seeTime > this.duration) {
  15488. seeTime = this.duration;
  15489. }
  15490. Logger.info('heanup sessionRewindCallback', `快退: ${time}秒, 目标位置: ${seeTime}ms`);
  15491. this.setSeekToActionProgress(seeTime);
  15492. await this.seekTo(seeTime + "");
  15493. };
  15494. private sessionSeekCallback = async (seekTime: number) => {
  15495. Logger.info('heanup sessionSeekCallback', `收到seek请求: ${seekTime}ms, 投播模式: ${this.isCastPlaying}`);
  15496. // 投播模式直接调用seekTo,它会自动处理投播控制器的seek命令
  15497. await this.seekTo(seekTime + "");
  15498. };
  15499. private async getFileSize(filePath: string): Promise<number> {
  15500. try {
  15501. const stat = await fs.stat(filePath);
  15502. return stat.size;
  15503. } catch (err) {
  15504. console.error('Failed to get file size: ' + err.message);
  15505. return 0;
  15506. }
  15507. }
  15508. private async pause() {
  15509. // 如果是投播模式,使用 CastController 的 pause 方法
  15510. if (this.castControllerWrapper && this.isCastPlaying) {
  15511. try {
  15512. Logger.info('heanup pause', '投播模式暂停');
  15513. await this.castControllerWrapper.setPause();
  15514. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  15515. this.setIsPlaying(false);
  15516. this.updateSessionPlayState(false);
  15517. Logger.info('heanup pause', '投播暂停成功');
  15518. } catch (error) {
  15519. Logger.error('heanup pause', `投播暂停失败: ${error}`);
  15520. }
  15521. } else if (this.mIjkMediaPlayer.isPlaying()) {
  15522. // 本地播放器模式
  15523. this.savePlaybackPosition();
  15524. this.mIjkMediaPlayer.pause();
  15525. this.setProgress();
  15526. this.mDestroyPage = true;
  15527. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  15528. this.updateSessionPlayState(false)
  15529. this.playChange()
  15530. if (this.pipController) {
  15531. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  15532. PiPWindow.PiPControlStatus.PAUSE);
  15533. }
  15534. }
  15535. }
  15536. private stop() {
  15537. this.clearInitialSeekGuardTimer();
  15538. this.waitInitialSeekBeforeStart = false;
  15539. this.pendingMemorySeekPosition = 0;
  15540. this.isPlayerLoading = false;
  15541. this.savePlaybackPosition();
  15542. this.CONTROL_PlayStatus = PlayStatus.INIT;
  15543. this.mIjkMediaPlayer.stop();
  15544. this.mIjkMediaPlayer.release();
  15545. this.stopProgressTask();
  15546. this.updateSessionPlayState(false)
  15547. this.playChange()
  15548. this.watchStatus();
  15549. }
  15550. //保持记忆播放功能
  15551. private savePlaybackPosition() {
  15552. if (this.mIjkMediaPlayer != null) {
  15553. const position = this.mIjkMediaPlayer.getCurrentPosition();
  15554. // ToastUtil.showToast('保存记忆播放 = ' + position)
  15555. const duration = this.mIjkMediaPlayer.getDuration();
  15556. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  15557. // 如果播放位置接近视频末尾,则保存 position 为 0
  15558. const playbackPosition = (duration - position < threshold) ? 0 : position;
  15559. const memoryKey = this.activePlaybackMemoryKey || this.getPlaybackMemoryKey();
  15560. PreferencesUtil.putSync(memoryKey, playbackPosition);
  15561. }
  15562. }
  15563. private buildPlaybackMemoryKey(song?: VideoItem, playbackUrl?: string): string {
  15564. if (song && isRemoteCloudType(song.type)) {
  15565. const accountId = song.webdav_account_id || 'unknown';
  15566. const stablePath = song.remote_rel_path || song.id || song.baiduFsId || song.filePath || playbackUrl || '';
  15567. return `memory_play_remote:${song.type}:${accountId}:${stablePath}`;
  15568. }
  15569. return playbackUrl || '';
  15570. }
  15571. private getPlaybackMemoryKey(): string {
  15572. return this.buildPlaybackMemoryKey(this.currentSong, this.videoUrl);
  15573. }
  15574. private restoreRemotePlaybackPositionSafely(position: number, token: number, retryCount: number = 0): void {
  15575. if (token !== this.remoteRestoreSeekToken) {
  15576. return;
  15577. }
  15578. if (!this.mIjkMediaPlayer || position <= 0) {
  15579. if (this.waitInitialSeekBeforeStart) {
  15580. this.finishInitialSeekWait('invalid-memory-position', true);
  15581. }
  15582. return;
  15583. }
  15584. const duration = this.getActiveDuration();
  15585. const currentPos = this.mIjkMediaPlayer.getCurrentPosition();
  15586. let safePosition = position;
  15587. if (duration > 0) {
  15588. safePosition = Math.max(0, Math.min(position, duration - 500));
  15589. } else {
  15590. safePosition = Math.max(0, position);
  15591. }
  15592. if (safePosition <= 0) {
  15593. if (this.waitInitialSeekBeforeStart) {
  15594. this.finishInitialSeekWait('memory-position-too-small', true);
  15595. }
  15596. return;
  15597. }
  15598. if (retryCount === 0 && duration <= 0 && currentPos <= 0) {
  15599. Logger.info(TAG, `远程记忆seek提前尝试: pos=${safePosition}, duration=${duration}, current=${currentPos}`);
  15600. }
  15601. this.seekTo(safePosition + "");
  15602. if (retryCount >= this.remoteMemorySeekMaxRetryCount) {
  15603. return;
  15604. }
  15605. setTimeout(() => {
  15606. if (token !== this.remoteRestoreSeekToken || !this.waitInitialSeekBeforeStart || !this.mIjkMediaPlayer) {
  15607. return;
  15608. }
  15609. const latestPos = this.mIjkMediaPlayer.getCurrentPosition();
  15610. if (Math.abs(latestPos - safePosition) <= 1500) {
  15611. return;
  15612. }
  15613. this.restoreRemotePlaybackPositionSafely(position, token, retryCount + 1);
  15614. }, this.remoteMemorySeekRetryIntervalMs);
  15615. }
  15616. //获取记忆播放功能
  15617. private restorePlaybackPosition() {
  15618. const position: number = this.pendingMemorySeekPosition > 0 ?
  15619. this.pendingMemorySeekPosition : PreferencesUtil.getNumberSync(this.getPlaybackMemoryKey(), 0);
  15620. if (!this.mIjkMediaPlayer || position <= 0) {
  15621. if (this.waitInitialSeekBeforeStart) {
  15622. this.finishInitialSeekWait('no-memory-position', true);
  15623. }
  15624. return;
  15625. }
  15626. const isRemoteSong = this.currentSong ? isRemoteCloudType(this.currentSong.type) : false;
  15627. if (isRemoteSong && this.videoUrl.includes('://')) {
  15628. const token = this.remoteRestoreSeekToken;
  15629. this.restoreRemotePlaybackPositionSafely(position, token);
  15630. return;
  15631. }
  15632. const duration = this.getActiveDuration();
  15633. let safePosition = position;
  15634. if (duration > 0) {
  15635. safePosition = Math.max(0, Math.min(position, duration - 500));
  15636. } else {
  15637. safePosition = Math.max(0, position);
  15638. }
  15639. if (safePosition <= 0) {
  15640. if (this.waitInitialSeekBeforeStart) {
  15641. this.finishInitialSeekWait('memory-position-too-small', true);
  15642. }
  15643. return;
  15644. }
  15645. this.seekTo(safePosition + "");
  15646. }
  15647. private async seekTo(value: string) {
  15648. // if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  15649. // ToastUtil.showToast('wma格式不支持拖动快进。')
  15650. // return
  15651. // }
  15652. // 如果是投播模式,使用 CastController 的 seek 方法
  15653. if (this.castControllerWrapper && this.isCastPlaying) {
  15654. try {
  15655. let seekPos = Number.parseInt(value);
  15656. const duration = this.getActiveDuration();
  15657. if (duration > 0) {
  15658. seekPos = Math.max(0, Math.min(seekPos, duration - 200));
  15659. }
  15660. this.isSeekTo = true;
  15661. Logger.info('heanup seekTo', `投播模式seek到: ${seekPos}ms, 当前时长: ${this.duration}ms`);
  15662. // 检查是否接近末尾
  15663. if (this.duration > 0 && seekPos >= this.duration - 500) {
  15664. Logger.warn('heanup seekTo', `快进位置接近末尾(${seekPos}ms >= ${this.duration}ms),可能触发播放完成`);
  15665. }
  15666. await this.castControllerWrapper.seek(seekPos);
  15667. Logger.info('heanup seekTo', `投播seek命令发送成功,位置: ${seekPos}ms`);
  15668. } catch (error) {
  15669. Logger.error('heanup seekTo', `投播seek失败: ${error}`);
  15670. }
  15671. } else {
  15672. // 本地播放器模式
  15673. let seekPos = Number.parseInt(value);
  15674. if (Number.isNaN(seekPos)) {
  15675. return;
  15676. }
  15677. const duration = this.getActiveDuration();
  15678. const isRemoteSong = this.currentSong ? isRemoteCloudType(this.currentSong.type) : false;
  15679. if (duration > 0) {
  15680. seekPos = Math.max(0, Math.min(seekPos, duration - 200));
  15681. } else if (seekPos < 0) {
  15682. seekPos = 0;
  15683. }
  15684. if (isRemoteSong && duration <= 0 && seekPos > 0) {
  15685. Logger.warn(TAG, `seekTo 跳过未知时长远程seek: ${seekPos}ms`);
  15686. return;
  15687. }
  15688. if (isRemoteSong && duration <= 0) {
  15689. Logger.info(TAG, `seekTo 远程歌曲时长未知,仅允许起点seek: ${seekPos}ms`);
  15690. }
  15691. this.isSeekTo = true
  15692. try {
  15693. this.mIjkMediaPlayer.seekTo(seekPos + "");
  15694. this.setProgress()
  15695. } catch (error) {
  15696. Logger.error(TAG, `本地播放器seek失败: ${error}`);
  15697. } finally {
  15698. this.isSeekTo = false
  15699. }
  15700. }
  15701. }
  15702. // 添加到下一首播放
  15703. private addToNextPlay(song: VideoItem) {
  15704. if (!this.debounce()) {
  15705. return;
  15706. }
  15707. if (this.currentSong) {
  15708. if (this.currentSong === song) {
  15709. ToastUtil.showToast('当前已经在播放这首歌了!')
  15710. return
  15711. }
  15712. }
  15713. // 如果未开始播放或队列为空
  15714. if (this.curIndex === -1 || this.songList.length === 0) {
  15715. this.songList = [song];
  15716. this.curIndex = 0;
  15717. this.doPlay(song)
  15718. return;
  15719. }
  15720. // 插入到当前索引+1的位置
  15721. const insertPos = this.curIndex + 1;
  15722. this.songList.splice(insertPos, 0, song);
  15723. this.songList = [...this.songList]; // 触发状态更新
  15724. this.sonDataSource.pushArrayData(this.songList)
  15725. ToastUtil.showToast('已添加至下一首播放')
  15726. }
  15727. //后退10s,可再设置设置默认几秒
  15728. async backForward() {
  15729. // 如果是投播模式,从currentTime2获取当前位置
  15730. let pos: number;
  15731. if (this.castController && this.isCastPlaying) {
  15732. pos = this.currentTime2 * 1000; // 使用秒转毫秒
  15733. Logger.info('heanup backForward', `投播模式当前位置: ${pos}ms`);
  15734. } else if (this.mIjkMediaPlayer) {
  15735. pos = this.mIjkMediaPlayer.getCurrentPosition();
  15736. } else {
  15737. return;
  15738. }
  15739. let value = pos - Number(this.fastForwardSeconds) * 1000;
  15740. if (value < 0) {
  15741. value = 0;
  15742. }
  15743. await this.seekTo(value + "");
  15744. }
  15745. //快进10s,可再设置设置默认几秒
  15746. async fastForward() {
  15747. // 如果是投播模式,从currentTime2获取当前位置
  15748. let pos: number;
  15749. if (this.castController && this.isCastPlaying) {
  15750. pos = this.currentTime2 * 1000; // 使用秒转毫秒
  15751. Logger.info('heanup fastForward', `投播模式当前位置: ${pos}ms`);
  15752. } else if (this.mIjkMediaPlayer) {
  15753. pos = this.mIjkMediaPlayer.getCurrentPosition();
  15754. } else {
  15755. return;
  15756. }
  15757. let value = pos + Number(this.fastForwardSeconds) * 1000;
  15758. // 限制不超过总时长
  15759. if (this.duration > 0 && value > this.duration) {
  15760. value = this.duration;
  15761. }
  15762. await this.seekTo(value + "");
  15763. }
  15764. //下一个
  15765. private async playNext() {
  15766. this.lyricController.setLyric(null)
  15767. this.lyricControllerXF.setLyric(null)
  15768. this.lyricControllerSingle.setLyric(null)
  15769. Logger.info('heanup playNext', '========== playNext 开始 ==========');
  15770. Logger.info('heanup playNext', `isCastPlaying=${this.isCastPlaying}, castControllerWrapper存在=${!!this.castControllerWrapper}`);
  15771. if (!this.debounce()) {
  15772. Logger.warn('heanup playNext', 'debounce() 返回 false,退出');
  15773. return;
  15774. }
  15775. Logger.info('heanup playNext', `playType=${this.playType}`);
  15776. if (this.playType == 3) { //3:随机播放
  15777. Logger.info('heanup playNext', '随机播放模式');
  15778. await this.randomPlay()
  15779. return;
  15780. }
  15781. if (ArrayUtil.isNotEmpty(this.songList)) {
  15782. if (this.curIndex >= this.songList.length - 1) {
  15783. // playType=0 或 3: 尝试加载更多或循环
  15784. // playType=4: 不循环,检查是否是最后一首
  15785. if (this.playType == 4) {
  15786. // 连续播放不循环模式:到达最后一首时停止播放
  15787. Logger.info('heanup playNext', '连续播放不循环模式:已到达最后一首,停止播放');
  15788. ToastUtil.showToast('已经是最后一首了');
  15789. this.showRePlay();
  15790. this.currentTime = this.stringForTime(this.mIjkMediaPlayer.getDuration());
  15791. this.progressValue = this.PROGRESS_MAX_VALUE;
  15792. this.slideEnable = false;
  15793. this.stop();
  15794. return;
  15795. }
  15796. await this.tryLoadNextPageForPlayback();
  15797. }
  15798. if (this.curIndex >= this.songList.length - 1) {
  15799. // playType=4 不应该执行到这里,因为上面已经return了
  15800. this.curIndex = 0;
  15801. } else {
  15802. this.curIndex++;
  15803. }
  15804. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  15805. this.currentSong = this.songList[this.curIndex];
  15806. console.info('heanup playNext', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  15807. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  15808. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  15809. context: this.context,
  15810. autoParseMusicName: this.autoParseMusicName
  15811. });
  15812. this.artist = this.songList[this.curIndex].artist
  15813. this.name = this.songList[this.curIndex].name
  15814. //this.cover = this.songList[this.curIndex].pixelMapPath
  15815. console.info('heanup playNext 1 ', `this.isCastPlaying: ${ this.isCastPlaying}`)
  15816. console.info('heanup playNext 2 ', `this.castControllerWrapper: ${this.castControllerWrapper}`)
  15817. // 如果是投播模式,使用 CastController 播放下一首
  15818. if (this.castControllerWrapper) {
  15819. console.info('heanup playNext', '使用 CastController 播放下一首');
  15820. try {
  15821. const nextDuration = this.getSongDurationMs(this.currentSong);
  15822. if (nextDuration > 0) {
  15823. this.duration = nextDuration;
  15824. this.durationTime = Math.floor(nextDuration / 1000);
  15825. this.durationStringTime = secondToTime(this.durationTime);
  15826. this.totalTime = this.stringForTime(nextDuration);
  15827. this.avSessionController.setAVMetadataMusic(this.currentSong, nextDuration, this.lyricContent);
  15828. }
  15829. this.updateCastProgress(0);
  15830. await this.castControllerWrapper.playNext(this.songList, this.curIndex, this.videoUrl, nextDuration);
  15831. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  15832. console.info('heanup playNext', 'CastController 播放下一首成功');
  15833. return;
  15834. } catch (error) {
  15835. console.error('heanup playNext', `CastController 播放下一首失败: ${error}`);
  15836. // 如果投播失败,回退到本地播放
  15837. this.isCastPlaying = false;
  15838. }
  15839. }
  15840. // 本地播放器模式,需要先stop
  15841. this.CONTROL_PlayStatus = PlayStatus.INIT;
  15842. this.stop();
  15843. this.changeImageAnimation()
  15844. }
  15845. }
  15846. changeImageAnimation() {
  15847. if(this.openSkipSongAnimate){
  15848. // 第一步:淡出动画
  15849. this.getUIContext()?.animateTo({
  15850. duration: 500,
  15851. curve: Curve.EaseOut,
  15852. }, () => {
  15853. this.opacityValueImage = 0.1;
  15854. if(this.isCoverRectangle){
  15855. this.scaleValueImage = 0.88
  15856. }
  15857. });
  15858. // 第二步:切换图片后淡入
  15859. setTimeout(() => {
  15860. this.cover = this.songList[this.curIndex].pixelMapPath
  15861. this.getUIContext()?.animateTo({
  15862. duration: 500,
  15863. curve: Curve.EaseIn,
  15864. }, () => {
  15865. this.opacityValueImage = 1;
  15866. this.scaleValueImage = 1 // 图标恢复到原始大小
  15867. this.startPlayOrResumePlay()
  15868. });
  15869. }, 500);
  15870. }else{
  15871. this.cover = this.songList[this.curIndex].pixelMapPath
  15872. this.startPlayOrResumePlay()
  15873. }
  15874. }
  15875. // 内部方法:提前缓存下一首
  15876. private async preloadNextSongInternal(): Promise<void> {
  15877. // 随机模式下传递已播放索引集合
  15878. if (this.playType === 3) {
  15879. this.preloadNextRandomIndex = await preloadNextSongIfNeeded(
  15880. this.songList,
  15881. this.curIndex,
  15882. this.playType,
  15883. this.playedIndices
  15884. );
  15885. } else {
  15886. this.preloadNextRandomIndex = await preloadNextSongIfNeeded(
  15887. this.songList,
  15888. this.curIndex,
  15889. this.playType
  15890. );
  15891. }
  15892. }
  15893. // 存储已播放的歌曲索引
  15894. private playedIndices: Set<number> = new Set();
  15895. // 存储已播放的本地歌曲路径(随机播放去重用)
  15896. private playedLocalFilePaths: Set<string> = new Set();
  15897. // 随机播放模式下的播放历史栈(记录实际播放顺序,用于"上一首"功能)
  15898. private randomPlayHistory: VideoItem[] = [];
  15899. //随机播放
  15900. private async randomPlay() {
  15901. // if (!this.debounce()) {
  15902. // return;
  15903. // }
  15904. // 网盘模式: 渐进式扩展播放库的随机播放
  15905. // 通过检查当前歌曲类型判断是否为网盘音乐(而非modeType,因为不同网盘类型modeType不同)
  15906. const isCloudSong = this.currentSong && isRemoteCloudType(this.currentSong.type);
  15907. if (isCloudSong) {
  15908. // 阈值常量
  15909. const UNPLAYED_THRESHOLD = 10; // 剩余未播放歌曲阈值
  15910. const LOAD_MORE_PAGES = 3; // 每次加载页数
  15911. // 获取网盘播放列表
  15912. const navidromeList = getNavidromeVideoItems();
  15913. const webdavList = getWebdavVideoItems();
  15914. const isNavidrome = navidromeList.length > 0;
  15915. const remoteList = isNavidrome ? navidromeList : webdavList;
  15916. if (remoteList.length > 0) {
  15917. // 将当前歌加入历史栈
  15918. if (this.currentSong) {
  15919. this.randomPlayHistory.unshift(this.currentSong);
  15920. if (this.randomPlayHistory.length > 50) {
  15921. this.randomPlayHistory = this.randomPlayHistory.slice(0, 50);
  15922. }
  15923. // 标记当前歌曲为已播放
  15924. markAsPlayed(this.currentSong.filePath);
  15925. Logger.info(TAG, `randomPlay(网盘模式): 将当前歌加入历史栈, 栈大小: ${this.randomPlayHistory.length}`);
  15926. }
  15927. // 检查未播放歌曲数量(仅Navidrome支持渐进式加载)
  15928. let unplayedCount = isNavidrome ? getUnplayedCount() : remoteList.length;
  15929. const totalCount = remoteList.length;
  15930. const playedCount = isNavidrome ? getPlayedCount() : 0;
  15931. Logger.info(TAG, `randomPlay(网盘模式): 总数${totalCount}, 已播放${playedCount}, 未播放${unplayedCount}`);
  15932. // 如果未播放数量不足阈值,且还有更多数据,触发加载更多页
  15933. if (isNavidrome && unplayedCount < UNPLAYED_THRESHOLD && hasMoreData()) {
  15934. Logger.info(TAG, `randomPlay(网盘模式): 未播放(${unplayedCount})不足阈值(${UNPLAYED_THRESHOLD}),触发加载更多`);
  15935. const loadSuccess = await triggerLoadMoreSongs(LOAD_MORE_PAGES);
  15936. if (loadSuccess) {
  15937. // 重新获取未播放数量
  15938. unplayedCount = getUnplayedCount();
  15939. Logger.info(TAG, `randomPlay(网盘模式): 加载完成,未播放数量更新为${unplayedCount}`);
  15940. }
  15941. }
  15942. // 从未播放歌曲中随机选择
  15943. let candidates: VideoItem[];
  15944. if (isNavidrome) {
  15945. candidates = getUnplayedSongs();
  15946. // 如果全部播放完,重置已播放记录
  15947. if (candidates.length === 0) {
  15948. Logger.info(TAG, 'randomPlay(网盘模式): 全部播放完毕,重置已播放记录');
  15949. clearPlayedHistory();
  15950. // 排除当前歌曲
  15951. const currentFilePath = this.currentSong?.filePath;
  15952. candidates = currentFilePath
  15953. ? getNavidromeVideoItems().filter(v => v.filePath !== currentFilePath)
  15954. : getNavidromeVideoItems();
  15955. }
  15956. } else {
  15957. // WebDAV模式:简单排除当前歌曲
  15958. const currentFilePath = this.currentSong?.filePath;
  15959. candidates = currentFilePath
  15960. ? remoteList.filter(v => v.filePath !== currentFilePath)
  15961. : remoteList;
  15962. }
  15963. if (candidates.length > 0) {
  15964. const randomIndex = Math.floor(Math.random() * candidates.length);
  15965. const randomSong = candidates[randomIndex];
  15966. // 标记为已播放
  15967. if (isNavidrome) {
  15968. markAsPlayed(randomSong.filePath);
  15969. }
  15970. Logger.info(TAG, `randomPlay(网盘模式): 从${candidates.length}首候选中随机选择: ${randomSong.name}`);
  15971. // 将选中的歌曲加入播放列表(如果不存在)
  15972. let nextIndex = this.songList.findIndex(song => song.filePath === randomSong.filePath);
  15973. if (nextIndex < 0) {
  15974. this.songList = [...this.songList, randomSong];
  15975. this.sonDataSource.pushArrayData(this.songList);
  15976. nextIndex = this.songList.length - 1;
  15977. }
  15978. this.curIndex = nextIndex;
  15979. this.playedIndices.add(this.curIndex);
  15980. this.CONTROL_PlayStatus = PlayStatus.INIT;
  15981. this.stop();
  15982. this.currentSong = randomSong;
  15983. // 设置videoUrl
  15984. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  15985. context: this.context,
  15986. autoParseMusicName: this.autoParseMusicName
  15987. });
  15988. this.name = this.currentSong.name;
  15989. this.artist = this.currentSong.artist;
  15990. this.changeImageAnimation();
  15991. return;
  15992. }
  15993. Logger.warn(TAG, 'randomPlay(网盘模式): 无可用候选歌曲,回退到默认随机逻辑');
  15994. }
  15995. }
  15996. if (this.currentSong) {
  15997. // 将当前歌加入到随机播放历史栈(在切换到新歌之前)
  15998. this.randomPlayHistory.unshift(this.currentSong);
  15999. // 限制历史栈大小,避免无限增长
  16000. if (this.randomPlayHistory.length > 50) {
  16001. this.randomPlayHistory = this.randomPlayHistory.slice(0, 50);
  16002. }
  16003. Logger.info(TAG, `randomPlay: 将当前歌加入历史栈, 栈大小: ${this.randomPlayHistory.length}`);
  16004. const isCurrentRemote = isRemoteCloudType(this.currentSong.type);
  16005. const currentFilePath = this.currentSong.filePath;
  16006. if (isCurrentRemote) {
  16007. const remoteOptions: RandomSongQueryOptions = {
  16008. type: this.currentSong.type,
  16009. excludeFilePaths: currentFilePath ? [currentFilePath] : []
  16010. };
  16011. const randomRemoteSong = await this.table.queryRandomSong(remoteOptions);
  16012. if (randomRemoteSong) {
  16013. // 验证并修正webdav_account_id
  16014. if (randomRemoteSong.webdav_account_id) {
  16015. const manager = RemoteDriveManager.getInstance();
  16016. const account = await manager.getWebDavAccountById(randomRemoteSong.webdav_account_id);
  16017. if (!account) {
  16018. Logger.warn(TAG, `随机播放的歌曲账号ID无效: ${randomRemoteSong.webdav_account_id}, 尝试查找同类型账号`);
  16019. // 获取所有账号,查找相同类型的账号
  16020. const allAccounts = manager.getAllWebDavAccounts();
  16021. let foundAccount: WebDavAccount | null = null;
  16022. for (let i = 0; i < allAccounts.length; i++) {
  16023. if (allAccounts[i].webType === randomRemoteSong.type) {
  16024. foundAccount = allAccounts[i];
  16025. break;
  16026. }
  16027. }
  16028. if (foundAccount && foundAccount.id) {
  16029. Logger.info(TAG, `找到同类型账号,更新webdav_account_id: ${randomRemoteSong.webdav_account_id} -> ${foundAccount.id}`);
  16030. randomRemoteSong.webdav_account_id = foundAccount.id.toString();
  16031. // 更新数据库记录
  16032. await this.table.updateWebDavAccountId(randomRemoteSong.filePath, foundAccount.id.toString());
  16033. } else {
  16034. Logger.error(TAG, `无法找到类型为${randomRemoteSong.type}的账号,跳过此歌曲`);
  16035. return;
  16036. }
  16037. }
  16038. }
  16039. let nextIndex = this.songList.findIndex(song => song.filePath === randomRemoteSong.filePath);
  16040. if (nextIndex < 0) {
  16041. this.songList = [...this.songList, randomRemoteSong];
  16042. this.sonDataSource.pushArrayData(this.songList);
  16043. nextIndex = this.songList.length - 1;
  16044. }
  16045. this.curIndex = nextIndex;
  16046. this.playedIndices.add(this.curIndex);
  16047. this.CONTROL_PlayStatus = PlayStatus.INIT;
  16048. this.stop();
  16049. this.currentSong = randomRemoteSong;
  16050. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  16051. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  16052. context: this.context,
  16053. autoParseMusicName: this.autoParseMusicName
  16054. });
  16055. this.name = this.currentSong.name;
  16056. this.artist = this.currentSong.artist;
  16057. this.changeImageAnimation();
  16058. return;
  16059. }
  16060. Logger.warn(TAG, '随机播放未获取到网盘歌曲,回退到列表随机');
  16061. } else {
  16062. if (currentFilePath) {
  16063. this.playedLocalFilePaths.add(currentFilePath);
  16064. }
  16065. // 根据modeType构建不同的查询选项
  16066. const localOptions: RandomSongQueryOptions = {
  16067. type: CommonConstants.TYPE_LOCAL,
  16068. excludeFilePaths: Array.from(this.playedLocalFilePaths)
  16069. };
  16070. Logger.info(TAG, `randomPlay: 本地播放模式, modeType=${this.modeType}, currentPlaylistSongFilePaths.length=${this.currentPlaylistSongFilePaths.length}, currentPath=${this.currentPath}`);
  16071. // modeType==0: 文件夹模式,添加parentPath过滤
  16072. if (this.modeType === 0 && this.currentPath) {
  16073. localOptions.parentPath = this.currentPath;
  16074. Logger.info(TAG, `randomPlay: 文件夹模式, parentPath=${this.currentPath}`);
  16075. }
  16076. // modeType==4: 歌单模式,添加playlistSongFilePaths
  16077. else if (this.modeType === 4 && this.currentPlaylistSongFilePaths.length > 0) {
  16078. localOptions.playlistSongFilePaths = this.currentPlaylistSongFilePaths;
  16079. Logger.info(TAG, `randomPlay: 歌单模式,歌曲数量=${this.currentPlaylistSongFilePaths.length}, 前3首=${this.currentPlaylistSongFilePaths.slice(0, 3).join(', ')}`);
  16080. } else if (this.modeType === 4) {
  16081. Logger.warn(TAG, `randomPlay: 歌单模式但没有歌曲路径列表! currentPlaylistSongFilePaths.length=${this.currentPlaylistSongFilePaths.length}`);
  16082. }
  16083. let randomLocalSong = await this.table.queryRandomSong(localOptions);
  16084. if (!randomLocalSong) {
  16085. this.playedLocalFilePaths.clear();
  16086. if (currentFilePath) {
  16087. this.playedLocalFilePaths.add(currentFilePath);
  16088. }
  16089. const fallbackLocalOptions: RandomSongQueryOptions = {
  16090. type: CommonConstants.TYPE_LOCAL,
  16091. excludeFilePaths: currentFilePath ? [currentFilePath] : []
  16092. };
  16093. // fallback时也要保持modeType的过滤条件
  16094. if (this.modeType === 0 && this.currentPath) {
  16095. fallbackLocalOptions.parentPath = this.currentPath;
  16096. } else if (this.modeType === 4 && this.currentPlaylistSongFilePaths.length > 0) {
  16097. fallbackLocalOptions.playlistSongFilePaths = this.currentPlaylistSongFilePaths;
  16098. }
  16099. randomLocalSong = await this.table.queryRandomSong(fallbackLocalOptions);
  16100. }
  16101. if (randomLocalSong !== null) {
  16102. const selectedLocalSong = randomLocalSong;
  16103. let nextIndex = this.songList.findIndex(song => song.filePath === selectedLocalSong.filePath);
  16104. if (nextIndex < 0) {
  16105. this.songList = [...this.songList, selectedLocalSong];
  16106. this.sonDataSource.pushArrayData(this.songList);
  16107. nextIndex = this.songList.length - 1;
  16108. }
  16109. this.curIndex = nextIndex;
  16110. this.playedIndices.add(this.curIndex);
  16111. this.CONTROL_PlayStatus = PlayStatus.INIT;
  16112. this.stop();
  16113. this.currentSong = selectedLocalSong;
  16114. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  16115. context: this.context,
  16116. autoParseMusicName: this.autoParseMusicName
  16117. });
  16118. this.name = this.currentSong.name;
  16119. this.artist = this.currentSong.artist;
  16120. this.changeImageAnimation();
  16121. return;
  16122. }
  16123. Logger.warn(TAG, '随机播放未获取到本地歌曲,回退到列表随机');
  16124. }
  16125. }
  16126. if (ArrayUtil.isNotEmpty(this.songList)) {
  16127. if (this.curIndex >= 0 && this.curIndex < this.songList.length) {
  16128. this.playedIndices.add(this.curIndex);
  16129. }
  16130. if (this.songList.length > 3) {
  16131. // 优先使用预缓存的随机索引(仅网盘播放时)
  16132. const nextSong = this.songList[this.preloadNextRandomIndex >= 0 ? this.preloadNextRandomIndex : 0];
  16133. const isNextRemote = nextSong && isRemoteCloudType(nextSong.type);
  16134. const isCurrentRemote = this.currentSong && isRemoteCloudType(this.currentSong.type);
  16135. if (this.preloadNextRandomIndex >= 0 && this.preloadNextRandomIndex < this.songList.length && isNextRemote && isCurrentRemote) {
  16136. Logger.info('heanup randomPlay', `使用预缓存的随机索引: ${this.preloadNextRandomIndex} (网盘播放)`);
  16137. this.curIndex = this.preloadNextRandomIndex;
  16138. this.playedIndices.add(this.curIndex);
  16139. this.preloadNextRandomIndex = -1; // 重置预缓存索引
  16140. // 立即预缓存下一首,避免下次点击时没有预缓存
  16141. void this.preloadNextSongInternal();
  16142. } else {
  16143. // 如果没有预缓存索引,则正常随机选择
  16144. // 如果所有歌曲都播放过一次,清空已播放索引集合
  16145. if (this.playedIndices.size === this.songList.length) {
  16146. this.playedIndices.clear();
  16147. }
  16148. // 随机选择一个未播放的歌曲索引
  16149. let newIndex: number;
  16150. // 添加超时机制防止无限循环
  16151. let attempt = 0;
  16152. const maxAttempts = 100; // 根据需求调整
  16153. do {
  16154. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  16155. attempt++;
  16156. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  16157. if (attempt >= maxAttempts) {
  16158. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  16159. newIndex = Math.floor(Math.random() * this.songList.length);
  16160. }
  16161. this.curIndex = newIndex;
  16162. this.playedIndices.add(newIndex);
  16163. }
  16164. } else {
  16165. // 当歌曲数量小于或等于3时,直接播放下一首
  16166. if (this.curIndex == this.songList.length - 1) {
  16167. this.curIndex = 0;
  16168. } else {
  16169. this.curIndex++;
  16170. }
  16171. }
  16172. this.CONTROL_PlayStatus = PlayStatus.INIT;
  16173. this.stop();
  16174. this.currentSong = this.songList[this.curIndex];
  16175. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  16176. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  16177. context: this.context,
  16178. autoParseMusicName: this.autoParseMusicName
  16179. });
  16180. this.name = this.songList[this.curIndex].name;
  16181. this.artist = this.songList[this.curIndex].artist
  16182. // this.cover = this.songList[this.curIndex].pixelMapPath
  16183. this.changeImageAnimation()
  16184. // 预缓存下一首(包括网盘和本地)
  16185. void this.preloadNextSongInternal();
  16186. }
  16187. }
  16188. private async playIndex(index: number) {
  16189. if (!this.debounce()) {
  16190. return;
  16191. }
  16192. if (ArrayUtil.isNotEmpty(this.songList)) {
  16193. this.curIndex = index;
  16194. this.currentSong = this.songList[index];
  16195. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  16196. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  16197. context: this.context,
  16198. autoParseMusicName: this.autoParseMusicName
  16199. });
  16200. this.name = this.currentSong.name
  16201. this.artist = this.currentSong.artist
  16202. // 如果是投播模式,需要为投播设备准备当前歌曲
  16203. if (this.castController && this.isCastPlaying) {
  16204. Logger.info('heanup playIndex', '投播模式播放指定歌曲,不调用本地stop()');
  16205. this.initQueueItem();
  16206. await this.prepare();
  16207. this.cover = this.currentSong.pixelMapPath;
  16208. return;
  16209. }
  16210. // 本地播放器模式,需要先stop
  16211. this.CONTROL_PlayStatus = PlayStatus.INIT;
  16212. this.stop();
  16213. this.changeImageAnimation()
  16214. }
  16215. }
  16216. //上一个
  16217. private async playPrevious() {
  16218. if (!this.debounce()) {
  16219. return;
  16220. }
  16221. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  16222. this.randomModePlayFromHistory()
  16223. return;
  16224. }
  16225. if (this.curIndex == 0) {
  16226. this.curIndex = this.songList.length - 1;
  16227. } else {
  16228. this.curIndex--;
  16229. }
  16230. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  16231. this.currentSong = this.songList[this.curIndex];
  16232. Logger.info('heanup playPrevious', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  16233. // 验证并修正webdav_account_id(针对远程类型歌曲)
  16234. if (isRemoteCloudType(this.currentSong.type) && this.currentSong.webdav_account_id) {
  16235. const manager = RemoteDriveManager.getInstance();
  16236. const account = await manager.getWebDavAccountById(this.currentSong.webdav_account_id);
  16237. if (!account) {
  16238. Logger.warn(TAG, `playPrevious: 歌曲账号ID无效: ${this.currentSong.webdav_account_id}, 尝试查找同类型账号`);
  16239. // 获取所有账号,查找相同类型的账号
  16240. const allAccounts = manager.getAllWebDavAccounts();
  16241. let foundAccount: WebDavAccount | null = null;
  16242. for (let i = 0; i < allAccounts.length; i++) {
  16243. if (allAccounts[i].webType === this.currentSong.type) {
  16244. foundAccount = allAccounts[i];
  16245. break;
  16246. }
  16247. }
  16248. if (foundAccount && foundAccount.id) {
  16249. Logger.info(TAG, `playPrevious: 找到同类型账号,更新webdav_account_id: ${this.currentSong.webdav_account_id} -> ${foundAccount.id}`);
  16250. this.currentSong.webdav_account_id = foundAccount.id.toString();
  16251. // 更新数据库记录
  16252. await this.table.updateWebDavAccountId(this.currentSong.filePath, foundAccount.id.toString());
  16253. } else {
  16254. Logger.error(TAG, `playPrevious: 无法找到类型为${this.currentSong.type}的账号,跳过此歌曲`);
  16255. // 跳过无效账号的歌曲,继续查找上一首
  16256. if (this.curIndex == 0) {
  16257. this.curIndex = this.songList.length - 1;
  16258. } else {
  16259. this.curIndex--;
  16260. }
  16261. this.currentSong = this.songList[this.curIndex];
  16262. }
  16263. }
  16264. }
  16265. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  16266. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  16267. context: this.context,
  16268. autoParseMusicName: this.autoParseMusicName
  16269. });
  16270. this.name = this.songList[this.curIndex].name
  16271. this.artist = this.songList[this.curIndex].artist
  16272. // 如果是投播模式,使用 CastController 切换上一首
  16273. if (this.castControllerWrapper) {
  16274. Logger.info('heanup playPrevious', '投播模式播放上一首,不调用本地stop()');
  16275. try {
  16276. const prevDuration = this.getSongDurationMs(this.currentSong);
  16277. if (prevDuration > 0) {
  16278. this.duration = prevDuration;
  16279. this.durationTime = Math.floor(prevDuration / 1000);
  16280. this.durationStringTime = secondToTime(this.durationTime);
  16281. this.totalTime = this.stringForTime(prevDuration);
  16282. this.avSessionController.setAVMetadataMusic(this.currentSong, prevDuration, this.lyricContent);
  16283. }
  16284. this.updateCastProgress(0);
  16285. await this.castControllerWrapper.playPrevious(this.songList, this.curIndex, this.videoUrl, prevDuration);
  16286. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  16287. } catch (error) {
  16288. Logger.error('heanup playPrevious', `CastController 播放上一首失败: ${error}`);
  16289. this.isCastPlaying = false;
  16290. }
  16291. this.cover = this.songList[this.curIndex].pixelMapPath;
  16292. return;
  16293. }
  16294. // 本地播放器模式,需要先stop
  16295. this.CONTROL_PlayStatus = PlayStatus.INIT;
  16296. this.stop();
  16297. this.changeImageAnimation()
  16298. }
  16299. //随机播放模式下点击上一首: 播放刚刚播放过的那一首
  16300. private async randomModePlayFromHistory() {
  16301. if (this.randomPlayHistory.length >= 1) {
  16302. // 播放历史栈的第一首(刚刚播放过的)
  16303. const prevSong = this.randomPlayHistory[0];
  16304. Logger.info('heanup randomModePlayFromHistory', `从随机播放历史栈获取歌曲: ${prevSong.name}, type: ${prevSong.type}, 栈大小: ${this.randomPlayHistory.length}`);
  16305. // 从栈中移除这首歌(因为即将播放它,它应该成为当前歌,而不是历史)
  16306. this.randomPlayHistory.shift();
  16307. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  16308. this.CONTROL_PlayStatus = PlayStatus.INIT;
  16309. this.stop();
  16310. // 验证并修正webdav_account_id(针对远程类型歌曲)
  16311. if (isRemoteCloudType(prevSong.type) && prevSong.webdav_account_id) {
  16312. const manager = RemoteDriveManager.getInstance();
  16313. const account = await manager.getWebDavAccountById(prevSong.webdav_account_id);
  16314. if (!account) {
  16315. Logger.warn(TAG, `randomModePlayFromHistory: 歌曲账号ID无效: ${prevSong.webdav_account_id}, 尝试查找同类型账号`);
  16316. const allAccounts = manager.getAllWebDavAccounts();
  16317. let foundAccount: WebDavAccount | null = null;
  16318. for (let i = 0; i < allAccounts.length; i++) {
  16319. if (allAccounts[i].webType === prevSong.type) {
  16320. foundAccount = allAccounts[i];
  16321. break;
  16322. }
  16323. }
  16324. if (foundAccount && foundAccount.id) {
  16325. Logger.info(TAG, `randomModePlayFromHistory: 找到同类型账号,更新webdav_account_id: ${prevSong.webdav_account_id} -> ${foundAccount.id}`);
  16326. prevSong.webdav_account_id = foundAccount.id.toString();
  16327. await this.table.updateWebDavAccountId(prevSong.filePath, foundAccount.id.toString());
  16328. } else {
  16329. Logger.error(TAG, `randomModePlayFromHistory: 无法找到类型为${prevSong.type}的账号`);
  16330. // 无法播放这首歌,继续尝试下一首历史记录
  16331. if (this.randomPlayHistory.length >= 1) {
  16332. this.randomModePlayFromHistory();
  16333. return;
  16334. } else {
  16335. // 历史记录为空,无法继续
  16336. ToastUtil.showToast('没有更多历史记录');
  16337. return;
  16338. }
  16339. }
  16340. }
  16341. }
  16342. this.currentSong = prevSong;
  16343. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  16344. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  16345. context: this.context,
  16346. autoParseMusicName: this.autoParseMusicName
  16347. });
  16348. this.cover = this.currentSong.pixelMapPath
  16349. this.artist = this.currentSong.artist
  16350. this.name = this.currentSong.name;
  16351. console.info('onecold startPlayOrResumePlay randomModePlayFromHistory')
  16352. this.startPlayOrResumePlay();
  16353. } else {
  16354. ToastUtil.showToast('随机播放模式暂无历史记录');
  16355. }
  16356. }
  16357. debounce() {
  16358. const delay = 600;
  16359. let cur = new Date().getTime();
  16360. if (cur - this.last > delay) {
  16361. this.last = cur;
  16362. return true;
  16363. }
  16364. return false;
  16365. }
  16366. /**
  16367. * Sets whether the screen is a constant based on the playback status.
  16368. */
  16369. watchStatus() {
  16370. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  16371. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  16372. this.windowClass.setWindowKeepScreenOn(true);
  16373. } else {
  16374. this.windowClass.setWindowKeepScreenOn(false);
  16375. }
  16376. }
  16377. /**
  16378. * Volume gesture method onActionStart.
  16379. *
  16380. * @param event Gesture event.
  16381. */
  16382. private customDialogComponentIdMM: number = 0
  16383. @Builder
  16384. customDialogComponentMM() {
  16385. Column() {
  16386. Row() {
  16387. Blank()
  16388. Text('验证密码')
  16389. .fontSize(22)
  16390. .fontColor($r('app.color.pri_bg'))
  16391. .margin({ top: 18 })
  16392. Blank()
  16393. Image($r('app.media.close'))
  16394. .fillColor(Color.White)
  16395. .margin({ top: 18, right: 18 })
  16396. .width(20)
  16397. .onClick(() => {
  16398. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  16399. })
  16400. }
  16401. .width('100%') // 使Row占据整个宽度
  16402. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  16403. Verify({
  16404. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  16405. });
  16406. }.height('60%')
  16407. .backgroundColor($r('app.color.index_background'))
  16408. .justifyContent(FlexAlign.SpaceBetween)
  16409. }
  16410. private handleVerifyCompleted(isSuccess: boolean) {
  16411. if (isSuccess) {
  16412. console.log('验证成功');
  16413. // 在这里处理验证成功后的逻辑
  16414. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  16415. this.currentPath = this.lockPath
  16416. this.getSortedFiles(this.currentPath)
  16417. } else {
  16418. // console.log('验证失败');
  16419. ToastUtil.showToast('验证失败')
  16420. }
  16421. }
  16422. private showVerifyDialog() {
  16423. promptAction.openCustomDialog({
  16424. transition: TransitionEffect.asymmetric(
  16425. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  16426. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  16427. ,
  16428. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  16429. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  16430. ),
  16431. builder: () => {
  16432. this.customDialogComponentMM()
  16433. },
  16434. isModal: true,
  16435. autoCancel: true,
  16436. maskColor: Color.Transparent,
  16437. alignment: DialogAlignment.Bottom,
  16438. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  16439. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  16440. console.log("dialog onWillDismiss")
  16441. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  16442. dismissDialogAction.dismiss()
  16443. }
  16444. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  16445. dismissDialogAction.dismiss()
  16446. }
  16447. }
  16448. }).then((dialogId: number) => {
  16449. this.customDialogComponentIdMM = dialogId
  16450. })
  16451. }
  16452. //左滑操作 移动文件 重命名 删除等操作
  16453. @Builder
  16454. DeleteButton(item: VideoItem, index: number, filePath: string) {
  16455. Row() {
  16456. //加入收藏
  16457. Button() {
  16458. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  16459. .fillColor(Color.White)
  16460. .width(20)
  16461. }
  16462. .width(40)
  16463. .height(40)
  16464. .type(ButtonType.Circle)
  16465. .backgroundColor(this.themeColor)
  16466. .margin(5)
  16467. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  16468. .onClick(() => {
  16469. if (item) {
  16470. this.doFav(item)
  16471. }
  16472. })
  16473. //加入下一首播放
  16474. Button() {
  16475. Image($r('app.media.next_to_play'))
  16476. .fillColor(Color.White)
  16477. .width(20)
  16478. }
  16479. .width(40)
  16480. .height(40)
  16481. .type(ButtonType.Circle)
  16482. .backgroundColor(this.themeColor)
  16483. .margin(5)
  16484. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  16485. .onClick(() => {
  16486. this.addToNextPlay(item);
  16487. })
  16488. //复制文件
  16489. Button() {
  16490. Image($r('app.media.copy'))
  16491. .fillColor(Color.White)
  16492. .width(20)
  16493. }
  16494. .width(40)
  16495. .height(40)
  16496. .type(ButtonType.Circle)
  16497. .backgroundColor(this.themeColor)
  16498. .margin(5)
  16499. .id(filePath + 'copy')
  16500. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  16501. .onClick(() => {
  16502. this.showCopyDialog(false, item, index, filePath + 'copy');
  16503. })
  16504. //移动文件
  16505. Button() {
  16506. Image($r('app.media.cut'))
  16507. .fillColor(Color.White)
  16508. .width(20)
  16509. }
  16510. .width(40)
  16511. .height(40)
  16512. .type(ButtonType.Circle)
  16513. .backgroundColor(this.themeColor)
  16514. .margin(5)
  16515. .id(filePath)
  16516. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  16517. .onClick(() => {
  16518. this.showCutDialog(false, item, index, filePath);
  16519. })
  16520. Button() {
  16521. Image($r('app.media.cut_current'))
  16522. .fillColor(Color.White)
  16523. .width(20)
  16524. }
  16525. .width(40)
  16526. .height(40)
  16527. .type(ButtonType.Circle)
  16528. .backgroundColor(this.themeColor)
  16529. .margin(5)
  16530. .id(filePath + 'current')
  16531. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  16532. (this.isHasDir ? Visibility.Visible : Visibility.None))
  16533. .onClick(() => {
  16534. this.showCutDialog(true, item, index, filePath + 'current');
  16535. })
  16536. //重命名
  16537. Button() {
  16538. Image($r('app.media.rename2'))
  16539. .fillColor(Color.White)
  16540. .width(20)
  16541. }
  16542. .width(40)
  16543. .height(40)
  16544. .type(ButtonType.Circle)
  16545. .backgroundColor(this.themeColor)
  16546. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  16547. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  16548. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  16549. .margin(5)
  16550. .onClick(() => {
  16551. this.showReNameDialog(item, index + '', filePath)
  16552. })
  16553. Button() {
  16554. Image($r('app.media.delete2'))
  16555. .fillColor(Color.White)
  16556. .width(20)
  16557. }
  16558. .width(40)
  16559. .height(40)
  16560. .type(ButtonType.Circle)
  16561. .backgroundColor(this.themeColor)
  16562. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  16563. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  16564. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  16565. .margin(5)
  16566. .onClick(() => {
  16567. this.selectedFiles.push(item)
  16568. this.showWarnIsDelete()
  16569. // this.showWarnIsDeleteFile(item, index + '', filePath)
  16570. })
  16571. Button() {
  16572. Image($r('app.media.share2'))
  16573. .fillColor(Color.White)
  16574. .width(20)
  16575. }
  16576. .width(40)
  16577. .height(40)
  16578. .type(ButtonType.Circle)
  16579. .backgroundColor(this.themeColor)
  16580. .margin(5)
  16581. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  16582. .onClick(() => {
  16583. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  16584. })
  16585. }
  16586. }
  16587. /**
  16588. * 穿山甲banner广告
  16589. */
  16590. // private declare bannerAd: CSJNativeExpressAd;
  16591. // @State private status: string = "未加载"
  16592. // @State private isShowAd: boolean = false
  16593. // private declare mAdSlot: AdSlot;
  16594. // private mBiddingAdm = '' //服务端bidding才需要设置
  16595. // private expressLoadAdListener: NativeExpressAdListener = {
  16596. // /**
  16597. // * 加载失败的回调
  16598. // *
  16599. // * @param code
  16600. // * @param message
  16601. // */
  16602. // onError: (code: number, message: string) => {
  16603. // console.error("加载广告失败,code=" + code + ",message=" + message);
  16604. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  16605. // },
  16606. //
  16607. // /**
  16608. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  16609. // *
  16610. // * @param ads 返回的广告列表
  16611. // */
  16612. //
  16613. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  16614. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  16615. // if (ads && ads.length > 0) {
  16616. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  16617. // ad.setExpressInteractionListener({
  16618. // /**
  16619. // *广告的点击回调
  16620. // * @param type 广告的交互类型
  16621. // */
  16622. // onAdClicked: (type: number) => {
  16623. // console.log("BannerExpressAdPage==onAdClicked......");
  16624. // },
  16625. //
  16626. // /**
  16627. // * 广告的展示回调 每个广告仅回调一次
  16628. // * @param type 广告的交互类型
  16629. // */
  16630. // onAdShow: (type: number) => {
  16631. // console.log("BannerExpressAdPage==onAdShow......");
  16632. // },
  16633. //
  16634. // /**
  16635. // * 模板渲染失败
  16636. // */
  16637. // onRenderFail: (code: number, msg: string) => {
  16638. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  16639. // },
  16640. //
  16641. // /**
  16642. // * 模板渲染成功
  16643. // * @param width 返回view的宽 单位 vp
  16644. // * @param height 返回view的高 单位 vp
  16645. // */
  16646. // onRenderSuccess: (width: number, height: number) => {
  16647. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  16648. // this.bannerAd = ad;
  16649. // this.status = "广告加载完成待展示";
  16650. //
  16651. // this.showBannerAd()
  16652. // }
  16653. // })
  16654. // //渲染广告
  16655. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  16656. // this.setDislikeCallback(ad); //设置dislike
  16657. // ad.render(this.getUIContext())
  16658. // this.status = "广告加载中...";
  16659. // });
  16660. // }
  16661. // }
  16662. // }
  16663. //
  16664. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  16665. // ad.setDislikeCallback({
  16666. // /**
  16667. // * dislike show
  16668. // */
  16669. // onShow: () => {
  16670. // console.log("BannerExpressAdPage==dislike......show");
  16671. // },
  16672. //
  16673. // /**
  16674. // * @param position 选择的位置
  16675. // * @param value 选择的内容
  16676. // * @param enforceRemove 是否强制关闭广告
  16677. // */
  16678. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  16679. // this.isShowAd = false;
  16680. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  16681. // ",enforce=" + enforceRemove);
  16682. // },
  16683. //
  16684. // /**
  16685. // * 点击取消
  16686. // */
  16687. // onCancel: () => {
  16688. // console.log("BannerExpressAdPage==dislike......onCancel");
  16689. // }
  16690. //
  16691. // })
  16692. // }
  16693. /**
  16694. * 加载Banner广告
  16695. */
  16696. loadBannerAd(rit: string) {
  16697. // if (Utility.isNoble()) {
  16698. // return
  16699. // }
  16700. // if (!Utility.isPassInstallTime(2)) {
  16701. // return
  16702. // }
  16703. // this.isShowAd = false;
  16704. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  16705. // this.mAdSlot = new AdSlotBuilder()
  16706. // .setCodeId(rit)
  16707. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  16708. // .setAdCount(1)
  16709. // .setBidAdm(this.mBiddingAdm)
  16710. // .build()
  16711. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  16712. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  16713. // this.status = "广告加载中..."
  16714. }
  16715. /**
  16716. * 展示Banner广告
  16717. */
  16718. // showBannerAd() {
  16719. // if (!this.bannerAd) {
  16720. // return
  16721. // }
  16722. // this.isShowAd = true
  16723. // this.status = "已展示"
  16724. // }
  16725. /**
  16726. * 穿山甲广告代码结束
  16727. */
  16728. /**
  16729. * 处理歌单播放请求
  16730. */
  16731. private syncWebdavQueueWithoutRestart(): void {
  16732. try {
  16733. if (!this.currentSong || !isWebDavType(this.currentSong.type)) {
  16734. return;
  16735. }
  16736. const webdavList = getWebdavVideoItems();
  16737. if (!ArrayUtil.isNotEmpty(webdavList)) {
  16738. return;
  16739. }
  16740. const currentPath = this.currentSong.filePath;
  16741. let targetIndex = webdavList.findIndex((item: VideoItem) => item.filePath === currentPath);
  16742. if (targetIndex < 0) {
  16743. const memoryIndex = getWebdavCurrentPlayIndex();
  16744. if (memoryIndex >= 0 && memoryIndex < webdavList.length) {
  16745. targetIndex = memoryIndex;
  16746. }
  16747. }
  16748. if (targetIndex < 0) {
  16749. targetIndex = 0;
  16750. }
  16751. this.songList = [...webdavList];
  16752. this.currentSongList = [...webdavList];
  16753. this.sonDataSource.pushArrayData(this.songList);
  16754. this.currentPlaylistSongFilePaths = this.songList.map(song => song.filePath);
  16755. this.curIndex = targetIndex;
  16756. PreferencesUtil.putSync('LastMusicList', this.songList);
  16757. Logger.info(TAG, `WebDAV播放队列已刷新,当前索引=${this.curIndex}, 队列长度=${this.songList.length}`);
  16758. } catch (error) {
  16759. Logger.error(TAG, `刷新WebDAV播放队列失败: ${(error as Error).message}`);
  16760. }
  16761. }
  16762. private async handlePlaylistPlayRequest(playlistId: string, playlistName:
  16763. string, songFilePaths: string[], startIndex: number, isJump: boolean, songCount?: number) {
  16764. try {
  16765. const totalCount = songCount ?? songFilePaths.length;
  16766. Logger.info(`heanup 处理歌单播放请求: ${playlistName}, 已加载: ${songFilePaths.length}, 服务端总数: ${totalCount}, 开始索引: ${startIndex}`)
  16767. // 检查是否为WebDAV播放请求
  16768. if (playlistId === 'webdav-playlist') {
  16769. Logger.info(`heanup 检测到WebDAV播放请求,从内存读取videoItems`)
  16770. // 从全局内存读取videoItems数据
  16771. const videoItems = getWebdavVideoItems();
  16772. const currentPlayIndex = getWebdavCurrentPlayIndex();
  16773. Logger.info(`heanup 从内存读取到WebDAV歌曲列表,长度:${videoItems.length},索引:${currentPlayIndex}`)
  16774. if (videoItems && videoItems.length > 0) {
  16775. // 验证webdav_account_id设置情况
  16776. const accountIds = videoItems.map(item => item.webdav_account_id).filter(id => id);
  16777. Logger.info(`heanup 有 ${accountIds.length}/${videoItems.length} 首歌曲设置了webdav_account_id`)
  16778. if(isJump){
  16779. this.setShowPlayTrue()//显示播放页
  16780. }
  16781. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName, totalCount)
  16782. return
  16783. } else {
  16784. return
  16785. }
  16786. }
  16787. if (playlistId === 'navidrome-playlist') {
  16788. Logger.info(`heanup 检测到Navidrome播放请求,从内存读取videoItems`);
  16789. const videoItems = getNavidromeVideoItems();
  16790. const currentPlayIndex = getNavidromeCurrentPlayIndex();
  16791. Logger.info(`heanup Navidrome歌曲列表长度: ${videoItems.length}, 服务端总数: ${totalCount}`);
  16792. if (videoItems && videoItems.length > 0) {
  16793. if(isJump){
  16794. this.setShowPlayTrue()//显示播放页
  16795. }
  16796. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName, totalCount);
  16797. return;
  16798. } else {
  16799. Logger.warn('heanup Navidrome播放请求缺少歌曲数据');
  16800. return;
  16801. }
  16802. }
  16803. // 从数据库重新加载这些歌曲,使用索引记录位置以保持顺序
  16804. const songMap: Map<number, VideoItem> = new Map()
  16805. let completedQueries = 0
  16806. Logger.info(`heanup 开始从数据库查询 ${songFilePaths.length} 首歌曲`)
  16807. // 遍历所有文件路径,使用索引记录位置
  16808. for (let i = 0; i < songFilePaths.length; i++) {
  16809. const filePath = songFilePaths[i]
  16810. const index = i
  16811. // Logger.info(`heanup 正在查询歌曲[${index}]: ${filePath}`)
  16812. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  16813. const queryPromise = this.table.queryVideoByFilePath(filePath)
  16814. // Logger.info(`heanup 创建了查询Promise,开始等待结果[${index}]: ${filePath}`)
  16815. queryPromise.then((videoItem) => {
  16816. completedQueries++
  16817. // Logger.info(`heanup 查询Promise返回结果[${index}]: ${filePath}, 找到歌曲: ${videoItem ? videoItem.name : 'null'}`)
  16818. if (videoItem) {
  16819. // 使用索引作为key保存到Map中,保持原始顺序
  16820. songMap.set(index, videoItem)
  16821. // Logger.info(`heanup 从数据库找到歌曲[${index}]: ${videoItem.name} (${completedQueries}/${songFilePaths.length})`)
  16822. } else {
  16823. Logger.warn(`heanup 数据库中未找到歌曲[${index}]: ${filePath} (${completedQueries}/${songFilePaths.length})`)
  16824. }
  16825. // 检查是否所有歌曲都已加载完成
  16826. if (completedQueries === songFilePaths.length) {
  16827. // Logger.info(`heanup 所有数据库查询完成,共找到 ${songMap.size} 首歌曲`)
  16828. // 按照索引顺序重建歌曲数组
  16829. const songs: VideoItem[] = []
  16830. for (let j = 0; j < songFilePaths.length; j++) {
  16831. const song = songMap.get(j)
  16832. if (song) {
  16833. songs.push(song)
  16834. // Logger.info(`heanup 按顺序添加歌曲[${j}]: ${song.name}`)
  16835. }
  16836. }
  16837. Logger.info(`heanup 最终歌曲列表顺序: ${songs.map((s, idx) => `[${idx}]${s.name}`).join(', ')}`)
  16838. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  16839. }
  16840. }).catch((error: Error) => {
  16841. completedQueries++
  16842. Logger.error(`heanup 查询歌曲失败[${index}]: ${filePath}, 错误: ${error.message} (${completedQueries}/${songFilePaths.length})`)
  16843. // 即使出错也要检查是否完成所有查询
  16844. if (completedQueries === songFilePaths.length) {
  16845. Logger.info(`heanup 所有数据库查询完成(包含错误),共找到 ${songMap.size} 首歌曲`)
  16846. // 按照索引顺序重建歌曲数组
  16847. const songs: VideoItem[] = []
  16848. for (let j = 0; j < songFilePaths.length; j++) {
  16849. const song = songMap.get(j)
  16850. if (song) {
  16851. songs.push(song)
  16852. }
  16853. }
  16854. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  16855. }
  16856. })
  16857. }
  16858. } catch (error) {
  16859. Logger.error('heanup 处理简化歌单播放请求失败: ' + error)
  16860. ToastUtil.showToast('播放失败')
  16861. }
  16862. }
  16863. /**
  16864. * 完成歌单加载并开始播放
  16865. */
  16866. private finishLoadingPlaylist(songs: VideoItem[], startIndex: number, playlistName: string, totalCount?: number) {
  16867. if (songs.length === 0) {
  16868. Logger.error('heanup 没有找到任何可播放的歌曲')
  16869. ToastUtil.showToast('没有找到可播放的歌曲')
  16870. return
  16871. }
  16872. this.songList = songs
  16873. this.currentSongList = songs // 同步更新 currentSongList
  16874. this.sonDataSource.pushArrayData(songs)
  16875. this.sonDataSource.notifyDataReload()
  16876. this.curIndex = startIndex
  16877. // 保存歌单的歌曲路径列表,用于随机播放
  16878. this.currentPlaylistSongFilePaths = songs.map(song => song.filePath);
  16879. const actualTotal = totalCount ?? songs.length;
  16880. // 如果是网盘播放,保存服务端总数到全局存储
  16881. if (totalCount && totalCount > 0 && songs.length > 0) {
  16882. const firstSong = songs[0];
  16883. if (firstSong && (isNavidromeType(firstSong.type) ||
  16884. isJellyfinType(firstSong.type) ||
  16885. isEmbyType(firstSong.type) ||
  16886. isAudioStationType(firstSong.type) ||
  16887. isPlexType(firstSong.type) ||
  16888. isDaoLiYuType(firstSong.type))) {
  16889. setNavidromeTotalCount(totalCount);
  16890. Logger.info('heanup finishLoadingPlaylist', `已保存服务端总数到全局存储: ${totalCount}`);
  16891. }
  16892. }
  16893. Logger.info('heanup finishLoadingPlaylist', `保存歌单歌曲路径列表,已加载=${this.currentPlaylistSongFilePaths.length}, 服务端总数=${actualTotal}`);
  16894. if (songs[startIndex]) {
  16895. // 确保当前播放的歌曲也更新到存储
  16896. AppStorage.setOrCreate('currentSong', songs[startIndex])
  16897. // 设置isFromSonPlayList=true,避免doPlay方法重新从全局列表构建播放列表
  16898. this.doPlay(songs[startIndex], startIndex, true)
  16899. }
  16900. PreferencesUtil.putSync('LastMusicList', this.songList)
  16901. // ToastUtil.showToast(`开始播放歌单: ${playlistName}`)
  16902. }
  16903. }
  16904. //视频气泡窗口的布局
  16905. @Builder
  16906. function customPopupBuilder(dataBu: BubbleBean) {
  16907. List() {
  16908. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  16909. ListItem() {
  16910. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  16911. Row() {
  16912. Column() {
  16913. Image(dataBu.imageRes[index])
  16914. .height(28)
  16915. .fillColor(dataBu.color)
  16916. .alignSelf(ItemAlign.Center)
  16917. }
  16918. .width(32)
  16919. Text(item)
  16920. .padding({
  16921. top: 10,
  16922. bottom: 10,
  16923. right: 10,
  16924. left: 10
  16925. })
  16926. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  16927. .textAlign(TextAlign.Start)
  16928. .width("100%")
  16929. }
  16930. }
  16931. .backgroundColor($r('app.color.settings_background_main'))
  16932. .margin({ top: 6, bottom: 6 })
  16933. }
  16934. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  16935. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  16936. TransitionEffect.scale({ x: 0, y: 0 })))
  16937. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  16938. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  16939. .onClick(() => {
  16940. dataBu.onItemClick?.(index)
  16941. })
  16942. })
  16943. }
  16944. .scrollBar(BarState.Off)
  16945. .width(120)
  16946. .divider({
  16947. strokeWidth: 1,
  16948. color: "#22FFFFFF"
  16949. })
  16950. }
  16951. // Function to calculate a hash for the file list
  16952. function simpleHash(fileList: string[]): string {
  16953. let hash = 0;
  16954. const str = fileList.join(',');
  16955. for (let i = 0; i < str.length; i++) {
  16956. const char = str.charCodeAt(i);
  16957. hash = (hash << 5) - hash + char;
  16958. hash |= 0; // Convert to 32bit integer
  16959. }
  16960. return hash.toString();
  16961. }
  16962. interface MoreItem {
  16963. id: number;
  16964. image: Resource;
  16965. title: string;
  16966. }
  16967. //视频气泡窗口的布局
  16968. @Builder
  16969. function cutPopupBuilder(dataBu: BubbleBean) {
  16970. Column() {
  16971. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  16972. .padding({
  16973. top: 10,
  16974. bottom: 10,
  16975. right: 10,
  16976. left: 10
  16977. })
  16978. .textAlign(TextAlign.Start)
  16979. .width(160)
  16980. .fontWeight(666)
  16981. .fontSize(16)
  16982. List() {
  16983. ForEach(dataBu.data, (item: string, index: number) => {
  16984. ListItem() {
  16985. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  16986. Row() {
  16987. Column() {
  16988. Image($r('app.media.music_group'))
  16989. .height(28)
  16990. .fillColor(dataBu.color)
  16991. .alignSelf(ItemAlign.Center)
  16992. }
  16993. .width(32)
  16994. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  16995. .padding({
  16996. top: 10,
  16997. bottom: 10,
  16998. right: 10,
  16999. left: 10
  17000. })
  17001. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  17002. .fontSize(15)
  17003. }
  17004. }
  17005. .backgroundColor(Color.Transparent)
  17006. .margin({ top: 7, bottom: 7 })
  17007. }
  17008. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  17009. .animation({ duration: 500 }),
  17010. TransitionEffect.scale({ x: 0, y: 0 })))
  17011. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  17012. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  17013. .onClick(() => {
  17014. dataBu.onItemClick?.(index)
  17015. })
  17016. })
  17017. }
  17018. .scrollBar(BarState.Off)
  17019. .width(150)
  17020. .divider({
  17021. strokeWidth: 1,
  17022. color: "#22FFFFFF"
  17023. })
  17024. }
  17025. .height(300)
  17026. .padding({
  17027. bottom: 30
  17028. })
  17029. }
  17030. @Concurrent
  17031. function buildAlphabetIndexTask(items: Array<AlphaTaskItem>, sortType: number, isShowFileName: boolean): Array<string> {
  17032. const alphabetSet = new Set<string>()
  17033. for (const item of items) {
  17034. let text = isShowFileName ? (item.fileName || '') :
  17035. (item.type != CommonConstants.TYPE_IS_DIR && item.pyStr) ? item.pyStr : (item.name || '')
  17036. if (sortType === 0 || sortType == 1) {
  17037. text = item.artist || ''
  17038. } else if (sortType === 2 || sortType == 3) {
  17039. text = item.album || ''
  17040. }
  17041. if (text && text.length > 0) {
  17042. const first = getFirstLetter(text)
  17043. if (!alphabetSet.has(first)) {
  17044. alphabetSet.add(first)
  17045. }
  17046. }
  17047. }
  17048. const sorted = Array.from(alphabetSet).sort((a, b) => {
  17049. if (sortType === 4 || sortType == 0 || sortType == 2 || sortType == 6) {
  17050. return a.localeCompare(b)
  17051. }
  17052. return b.localeCompare(a)
  17053. })
  17054. return sorted
  17055. }
  17056. function getFileDirName(filePath: string,rootPath:string): string{
  17057. if(filePath===rootPath){
  17058. return '首页'
  17059. }
  17060. let result = FileUtil.getFileName(filePath)
  17061. if(StrUtil.isEmpty(result))
  17062. return ''
  17063. if(result.startsWith('.'))
  17064. result = result.replace(/\./g, '')
  17065. return result
  17066. }
  17067. //只扫描当前目录下文件(不扫描子文件夹)的方法
  17068. @Concurrent
  17069. async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
  17070. const table: MediaTable = new MediaTable(context);
  17071. try {
  17072. // 直接获取当前目录下的文件列表
  17073. const files = FileUtil.listFileSync(dirPath);
  17074. await Promise.all(files.map(async (file) => {
  17075. const fPath = `${dirPath}/${file}`;
  17076. // 跳过目录,只处理文件
  17077. if (FileUtil.isDirectory(fPath)) {
  17078. return;
  17079. }
  17080. // 跳过特定格式文件
  17081. if (fPath.endsWith('.lrc') || fPath.endsWith('.srt')) {
  17082. return;
  17083. }
  17084. // 检查是否为媒体文件
  17085. if (Utility.isMeidaByExtension(fPath)) {
  17086. let mType = CommonConstants.TYPE_LOCAL;
  17087. if (fPath.includes(lockPath)) {
  17088. mType = CommonConstants.TYPE_LOCK;
  17089. }
  17090. const mediaItem = await Utility.uriGetMusicAssetsFromFile(
  17091. context, fPath, mType, true
  17092. );
  17093. table.insert(mediaItem, (id: number) => {
  17094. // 插入回调函数
  17095. }, cover_api);
  17096. }
  17097. }));
  17098. } catch (error) {
  17099. console.error(' 扫描当前目录失败:', error);
  17100. }
  17101. }
  17102. //内嵌标签后更新库
  17103. @Concurrent
  17104. async function updateInfoDb(
  17105. context: Context,
  17106. filePath: string,
  17107. titleStr: string,
  17108. artistStr: string,
  17109. albumStr: string,
  17110. lyricConStr: string,
  17111. yearStr: string,
  17112. genreStr: string,
  17113. trackStr: string,
  17114. albumArtistStr: string,
  17115. composerStr: string,
  17116. lyricistStr: string,
  17117. commentStr: string,
  17118. discStr: string,
  17119. ): Promise<boolean> {
  17120. const table: MediaTable = new MediaTable(context);
  17121. await new Promise<void>((resolve, reject) => {
  17122. table.getRdbStore(context, (err:Error) => {
  17123. err ? reject(err) : resolve();
  17124. });
  17125. });
  17126. return await new Promise<boolean>((resolve) => {
  17127. table.updateMediaInfo(filePath, titleStr, artistStr, albumStr, lyricConStr,
  17128. yearStr, genreStr, trackStr, albumArtistStr, composerStr, lyricistStr, commentStr, discStr,
  17129. (success: boolean, error?: string) => {
  17130. if (success) {
  17131. console.log("onecold 编辑信息成功,数据库已同步");
  17132. } else {
  17133. console.error("onecold 编辑信息数据库失败原因: " + error);
  17134. }
  17135. resolve(success);
  17136. });
  17137. });
  17138. }
  17139. @Concurrent
  17140. async function replaceLocalMusicCoverTask(
  17141. context: Context,
  17142. filePath: string,
  17143. sandboxCoverPath: string
  17144. ): Promise<boolean> {
  17145. const coverResult: boolean = await changeMusicCover(context, filePath, sandboxCoverPath, true, '');
  17146. if (!coverResult) {
  17147. return false;
  17148. }
  17149. const table: MediaTable = new MediaTable(context);
  17150. await new Promise<void>((resolve, reject) => {
  17151. table.getRdbStore(context, (err: Error) => {
  17152. err ? reject(err) : resolve();
  17153. });
  17154. });
  17155. return await new Promise<boolean>((resolve) => {
  17156. table.updatePixelMapPath(filePath, fileUri.getUriFromPath(sandboxCoverPath),
  17157. (success: boolean, _error?: string) => {
  17158. resolve(success);
  17159. });
  17160. });
  17161. }