LocalMusic.ets 589 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795
  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 { getNavidromeVideoItems, getNavidromeCurrentPlayIndex } from '../common/util/NavidromePlaylistStore';
  7. import {
  8. ImplOnBufferingUpdateListener,
  9. ImplOnCompletionListener,
  10. ImplOnErrorListener,
  11. ImplOnInfoListener,
  12. ImplOnPreparedListener,
  13. ImplOnSeekCompleteListener,
  14. ImplOnTimedTextListener,
  15. ImplOnVideoSizeChangedListener
  16. } from '../common/IjkPlayerListenerImpls';
  17. import {
  18. ButtonFancyModifier,
  19. ImageFancyModifier,
  20. ShadowModifier,
  21. SymbolGlyphFancyModifier } from '../common/util/AttributeModifierUtil'
  22. import {
  23. AppUtil,
  24. ArrayUtil,
  25. Base64Util,
  26. DateUtil,
  27. DeviceUtil,
  28. FileUtil,
  29. GlobalContext,
  30. LogUtil,
  31. MD5,
  32. PreferencesUtil,
  33. RandomUtil,
  34. StrUtil,
  35. ToastUtil
  36. } from '@pura/harmony-utils';
  37. import { imagePathToPixelMap } from '../common/util/CommUtils';
  38. import { unifiedDataChannel, uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData';
  39. import { CommonConstants } from '../common/constants/CommonConstants';
  40. import { BaiduConstants } from '../common/constants/BaiduConstants';
  41. import { EventConstants } from '../common/constants/EventConstants';
  42. import Logger from '../common/util/Logger';
  43. import { http } from '@kit.NetworkKit';
  44. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  45. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  46. import { BubbleBean } from '../viewmodel/BubbleBean';
  47. import { PopupPosition, XPopup } from '@chinalike/popup';
  48. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  49. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  50. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  51. import { MessageEvents, util, worker, ErrorEvent, JSON } from '@kit.ArkTS';
  52. import { Verify } from './Verify';
  53. import { taskpool } from '@kit.ArkTS';
  54. import { RotatingCover } from './RotatingCover';
  55. import { PointLightButton } from './PointLight/PointLightButton';
  56. import { PlayConstants } from '../common/constants/PlayConstants';
  57. import { effectKit } from '@kit.ArkGraphics2D';
  58. import { ColorConversion } from '../common/util/ColorConversion';
  59. import { Lyric, LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  60. import { AvSessionController } from '../controller/AvSessionController';
  61. import { EqualizerManager } from '../common/util/EqualizerManager';
  62. import { EqualizerViewWithCallback } from './EqualizerView';
  63. import { CastController, CastControllerCallbacks } from '../controller/CastController';
  64. import { repairAudioMetadata, convertDsfToWav, getApiLyric,changeMusicCover} from '../common/util/MusicTagUtils';
  65. import { extractHwMediaMetadata, FFMpegTags,Utility } from '../common/util/Utility';
  66. import { TagsContentCover } from '../view/TagsContentCover';
  67. import {
  68. DeviceChangeReason,
  69. IjkMediaPlayer,
  70. InterruptEvent,
  71. InterruptHintType,
  72. LogUtils,
  73. OnBufferingUpdateListener,
  74. OnCompletionListener,
  75. OnErrorListener,
  76. OnInfoListener,
  77. OnPreparedListener,
  78. OnSeekCompleteListener,
  79. OnTimedTextListener,
  80. OnVideoSizeChangedListener
  81. } from '@ohos/ijkplayer';
  82. import { PlayStatus } from '../common/PlayStatus';
  83. import fs from '@ohos.file.fs';
  84. import { image } from '@kit.ImageKit';
  85. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  86. import { media } from '@kit.MediaKit';
  87. import { UniversalDetector } from '@ohos/juniversalchardet';
  88. import { SettingPage } from '../pages/SettingPage';
  89. import { secondToTime,getTransverterText } from '../common/util/CommUtils';
  90. import { CommonConstants2 } from '../common/util/CommonConstants2';
  91. import { hilog } from '@kit.PerformanceAnalysisKit';
  92. import { LazyDataSource } from '../common/util/LazyDataSource';
  93. import MediaTable, { PageQueryOptions, PageQueryResult, RandomSongQueryOptions } from '../common/util/MediaTable';
  94. import FileDeletionWatcher from '../common/util/FileDeletionWatcher';
  95. import LyricUtil from '../common/util/LyricUtil';
  96. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  97. import { ringtone } from '@kit.RingtoneKit';
  98. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  99. import { resourceManager } from '@kit.LocalizationKit';
  100. import { deviceInfo } from '@kit.BasicServicesKit';
  101. import '../common/network/RemoteCacheRegistry';
  102. import { ServerLogUtil } from '../common/util/ServerLogUtil';
  103. import { lyricService, SongData } from '../common/service/LyricService';
  104. import {
  105. cloneVideoItem,
  106. preloadNextSongIfNeeded,
  107. setVideoUrlForSong,
  108. getTypeOrder,
  109. isWebDavType,
  110. isSmbType,
  111. isNavidromeType,
  112. isFtpType,
  113. isBaiduType,
  114. isJellyfinType,
  115. isEmbyType,
  116. isAudioStationType,
  117. isPlexType,
  118. isRemoteCloudType,
  119. WorkerEditMusicResult,
  120. WebDavMetadataUpdatePayload
  121. } from '../common/util/RemotePlayerUtil';
  122. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  123. import app from '@system.app';
  124. import { TextNodeController } from './PipLyricTextBuilder';
  125. import { IndexerView } from './IndexerView';
  126. import { KeyCode } from '@kit.InputKit';
  127. import { KnockController } from '../controller/KnockController';
  128. import { DeleteComptent } from '../view/DeleteComptent';
  129. import { ABLoopComptent } from '../view/ABLoopComptent';
  130. import { FixMessyView } from '../view/FixMessyView';
  131. import { parseCueFile,CueTrack,CueInfo } from '../common/util/CueUtils';
  132. import { CueComptent } from '../view/CueComptent';
  133. import PlaylistTable from '../common/util/PlaylistTable';
  134. import { showAddToPlaylistDialog } from '../dialog/AddToPlaylistDialog';
  135. import { showCreatePlaylistDialog } from '../dialog/PlaylistDialog';
  136. import { convertPlaylistSongsToVideoItems, emptyView,updateAllSongsSortOrder } from '../pages/PlaylistDetailPage';
  137. import { Playlist, PlaylistSong } from '../viewmodel/Playlist';
  138. import { Song } from '../viewmodel/Song';
  139. import { WebDavAccount } from '../viewmodel/WebDavAccount';
  140. import { SongType } from '../common/enums/SongType';
  141. import { RemoteDriveManager, WebDavAuthInfo as WebDavManagerAuthInfo,
  142. buildHttpHeadersWithWebDav,
  143. WebDavAuthItem} from '../common/util/RemoteDriveManager';
  144. import PermissionUtil from '../common/util/PermissionUtil'
  145. import { EditAudio, setRingTone } from './EditAudio';
  146. import { ExtractAccompaniment } from './ExtractAccompaniment';
  147. import { ExtractAudioFromVideo } from './ExtractAudioFromVideo';
  148. import { AudioFormatConverter } from './AudioFormatConverter';
  149. import { MergeAudio } from './MergeAudio';
  150. import { AIVoiceSeparation } from './AIVoiceSeparation';
  151. import { WebDavUrlUtil } from '../common/util/WebDavUrlUtil';
  152. import { ChangeTone } from './ChangeTone';
  153. import {
  154. hdsEffect,
  155. HdsVisualComponent,
  156. HdsSceneController,
  157. HdsSceneType,
  158. HdsVisualComponentAttribute,
  159. } from '@kit.UIDesignKit';
  160. import { GlobalAlphabetIndexerModifier } from '../Styels/GlobalStyles'
  161. import { getFirstLetter } from '../Constants';
  162. import { audio } from '@kit.AudioKit';
  163. import { PointLightDefaultButton } from './PointLight/PointLightDeFaultButton';
  164. const TAG = 'LocalMusic';
  165. const HICAR_LOG_TAG = 'HiCarWindow';
  166. function logHiCarWindow(message: string): void {
  167. void ServerLogUtil.info(HICAR_LOG_TAG, message);
  168. }
  169. export interface WorkerMetadataPayload {
  170. originFilePath: string;
  171. originId?: string;
  172. bit_rate?: string;
  173. duration?: string;
  174. sampleRate?: string;
  175. mimeType?: string;
  176. md5Str?: string;
  177. videoSize?: number;
  178. size?: string;
  179. pixelMapPath?: string;
  180. artist?: string;
  181. album?: string;
  182. name?: string;
  183. lyricContent?: string;
  184. bits_per_raw_sample?: string;
  185. channels?: string;
  186. channel_layout?: string;
  187. start_time?: string;
  188. genre?: string;
  189. year?: string;
  190. probe_score?: number;
  191. track?: string;
  192. disc?: string;
  193. ALBUMARTIST?: string;
  194. COMPOSER?: string;
  195. COMMENT?: string;
  196. LYRICIST?: string;
  197. nb_streams?: number;
  198. nb_programs?: number;
  199. error?: string;
  200. }
  201. interface WorkerMessageScanDone {
  202. code: 101;
  203. data: Record<string, never>;
  204. }
  205. interface WorkerMessageMediaList {
  206. code: 102;
  207. data: Array<VideoItem>;
  208. totalCount: number;
  209. }
  210. interface WorkerMessageArtistList {
  211. code: 103;
  212. data1: Map<string, Array<VideoItem>>;
  213. data2: Array<VideoItem>;
  214. totalCount: number;
  215. }
  216. interface WorkerMessageAlbumList {
  217. code: 104;
  218. data1: Map<string, Array<VideoItem>>;
  219. data2: Array<VideoItem>;
  220. totalCount: number;
  221. }
  222. interface WorkerMessageMetadata {
  223. code: 105;
  224. data: WorkerMetadataPayload;
  225. }
  226. interface WorkerMessageEditResult {
  227. code: 106;
  228. data: WorkerEditMusicResult;
  229. }
  230. type LocalMusicWorkerMessage =
  231. WorkerMessageScanDone
  232. | WorkerMessageMediaList
  233. | WorkerMessageArtistList
  234. | WorkerMessageAlbumList
  235. | WorkerMessageMetadata
  236. | WorkerMessageEditResult;
  237. /**
  238. * 歌单播放事件数据
  239. */
  240. interface PlaylistEventData {
  241. playlistId: string;
  242. playlistName: string;
  243. songCount: number;
  244. startIndex: number;
  245. songFilePaths: string[];
  246. isJump: boolean;
  247. webDavAuthInfo?: WebDavAuthItem; // 新增WebDAV认证信息
  248. }
  249. const DEFAULT_INDEX =
  250. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  251. 'X', 'Y', 'Z']
  252. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  253. // 元数据提取状态追踪
  254. const metadataExtractionInFlight: Map<string, Promise<void>> = new Map();
  255. // setVideoUrlForSong 函数已移至 MusicPlayerUtil.ets
  256. // 定义接口
  257. interface HiCarAspectRatio {
  258. ratio: number;
  259. name: string;
  260. }
  261. interface GeneratedObjectLiteralInterface_1 {
  262. assetId: string;
  263. title: string;
  264. artist: string;
  265. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  266. mediaUri: string;
  267. // 该字段大写,音频'AUDIO',视频'VIDEO'
  268. mediaType: string;
  269. mediaSize: number;
  270. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  271. startPosition: number;
  272. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  273. duration: number;
  274. albumCoverUri: string;
  275. albumTitle: string;
  276. appName: string;
  277. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  278. drmScheme: string;
  279. }
  280. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  281. const ITEM_HEIGHT: number = 65; // 列表项中高度
  282. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  283. /**
  284. * 排序模式枚举
  285. * 定义各种排序方式的升序基准值
  286. */
  287. export enum SortMode {
  288. ByArtist = 0, // 按艺术家升序
  289. ByAlbum = 2, // 按专辑升序
  290. ByName = 4, // 按名称升序
  291. ByTime = 6, // 按时间升序
  292. ByAddTime = 7, // 按添加时间(只有降序)
  293. ByCount = 8, // 按数量升序
  294. ByDiscTrack = 10 // 按碟片编号-音轨号升序
  295. }
  296. //功能强大的音乐播放器
  297. @Preview
  298. @Component
  299. export struct LocalMusic {
  300. @State showFindLocation: boolean = true
  301. @StorageProp("EnablePointLight") enablePointLight: boolean = true
  302. @State showSimple: boolean = true//开启沉浸模式
  303. @State isPaging: boolean = true;//是否分页加载机制
  304. @State isCoverRectangle: boolean = true;
  305. @State showZMIndex: boolean = false //是否右侧显示字母索引
  306. private prevOffsetY: number = 0; // 记录上一次的Y轴偏移量
  307. @State autoHideTitle: boolean = true //滚动自动隐藏标题栏
  308. // 字母表
  309. @State alphaBet: string[] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
  310. 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  311. @State alphaBetStyle: GlobalAlphabetIndexerModifier = new GlobalAlphabetIndexerModifier()
  312. @State selectAlphaBetIndex: number = 0
  313. @State isShowAlphaBet: boolean = false
  314. @State isScrolling: boolean = false
  315. @State isTouchingAlphaBet: boolean = false
  316. @State alphabetHeight: number = 0
  317. public enableShowAlphabet: boolean = true // 是否显示字母表
  318. private alphaBetHideTimer: number = 0
  319. private alphaBetCacheKey: string = ''
  320. @State isShowPrecious: boolean = false //播控条显示上一首按钮
  321. //背景两侧流光控制器
  322. @State sceneBgController: HdsSceneController|undefined = deviceInfo.sdkApiVersion>=20
  323. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  324. new HdsSceneController()
  325. .setSceneParams({
  326. backgroundMaskColors: [Color.Green, Color.Red],
  327. firstEdgeFlowLight: {
  328. startPos: 0,
  329. endPos: 0.5,
  330. color: Color.Red
  331. },
  332. secondEdgeFlowLight: {
  333. startPos: 0,
  334. endPos: -0.5,
  335. color: Color.Green
  336. }
  337. }) : undefined;
  338. //背景流光控制器
  339. @State bgController: hdsEffect.ShaderEffectController|undefined = deviceInfo.sdkApiVersion>=20
  340. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  341. new hdsEffect.ShaderEffectController():undefined;
  342. @State showAddSheet:boolean = false
  343. private loadingDialogId: string = ''
  344. private loadingProgressDialogId: string = ''
  345. searchController: SearchController = new SearchController()
  346. @State rightTopImage:Resource = $r('sys.symbol.sort')
  347. @State isEditAudio:boolean = false
  348. @State isExtractAcc:boolean = false
  349. @State isConverter:boolean = false
  350. @State isAIVoiceSeparation:boolean = false
  351. @State isExtractAudio:boolean = false
  352. @State isMergeAudio:boolean = false
  353. @State isCopyFileToDownLoad: boolean = false
  354. @State isChangeTone:boolean = false
  355. @State offHeight: number = 75
  356. @State currentSongList: Array<VideoItem> = []//当前歌单
  357. @Consume currentSongListName:string //当前歌单名称
  358. @Consume @Watch('onIDChange') currentSongListID:string //当前歌单ID
  359. @State currentPlaylistSongFilePaths: string[] = [] //当前歌单的歌曲路径列表(用于随机播放)
  360. @State isRefreshing: boolean = false;
  361. @State maxRefreshingHeight: number = 100.0;
  362. @State isPlayerLoading: boolean = false; // 播放器加载状态
  363. private contentNode?: ComponentContent<Object> = undefined;
  364. // WebDAV相关实例变量(现在改为从内存读取,不再需要存储)
  365. @State ratioL: number = 1;
  366. @State mediaKuCount: number = 0;
  367. @State albumCount: number = 0;
  368. @State artistCount: number = 0;
  369. @State fastForwardSeconds: string = '10'
  370. @State isShowBackFast: boolean = true//快进快退按钮
  371. @State isCanAuto:boolean = true
  372. @State opacityValueImage: number = 1;
  373. @State tipPopup:boolean = false
  374. @State preloadNextSong: boolean = PreferencesUtil.getBooleanSync('preload_next_song', true) // 是否提前缓存下一首
  375. @Consume mType: number;
  376. @StorageProp('themeColor') themeColor: string =
  377. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  378. themeMode: number = 0;
  379. @State titleName: string = '首页'
  380. @State textStr: string = ''
  381. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  382. // private download_path: string = '';
  383. @Consume rootPath: string //音频根目录
  384. @Consume currentPath: string
  385. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  386. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  387. @State lockPath: string = ''
  388. @State favPath: string = ''
  389. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  390. @State historyPath: string = ''
  391. @State historyList: Array<VideoItem> = []
  392. @Consume isHistory: boolean
  393. static readonly HISTORY_MUSIC: string = 'music_historyList';
  394. private table: MediaTable = new MediaTable(getContext(this))
  395. private playlistTable: PlaylistTable | null = null
  396. private deletionWatcher: FileDeletionWatcher | null = null
  397. @State allPlaylists: Playlist[] = []
  398. @State isZero: boolean = false
  399. @State fileList: Array<string> = []
  400. @State dirList: Array<VideoItem> = []
  401. @Consume videoLocalList:VideoItem[]
  402. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  403. @State listRefreshKey: number = 0
  404. @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  405. @State artistList: Array<VideoItem> = []; //艺术家文件
  406. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  407. @State artistSongCountMap: Map<string, number> = new Map();
  408. @State albumList: Array<VideoItem> = []; //专辑文件
  409. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  410. @State albumSongCountMap: Map<string, number> = new Map();
  411. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  412. @State imageOpacities: number[] = [];
  413. @Consume isCanBack: boolean
  414. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  415. @State showSingleLyric: boolean = false
  416. @State sortType: number = 4 //默认排序方式
  417. @State isShowSimi: boolean = false //是否显示私密音频
  418. @State isShowFAV: boolean = true //是否显示我的收藏
  419. @State isShowTitleBar: boolean = true //是否显示分类导航条
  420. @State isShowAllBar: boolean = true //是否显示播放全部条
  421. @State isShowSingleLineLyric: boolean = false //是否显示单行歌词
  422. @State isShowHistory: boolean = true //是否显示最近播放
  423. @State @Watch('onColorModeChange') isCustomizeBg: boolean = false //自定义背景界面
  424. @State isGridMusic: boolean = false //是否网格布局
  425. @State isCircleBtn: boolean = false //是否圆形播放按钮
  426. @State twoFingerType: number = 3 //双支放大缩小的类型
  427. @State isScrollHide: boolean = false //是否滚动隐藏
  428. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  429. @State isStartAutoPlay: boolean = false //启动后自动播放
  430. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  431. @State isShowHeader: boolean = true
  432. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  433. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  434. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  435. @State isSwipe: boolean = false //listItem的左滑开关
  436. @State openSkipSongAnimate: boolean = true//切歌动画效果
  437. @State customizeBgPath: string | undefined = '';
  438. @State isDarkMode: boolean = false
  439. @State lyricTextWeight: number = 400
  440. @State lyricTextWeightPip: number = 400
  441. @State currentSwiperIndex: number = 0
  442. @State blurValue: number = 0 //背景模糊
  443. @State bgBrightness: number = 0 //背景亮度
  444. private listScroller: ListScroller = new ListScroller()
  445. private playListScroller: Scroller = new Scroller()
  446. @State isOneKeyTags:boolean = false
  447. @State isFixMessy:boolean = false
  448. // 分页相关状态
  449. @State private currentPage: number = 0 // 当前页码
  450. @State private pageSize: number = 50 // 每页数量
  451. @State private totalCount: number = 0 // 总记录数
  452. @State private hasMoreData: boolean = true // 是否还有更多数据
  453. @State private isLoadingPage: boolean = false // 是否正在加载分页数据
  454. private pageCache: Map<number, VideoItem[]> = new Map() // 页面缓存(最多保留3页)
  455. private prefetchingPages: Set<number> = new Set()
  456. private playQueueScope: 'view' | 'history' | 'fav' | 'playlist' | 'single' = 'view'
  457. private isHydratingPlayList: boolean = false
  458. @StorageProp('isLandscape') @Watch('onIsLandscapeChange') isLandscape: boolean = false;
  459. @StorageProp('topSafeHeight') topSafeHeight: number = 0;
  460. @StorageProp('bottomSafeHeight') bottomSafeHeight: number = 0;
  461. @StorageProp('windowWidth') windowWidth: number = 0;
  462. @StorageProp('windowHeight') windowHeight: number = 0;
  463. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  464. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  465. private UNKONWN:string = '';
  466. private listArea: Area = {
  467. width: 0,
  468. height: 0,
  469. position: {},
  470. globalPosition: {}
  471. }
  472. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  473. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  474. // WebDAV认证信息缓存(作为实例变量,比全局上下文更可靠)
  475. private currentWebDavAuthInfo: WebDavAuthItem | null = null;
  476. //瀑布流的列数横竖屏动态切换
  477. onIsLandscapeChange() {
  478. if(this.isLandscape){
  479. this.columns = 4
  480. }else{
  481. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  482. }
  483. }
  484. onColorModeChange() {
  485. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  486. }
  487. //点击某个歌单id发生变化的时候回调
  488. onIDChange(){
  489. console.log('onecold 歌单id发生变化this.currentSongListID='+this.currentSongListID)
  490. console.log('onecold 歌单id发生变化this.currentSongListName='+this.currentSongListName)
  491. if(this.modeType==4){
  492. this.titleName = this.currentSongListName
  493. this.rightTopImage = $r('sys.symbol.sort')
  494. //获取缓存
  495. const cacheSongs:string =PreferencesUtil.getStringSync(this.currentSongListID+'currentSongList', '')
  496. console.log('onecold 歌单id发生变化获取缓存2 cacheSongs = '+cacheSongs)
  497. if(StrUtil.isNotEmpty(cacheSongs)){
  498. this.currentSongList = JSON.parse(cacheSongs) as VideoItem[]
  499. this.updateListData(this.currentSongList, true)
  500. }
  501. this.doSongListTask()//获取歌单信息
  502. }
  503. }
  504. async doSongListTask() {
  505. // 初始化歌单数据库
  506. const playlistTable = new PlaylistTable(this.context);
  507. // 查询歌单中的所有歌曲
  508. const playlistSongs: PlaylistSong[] = await playlistTable.queryPlaylistSongs(this.currentSongListID);
  509. console.log('onecold 歌单id发生变化获取缓存7 playlistSongs='+playlistSongs.length)
  510. if (ArrayUtil.isEmpty(playlistSongs)) {
  511. this.updateListData([], true)
  512. // 清空歌单路径列表
  513. this.currentPlaylistSongFilePaths = [];
  514. } else {
  515. this.currentSongList = await convertPlaylistSongsToVideoItems(this.context, playlistSongs);
  516. console.log('onecold 从数据库读取的歌曲为 playlistSongs='+this.currentSongList.length)
  517. this.updateListData(this.currentSongList, true)
  518. // 保存歌单的歌曲路径列表,用于随机播放
  519. this.currentPlaylistSongFilePaths = playlistSongs.map(song => song.songFilePath);
  520. Logger.info('heanup doSongListTask', `保存歌单歌曲路径列表,歌单ID=${this.currentSongListID}, 数量=${this.currentPlaylistSongFilePaths.length}`);
  521. if (ArrayUtil.isNotEmpty(this.currentSongList)&&this.currentSongList.length > 100) {
  522. // 只保存前100条记录到缓存中
  523. let canceList = this.currentSongList.slice(0, 100);
  524. PreferencesUtil.putSync(this.currentSongListID+'currentSongList',
  525. JSON.stringify(canceList))
  526. } else {
  527. PreferencesUtil.putSync(this.currentSongListID+'currentSongList', JSON.stringify(this.currentSongList));
  528. }
  529. }
  530. this.isRefreshing = false
  531. }
  532. async onModeChange(): Promise<void> {
  533. this.isFavMusic = false
  534. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  535. Logger.info('heanup LocalMusic', `onModeChange: 切换模式 modeType=${this.modeType}`);
  536. switch (this.modeType) {
  537. case 0:
  538. // 首页模式已在 resetAndLoadFirstPage 中处理
  539. // 切换模式时加载对应的排序类型
  540. this.titleName = Utility.resourceToString(this.context,$r('app.string.home'))
  541. this.sortType = this.loadSortTypeForCurrentMode()
  542. break
  543. case 1:
  544. this.rightTopImage = $r('sys.symbol.sort')
  545. this.titleName = Utility.resourceToString(this.context,$r('app.string.media_ku'))
  546. // 切换模式时加载对应的排序类型
  547. this.sortType = this.loadSortTypeForCurrentMode()
  548. break
  549. case 2:
  550. this.rightTopImage = $r('sys.symbol.sort')
  551. this.titleName = Utility.resourceToString(this.context,$r('app.string.artist'))
  552. // 切换到艺术家模式时,加载艺术家模式的排序类型(默认按数量降序)
  553. this.sortType = this.loadSortTypeForCurrentMode()
  554. break
  555. case 3:
  556. this.rightTopImage = $r('sys.symbol.sort')
  557. this.titleName = Utility.resourceToString(this.context,$r('app.string.album'))
  558. // 切换到专辑模式时,加载专辑模式的排序类型(默认按数量降序)
  559. this.sortType = this.loadSortTypeForCurrentMode()
  560. break
  561. }
  562. // 模式切换时重置分页状态并加载第一页
  563. await this.resetAndLoadFirstPage();
  564. Logger.info('heanup onModeChange', `doSortType: 切换排序方式 sortType=${this.sortType}, mode=${this.modeType}`);
  565. }
  566. // @Consume currentSong: VideoItem | undefined;
  567. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  568. // @StorageLink('isPlay') isPlay: boolean = false;
  569. @Consume isShowPlay: boolean ;
  570. @StorageLink('songList') songList: Array<VideoItem> = [];
  571. @State translateY: number = 0;
  572. @State isShowSheet: boolean = false;
  573. @State isShowSheetView: boolean = false;
  574. @State isShowTimeCloseView: boolean = false;
  575. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  576. @StorageLink('currIndex') curIndex: number = 0;
  577. @Consume isShowDrawer: boolean;
  578. @Consume offsetX: number;
  579. @State isFac: boolean = false;
  580. @State favList: Array<VideoItem> = []
  581. @Consume isFavMusic: boolean
  582. @State isClickedPLayAll: boolean = false;
  583. private scrollerForlist: ListScroller = new ListScroller();
  584. private knockController: KnockController | undefined = undefined;
  585. // 修改为:
  586. imagesF: ImageFrameInfo[] = CommonConstants.IMAGE_FRAME_INFO;
  587. @StorageProp('animationState') animationState: AnimationStatus = AnimationStatus.Initial
  588. // 缓存机制
  589. private cache: Map<string, Array<VideoItem>> = new Map();
  590. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  591. // 持久化缓存
  592. private async saveCacheToStorage() {
  593. const cacheArray = Array.from(this.cache.entries());
  594. const stringCacheArray = Array.from(this.stringCache.entries());
  595. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  596. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  597. }
  598. // 载入缓存
  599. private async loadCacheFromStorage() {
  600. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  601. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  602. if (cacheString) {
  603. const parsedCache: Object | null = JSON.parse(cacheString);
  604. if (parsedCache && Array.isArray(parsedCache)) {
  605. const cacheArray: [string, Array<VideoItem>][] = parsedCache;
  606. this.cache = new Map(cacheArray);
  607. }
  608. }
  609. if (stringCacheString) {
  610. const parsedStringCache: Object | null = JSON.parse(stringCacheString);
  611. if (parsedStringCache && Array.isArray(parsedStringCache)) {
  612. const stringCacheArray: [string, string][] = parsedStringCache;
  613. this.stringCache = new Map(stringCacheArray);
  614. }
  615. }
  616. }
  617. // 查找缓存
  618. private findCache(key: string): Array<VideoItem> | undefined {
  619. return this.cache.get(key);
  620. }
  621. // 查找字符串缓存
  622. private findStringCache(key: string): string | undefined {
  623. return this.stringCache.get(key);
  624. }
  625. // 添加缓存
  626. private addCache(key: string, value: Array<VideoItem>) {
  627. this.cache.set(key, value);
  628. }
  629. // 添加字符串缓存
  630. private addStringCache(key: string, value: string) {
  631. this.stringCache.set(key, value);
  632. }
  633. // 删除缓存
  634. private deleteCache(key: string) {
  635. this.cache.delete(key);
  636. this.saveCacheToStorage()
  637. }
  638. // 删除字符串缓存
  639. private deleteStringCache(key: string) {
  640. this.stringCache.delete(key);
  641. }
  642. // 多选机制
  643. @State selectedFiles: Array<VideoItem> = [];
  644. @Consume isMultiSelect: boolean;
  645. @State isAllSelected: boolean = false;
  646. @State appName: string = ''
  647. @State isHasDir: boolean = false
  648. @State packName: string = ''
  649. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  650. doSwipBack() {
  651. if(this.isSearchMode){
  652. console.info('onecold doSwipBack = ' +this.isSearchMode)
  653. this.isSearchMode = false
  654. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  655. this.searchText = ''
  656. this.getSortedFiles(this.currentPath)
  657. return
  658. }
  659. this.onSearchInput('')
  660. return
  661. }
  662. this.isZero = false
  663. if (this.modeType !== 0 && this.isCanBack) {
  664. // 先设置 isCanBack=false,确保 onModeChange 读取的是列表页的排序设置
  665. this.isCanBack = false
  666. this.onModeChange()
  667. // 返回专辑列表时恢复滚动偏移量,支持列表和网格
  668. setTimeout(() => {
  669. if (this.modeType == 2) {
  670. if (this.isGridMusic||this.twoFingerType==4) {
  671. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  672. let lastWaterOffset = this.mScrollMap.get('lastWaterArtistScrollOffset') ?? 0
  673. if(this.twoFingerType==4){
  674. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  675. }else{
  676. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  677. }
  678. } else {
  679. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  680. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  681. }
  682. } else if (this.modeType == 3) {
  683. if (this.isGridMusic||this.twoFingerType==4) {
  684. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  685. let lastWaterOffset = this.mScrollMap.get('lastWaterAlBumScrollOffset') ?? 0
  686. if(this.twoFingerType==4){
  687. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  688. }else{
  689. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  690. }
  691. } else {
  692. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  693. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  694. }
  695. }
  696. }, 200)
  697. return
  698. }
  699. if (this.isHistory || this.isFavMusic) {
  700. this.isHistory = false
  701. this.getSortedFiles(this.currentPath)
  702. return
  703. }
  704. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  705. animateTo({ duration: 555 }, () => {
  706. // 动画闭包内控制Image组件的出现和消失
  707. this.isShowDrawer = !this.isShowDrawer
  708. this.offsetX = 0
  709. })
  710. return
  711. }
  712. //返回上一级歌单的滚动位置
  713. setTimeout(() => {
  714. if (this.modeType == 0) {
  715. if (this.isGridMusic||this.twoFingerType==4) {
  716. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  717. let lastWaterOffset = this.mScrollMap.get('lastWaterDirScrollOffset') ?? 0
  718. if(this.twoFingerType==4){
  719. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  720. }else{
  721. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  722. }
  723. } else {
  724. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  725. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  726. }
  727. }
  728. }, 100)
  729. this.currentPath = Utility.getParentDirectory(this.currentPath)
  730. Logger.info('this.currentPath2 = ' + this.currentPath)
  731. this.getSortedFiles(this.currentPath)
  732. }
  733. // 组件生命周期
  734. aboutToAppear() {
  735. console.info('onecold aboutToAppear sdkApiVersion = '+deviceInfo.sdkApiVersion)
  736. if(ArrayUtil.isNotEmpty(this.videoLocalList)&&this.modeType==0){
  737. this.updateListData(this.videoLocalList)
  738. }
  739. // 初始化 PlaylistTable
  740. this.playlistTable = new PlaylistTable(getContext(this))
  741. this.sonTwoFingerType = PreferencesUtil.getNumberSync('sonTwoFingerType', 3);
  742. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  743. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  744. this.tipPopup = !this.tipPopup
  745. PreferencesUtil.putSync('isFirstTiped',false)
  746. }
  747. this.initSetting()
  748. this.syncEqualizerUi();
  749. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  750. Utility.getAppName(getContext(this)).then((appName: string) => {
  751. this.appName = appName
  752. })
  753. this.packName = AppUtil.getBundleName()
  754. this.tabSelectedIndexes[0] = this.modeType//SegmentButton的索引
  755. this.loadCacheFromStorage(); // 加载文件夹缓存
  756. // 在首页初始化时读取媒体库,艺术家,专辑等缓存数据
  757. this.initLoadCache()
  758. this.mkDownLoadDir()
  759. let eventMusic: emitter.InnerEvent = { eventId: EventConstants.EVENT_AUDIO_OPEN }
  760. // 监听广播事件(打开其他应用处理)
  761. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  762. this.saveVideoDatas([eventData.data?.message], true)
  763. });
  764. //侧滑广播接收时间
  765. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_UPDATE }
  766. // 监听广播事件(手势返回处理)
  767. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  768. animateTo({ duration: 555 }, () => {
  769. this.doSwipBack()
  770. })
  771. });
  772. //ScanFilePage广播接收时间
  773. let eventScanUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_SCAN_UPDATE }
  774. // 监听ScanFilePage广播事件(更新数据库)
  775. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  776. this.doUpdateData()
  777. });
  778. let eventEqualizerChanged: emitter.InnerEvent = { eventId: EventConstants.EVENT_EQUALIZER_CHANGED }
  779. emitter.on(eventEqualizerChanged, () => {
  780. this.syncEqualizerUi();
  781. if (this.mIjkMediaPlayer) {
  782. const equalizerManager = EqualizerManager.getInstance();
  783. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  784. this.markEqualizerApplied();
  785. }
  786. });
  787. // 监听歌单播放请求事件
  788. let eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY }
  789. emitter.on(eventPlaylistPlay, async (eventData: emitter.EventData) => {
  790. const data = eventData.data as Record<string, Object>
  791. if (!data) {
  792. Logger.error('heanup eventPlaylistPlay: eventData.data is undefined or null')
  793. return
  794. }
  795. // 检查歌单播放数据结构
  796. if (data.playlistId && data.songFilePaths && data.startIndex !== undefined) {
  797. const playlistData: PlaylistEventData = {
  798. playlistId: data.playlistId as string,
  799. playlistName: data.playlistName as string,
  800. songCount: data.songCount as number,
  801. startIndex: data.startIndex as number,
  802. isJump: data.isJump as boolean,
  803. songFilePaths: data.songFilePaths as string[]
  804. }
  805. await this.handlePlaylistPlayRequest(
  806. playlistData.playlistId,
  807. playlistData.playlistName,
  808. playlistData.songFilePaths,
  809. playlistData.startIndex,
  810. playlistData.isJump,
  811. )
  812. return
  813. }
  814. Logger.error('heanup eventPlaylistPlay: 接收到无效的数据结构')
  815. });
  816. let eventRefreshSort: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_REFRESH_SORT }
  817. // 监听广播事件(通用设置配置更新)
  818. emitter.on(eventRefreshSort, (eventData: emitter.EventData) => {
  819. if(this.modeType ==4){
  820. this.doSongListTask()//获取歌单信息
  821. }
  822. });
  823. let eventSetting: emitter.InnerEvent = { eventId: EventConstants.EVENT_SETTING_UPDATE }
  824. // 监听广播事件(通用设置配置更新)
  825. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  826. this.initSetting()
  827. });
  828. // 监听 WebDAV 元数据更新事件
  829. let eventWebDavMetadata: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED }
  830. emitter.on(eventWebDavMetadata, (eventData: emitter.EventData) => {
  831. const payloads = eventData?.data as WebDavMetadataUpdatePayload[] | undefined;
  832. if (!payloads || payloads.length === 0) {
  833. Logger.info(TAG, 'LocalMusic: WebDav metadata event received but payload empty');
  834. return;
  835. }
  836. Logger.info(TAG, `LocalMusic: WebDav metadata event payload count: ${payloads.length}`);
  837. // 处理每个元数据更新
  838. for (let i = 0; i < payloads.length; i++) {
  839. const payload = payloads[i];
  840. if (!payload || !payload.filePath) {
  841. continue;
  842. }
  843. // 重要:只更新当前正在播放的歌曲
  844. // 如果 filePath 不匹配,说明是其他歌曲的元数据更新,忽略不做处理
  845. if (this.currentSong && this.currentSong.filePath === payload.filePath) {
  846. Logger.info(TAG, `LocalMusic: 更新当前播放歌曲的元数据: ${payload.filePath}`);
  847. if (payload.name && payload.name.length > 0) {
  848. this.name = payload.name;
  849. if (this.currentSong) {
  850. this.currentSong.name = payload.name;
  851. }
  852. }
  853. if (payload.artist && payload.artist.length > 0) {
  854. this.artist = payload.artist;
  855. if (this.currentSong) {
  856. this.currentSong.artist = payload.artist;
  857. }
  858. }
  859. if (payload.pixelMapPath && payload.pixelMapPath.length > 0) {
  860. this.cover = payload.pixelMapPath;
  861. if (this.currentSong) {
  862. this.currentSong.pixelMapPath = payload.pixelMapPath;
  863. }
  864. Logger.info(TAG, `LocalMusic: 封面已更新: ${payload.pixelMapPath}`);
  865. }
  866. // 同步更新 AppStorage
  867. AppStorage.setOrCreate('currentSong', this.currentSong);
  868. } else {
  869. Logger.info(TAG, `LocalMusic: 跳过非当前播放歌曲的元数据更新: ${payload.filePath}, 当前: ${this.currentSong?.filePath}`);
  870. }
  871. }
  872. });
  873. // 监听广播事件(通用设置配置更新)
  874. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  875. this.doChangeSetting()
  876. });
  877. let event: Callback<InterruptEvent> = (event) => {
  878. // LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  879. console.info(`heanup onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`)
  880. this.savePlaybackPosition()
  881. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  882. this.pause();
  883. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  884. console.info(`heanup onecold audioInterrupt startPlayOrResumePlay: ${JSON.stringify(event)}`)
  885. this.startPlayOrResumePlay();
  886. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  887. console.info(`heanup onecold 与其他应用音频冲突 被截断点 INTERRUPT_HINT_STOP`)
  888. if(!this.isSameTimePlay){
  889. this.stop();
  890. }
  891. }
  892. }
  893. this.mIjkMediaPlayer.on('audioInterrupt', event);
  894. // 音频设备断连回调处理比如蓝牙耳机断开
  895. let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  896. LogUtils.getInstance().LOGI(`Heanup deviceChange event: ${JSON.stringify(event)}`);
  897. if (event.reason === DeviceChangeReason.REASON_NEW_DEVICE_AVAILABLE) { // 音频设备连接
  898. } else if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  899. console.info('heanup onecold 音频设备断开连接, 暂停播放')
  900. this.pause();
  901. }
  902. }
  903. // 订阅音频设备断开和连接事件
  904. this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  905. const eventPause: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAY_PAUSE }
  906. // 监听广播事件(hicar断开暂停播放)
  907. emitter.on(eventPause, (eventData: emitter.EventData) => {
  908. console.info('heanup onecold hicar断开暂停播放, 暂停播放')
  909. this.pause();
  910. });
  911. // 有线耳机断开和连接的监听。监听音频设备状态变化。
  912. let audioManager = audio.getAudioManager(); // 需要先创建AudioManager实例。
  913. let audioRoutingManager = audioManager.getRoutingManager(); // 再调用AudioManager的方法创建AudioRoutingManager实例。
  914. audioRoutingManager.on('deviceChange', audio.DeviceFlag.INPUT_DEVICES_FLAG, (deviceChanged: audio.DeviceChangeAction) => {
  915. console.info('device change type : ' + deviceChanged.type); // 设备连接状态变化,0为连接,1为断开连接。
  916. // 设备类型 22是USB耳机,带麦克风,3是有线耳机。
  917. if(deviceChanged.type==1&&
  918. (deviceChanged.deviceDescriptors[0].deviceType== 22||
  919. deviceChanged.deviceDescriptors[0].deviceType==3)){
  920. console.info('heanup onecold 有线耳机断开, 暂停播放')
  921. this.pause();
  922. }
  923. });
  924. this.makeWorker()
  925. //折叠屏的屏幕显示模式变化
  926. display.on('foldDisplayModeChange', (data) => {
  927. this.doChangeBarHeight()
  928. });
  929. display.on('foldStatusChange', (data) => {
  930. Logger.info('onecold foldStatusChange ')
  931. });
  932. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  933. // 读取 themeMode 并同步 currentColorMode
  934. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  935. this.applyThemeMode(this.themeMode)
  936. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  937. AppStorage.setOrCreate('themeColor', themeColor);
  938. this.themeColor = themeColor;
  939. this.doChangeSetting()
  940. this.windowClass.on('windowSizeChange', (size: window.Size) => {
  941. LogUtil.info('onecold windowSizeChange')
  942. this.doChangeBarHeight()
  943. let viewWidth = px2vp(size.width);
  944. let viewHeight = px2vp(size.height);
  945. if(this.isPhoneLan()){
  946. this.is_auto_hide_progress = false
  947. if(this.isHiCar()){
  948. return
  949. }
  950. setTimeout(() => {
  951. this.is_auto_hide_progress = true
  952. }, 6000)
  953. }else{
  954. this.startAutoHide()
  955. }
  956. });
  957. this.eventHub.on('onStateChange', (fg: boolean) => {
  958. if (fg && this.curState === 'STARTED') {
  959. this.stopPip();
  960. }
  961. });
  962. //NewIndex的博空调收到eventHub消息控制播放
  963. this.getUIContext().getHostContext()!.eventHub.on('playOrPause', () => {
  964. if (ArrayUtil.isNotEmpty(this.songList)) {
  965. this.playOrPause();
  966. } else {
  967. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  968. }
  969. });
  970. this.getUIContext().getHostContext()!.eventHub.on('playPrevious', () => {
  971. if (ArrayUtil.isNotEmpty(this.songList)) {
  972. this.playPrevious();
  973. } else {
  974. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  975. }
  976. });
  977. this.getUIContext().getHostContext()!.eventHub.on('playNext', () => {
  978. if (ArrayUtil.isNotEmpty(this.songList)) {
  979. this.playNext();
  980. } else {
  981. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  982. }
  983. });
  984. this.getUIContext().getHostContext()!.eventHub.on('showPlayerView', () => {
  985. this.showPlayerView();
  986. });
  987. this.getUIContext().getHostContext()!.eventHub.on('openPlayList', () => {
  988. this.openPlayList();
  989. });
  990. }
  991. //载入媒体库,艺术家,专辑等缓存
  992. initLoadCache(){
  993. this.mediaKuCount = PreferencesUtil.getNumberSync('mediaKuCount', 0)
  994. this.artistCount = PreferencesUtil.getNumberSync('artistCount', 0)
  995. this.albumCount = PreferencesUtil.getNumberSync('albumCount', 0)
  996. let cachedListStr:string = PreferencesUtil.getStringSync('mediaKuList', '[]');
  997. let cachedList = JSON.parse(cachedListStr) as Array<VideoItem>;
  998. if(ArrayUtil.isNotEmpty(cachedList)){
  999. this.mediaKuList = cachedList
  1000. if(this.modeType==1){
  1001. this.updateListData(this.mediaKuList)
  1002. }
  1003. }
  1004. let artistListStr:string = PreferencesUtil.getStringSync('artistList', '[]');
  1005. let artistCachedList = JSON.parse(artistListStr) as Array<VideoItem>;
  1006. if(ArrayUtil.isNotEmpty(artistCachedList)){
  1007. this.artistList = artistCachedList
  1008. let artistMapStr:string = PreferencesUtil.getStringSync('artistMap', '[]');
  1009. const parsedArray = JSON.parse(artistMapStr) as [string, VideoItem[]][];
  1010. this.artistMap = new Map(parsedArray);
  1011. // this.artistMap = JSON.parse(artistMapStr) as Map<string, VideoItem[]>;
  1012. if(this.modeType==2){
  1013. this.updateListData(this.artistList)
  1014. }
  1015. }
  1016. let albumListStr:string = PreferencesUtil.getStringSync('albumList', '[]');
  1017. let albumCachedList = JSON.parse(albumListStr) as Array<VideoItem>;
  1018. if(ArrayUtil.isNotEmpty(albumCachedList)){
  1019. this.albumList = albumCachedList
  1020. let albumMapStr:string = PreferencesUtil.getStringSync('albumMap', '[]');
  1021. const parsedArray = JSON.parse(albumMapStr) as [string, VideoItem[]][];
  1022. this.albumMap = new Map(parsedArray);
  1023. if(this.modeType==3){
  1024. this.updateListData(this.albumList)
  1025. }
  1026. }
  1027. }
  1028. startAutoHide() {
  1029. if(this.isHiCar()){
  1030. return
  1031. }
  1032. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  1033. console.info('onecold startAutoHide')
  1034. this.is_auto_hide_progress = false
  1035. setTimeout(() => {
  1036. this.is_auto_hide_progress = true
  1037. }, 6000)
  1038. }
  1039. }
  1040. applyThemeMode(mode: number) {
  1041. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  1042. if (mode === 1) {
  1043. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  1044. } else if (mode === 2) {
  1045. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1046. }
  1047. AppStorage.setOrCreate('currentColorMode', colorMode)
  1048. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  1049. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  1050. AppStorage.setOrCreate('themeMode', mode)
  1051. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1052. // 只有强制浅色/深色时才主动设置
  1053. const context = getContext(this) as common.UIAbilityContext
  1054. context.getApplicationContext().setColorMode(colorMode)
  1055. }
  1056. initSetting() {
  1057. this.enablePointLight = PreferencesUtil.getBooleanSync('enablePointLight', true)
  1058. AppStorage.setOrCreate('EnablePointLight', this.enablePointLight);
  1059. this.showSimple = PreferencesUtil.getBooleanSync('showSimple', true)
  1060. this.showFindLocation = PreferencesUtil.getBooleanSync('showFindLocation', true)
  1061. this.showZMIndex = PreferencesUtil.getBooleanSync('showZMIndex', false)
  1062. this.autoHideTitle = PreferencesUtil.getBooleanSync('autoHideTitle', true)
  1063. this.isShowPrecious = PreferencesUtil.getBooleanSync('isShowPrecious', false)
  1064. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1065. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  1066. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  1067. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, false)
  1068. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  1069. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  1070. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  1071. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  1072. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  1073. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  1074. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  1075. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  1076. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  1077. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 2)
  1078. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  1079. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  1080. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  1081. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  1082. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  1083. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  1084. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  1085. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  1086. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  1087. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  1088. this.volumeSmall = PreferencesUtil.getBooleanSync('volumeSmall', false)
  1089. this.autoParseMusicName = PreferencesUtil.getBooleanSync('autoParseMusicName', true)
  1090. this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
  1091. this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
  1092. this.fastForwardSeconds = PreferencesUtil.getStringSync('fastForwardSeconds', '10')
  1093. this.isShowBackFast = PreferencesUtil.getBooleanSync('isShowBackFast', false)
  1094. this.isCopyFileToDownLoad = PreferencesUtil.getBooleanSync(SettingPage.IS_COPYFILE_TO_DOWNLOAD, false)
  1095. let audioManager = audio.getAudioManager();
  1096. let audioSessionManager: audio.AudioSessionManager = audioManager.getSessionManager();
  1097. if(this.isSameTimePlay){
  1098. //与其他应用同时播放,关键代码
  1099. let strategy: audio.AudioSessionStrategy = {
  1100. concurrencyMode: audio.AudioConcurrencyMode.CONCURRENCY_MIX_WITH_OTHERS
  1101. };
  1102. audioSessionManager.activateAudioSession(strategy).then(() => {
  1103. console.info('onecold Succeeded in doing activateAudioSession.');
  1104. }).catch((err: BusinessError) => {
  1105. console.error(`Failed to activateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1106. });
  1107. }else{
  1108. let isActivated = audioSessionManager.isAudioSessionActivated();
  1109. if(isActivated){
  1110. audioSessionManager.deactivateAudioSession().then(() => {
  1111. console.info('Succeeded in doing deactivateAudioSession.');
  1112. }).catch((err: BusinessError) => {
  1113. console.error(`Failed to deactivateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1114. });
  1115. }
  1116. }
  1117. if(this.volumeSmall){
  1118. this.volume = 0.5
  1119. }else{
  1120. this.volume = 1
  1121. }
  1122. //如果是hicar连接状态,这些都是false
  1123. if(this.isHiCar()){
  1124. this.autoHideTitle = false
  1125. this.isCoverRectangle= true
  1126. this.columns=4
  1127. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  1128. {
  1129. this.isGridMusic= false//用list不用网格
  1130. this.isCoverTopBig = false
  1131. }
  1132. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  1133. }
  1134. if (this.isSavePlayMode) {
  1135. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  1136. }
  1137. }
  1138. doChangeSetting() {
  1139. this.initSetting()
  1140. this.deleteCache(this.currentPath)
  1141. if (this.modeType === 0) {
  1142. this.getSortedFiles(this.currentPath)
  1143. }
  1144. }
  1145. doChangeBarHeight() {
  1146. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  1147. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  1148. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  1149. this.setBarHeightNormal()
  1150. }
  1151. }
  1152. onPageShow() {
  1153. this.knockController?.immersiveListening();
  1154. app.setImageCacheCount(100);
  1155. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  1156. app.setImageRawDataCacheSize(104857600);
  1157. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  1158. }
  1159. //开启线程查看各个数据库
  1160. makeWorker() {
  1161. setTimeout(() => {
  1162. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  1163. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  1164. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  1165. // workerInstance.postMessage({
  1166. // code: 1,
  1167. // data1: this.context,
  1168. // data2: this.rootPath,
  1169. // data3: this.lockPath,
  1170. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  1171. // data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  1172. // });
  1173. PreferencesUtil.putSync('isFirstApp', false)
  1174. } else {
  1175. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1176. workerInstance.postMessage({ code: 3, data: this.context });
  1177. workerInstance.postMessage({ code: 4, data: this.context });
  1178. this.getHistoryList(false)
  1179. }
  1180. }, 1000)
  1181. workerInstance.onmessage = (e: MessageEvents): void => {
  1182. const message = e.data as LocalMusicWorkerMessage;
  1183. switch (message.code) {
  1184. case 101: //第一次扫描文件夹入库
  1185. ToastUtil.showToast('刷新同步数据库成功!')
  1186. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  1187. this.doAllUpdateData()
  1188. break;
  1189. case 102: //查询媒体库列表
  1190. this.isRefreshing = false
  1191. this.mediaKuList = message.data // 只包含前100条
  1192. const mediaTotalCount: number = message.totalCount ?? this.mediaKuList.length;
  1193. this.mediaKuCount = mediaTotalCount;
  1194. Logger.info(`heanup 查询媒体库列表 缓存数=${this.mediaKuList.length}, 总数=${mediaTotalCount}`)
  1195. Utility.doSortListAscending(this.mediaKuList)
  1196. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  1197. // 媒体库模式下重新加载第一页(分页查询)
  1198. if (this.modeType === 1) {
  1199. this.resetAndLoadFirstPage();
  1200. }
  1201. PreferencesUtil.putSync('mediaKuCount', mediaTotalCount)
  1202. // 只保存前100条记录到缓存中
  1203. PreferencesUtil.putSync('mediaKuList', JSON.stringify(this.mediaKuList));
  1204. break;
  1205. case 103: //收到查询艺术家列表
  1206. this.isRefreshing = false
  1207. this.artistMap = message.data1; // 只包含前60个艺术家的歌曲
  1208. this.artistList = message.data2; // 只包含前100个艺术家
  1209. const artistTotalCount: number = message.totalCount ?? this.artistList.length;
  1210. this.artistCount = artistTotalCount;
  1211. const nextArtistCountMap = new Map(this.artistSongCountMap);
  1212. this.artistMap.forEach((songs, artist) => {
  1213. nextArtistCountMap.set(artist, songs.length);
  1214. });
  1215. this.artistSongCountMap = nextArtistCountMap;
  1216. Logger.info(`heanup 查询艺术家列表 缓存数=${this.artistList.length}, 总数=${artistTotalCount}`)
  1217. PreferencesUtil.putSync('artistCount', artistTotalCount)
  1218. // 艺术家模式下重新加载第一页(分页查询)
  1219. if (this.modeType === 2) {
  1220. this.resetAndLoadFirstPage();
  1221. }
  1222. // 保存前100条艺术家列表
  1223. PreferencesUtil.putSync('artistList', JSON.stringify(this.artistList));
  1224. // 保存前60条艺术家的歌曲Map
  1225. const sortedEntries = Array.from(this.artistMap.entries());
  1226. PreferencesUtil.putSync('artistMap', JSON.stringify(sortedEntries));
  1227. break;
  1228. case 104: //收到查询专辑列表
  1229. this.isRefreshing = false
  1230. this.albumMap = message.data1;
  1231. this.albumList = message.data2
  1232. const albumTotalCount: number = message.totalCount ?? this.albumList.length;
  1233. this.albumCount = albumTotalCount;
  1234. const nextAlbumCountMap = new Map(this.albumSongCountMap);
  1235. this.albumMap.forEach((songs, album) => {
  1236. nextAlbumCountMap.set(album, songs.length);
  1237. });
  1238. this.albumSongCountMap = nextAlbumCountMap;
  1239. Logger.info(`heanup 查询专辑列表 缓存数=${this.albumList.length}, 总数=${albumTotalCount}`)
  1240. // 专辑模式下重新加载第一页(分页查询)
  1241. if (this.modeType === 3) {
  1242. this.resetAndLoadFirstPage();
  1243. }
  1244. //查询完毕在启动是否自动播放
  1245. if (this.isStartAutoPlay&&this.isCanAuto) {
  1246. this.isCanAuto = false
  1247. console.info('onecold startPlayOrResumePlay 757')
  1248. this.startPlayOrResumePlay()
  1249. }
  1250. PreferencesUtil.putSync('albumCount', albumTotalCount)
  1251. // 保存前100条专辑列表(Worker已经只发送了100条)
  1252. PreferencesUtil.putSync('albumList', JSON.stringify(this.albumList));
  1253. // 保存前60条专辑Map(Worker已经只发送了60条)
  1254. const mapArrayAlbum = Array.from(this.albumMap.entries());
  1255. PreferencesUtil.putSync('albumMap', JSON.stringify(mapArrayAlbum));
  1256. break;
  1257. case 105: // 缓存完成后返回的元数据
  1258. this.handleWorkerMetadataPayload(message.data);
  1259. break;
  1260. case 106: // 编辑音乐元数据和封面完成
  1261. this.handleEditMusicResult(message.data);
  1262. break;
  1263. }
  1264. };
  1265. // 在调用terminate后,执行onexit
  1266. workerInstance.onexit = (code) => {
  1267. metadataExtractionInFlight.clear();
  1268. Logger.info(TAG, 'workerInstance 线程已退出,code: ' + code);
  1269. }
  1270. workerInstance.onerror = (err: ErrorEvent) => {
  1271. metadataExtractionInFlight.clear();
  1272. console.error('workerInstance 线程执行发生异常: ' + err.message)
  1273. }
  1274. }
  1275. private handleWorkerMetadataPayload(payload: WorkerMetadataPayload | undefined): void {
  1276. if (!payload || !payload.originFilePath) {
  1277. return;
  1278. }
  1279. metadataExtractionInFlight.delete(payload.originFilePath);
  1280. if (payload.error) {
  1281. Logger.warn(TAG, `缓存文件元数据解析失败: ${payload.error}`);
  1282. return;
  1283. }
  1284. this.applyMetadataToCollections(payload.originFilePath, payload);
  1285. }
  1286. private applyMetadataToCollections(filePath: string, payload: WorkerMetadataPayload): void {
  1287. const targets: Array<VideoItem> = [];
  1288. let mainListUpdated = false;
  1289. let playlistUpdated = false;
  1290. if (this.currentSong && this.currentSong.filePath === filePath) {
  1291. targets.push(this.currentSong);
  1292. }
  1293. const collectFromList = (list?: Array<VideoItem>, markUpdated?: () => void) => {
  1294. if (!list || list.length === 0) {
  1295. return;
  1296. }
  1297. const found = Utility.getItemByFilePath(list, filePath);
  1298. if (found) {
  1299. markUpdated?.();
  1300. targets.push(found);
  1301. }
  1302. };
  1303. collectFromList(this.videoLocalList, () => {
  1304. mainListUpdated = true;
  1305. });
  1306. collectFromList(this.songList, () => {
  1307. playlistUpdated = true;
  1308. });
  1309. collectFromList(this.historyList);
  1310. collectFromList(this.favList);
  1311. const remoteManager = RemoteDriveManager.getInstance();
  1312. collectFromList(remoteManager.webDavSongs);
  1313. const updated = new Set<VideoItem>();
  1314. const remoteMetadataUpdates: Map<string, WebDavMetadataUpdatePayload> = new Map();
  1315. for (let i = 0; i < targets.length; i++) {
  1316. const target = targets[i];
  1317. if (!target || updated.has(target)) {
  1318. continue;
  1319. }
  1320. updated.add(target);
  1321. this.mergeVideoItemWithPayload(target, payload);
  1322. if (isRemoteCloudType(target.type) && StrUtil.isNotEmpty(target.filePath)) {
  1323. remoteMetadataUpdates.set(target.filePath, {
  1324. filePath: target.filePath,
  1325. pixelMapPath: target.pixelMapPath,
  1326. name: target.name,
  1327. artist: target.artist
  1328. });
  1329. }
  1330. }
  1331. if (this.currentSong && this.currentSong.filePath === filePath) {
  1332. this.mergeVideoItemWithPayload(this.currentSong, payload);
  1333. if (payload.name) {
  1334. this.name = payload.name;
  1335. }
  1336. if (payload.artist) {
  1337. this.artist = payload.artist;
  1338. }
  1339. if (payload.pixelMapPath) {
  1340. this.cover = payload.pixelMapPath;
  1341. }
  1342. if (payload.lyricContent) {
  1343. this.applyInlineLyricContent(payload.lyricContent);
  1344. }
  1345. let avSessionDurationMs: number = this.duration;
  1346. if (payload.duration) {
  1347. const durationSeconds = Number(payload.duration);
  1348. if (!Number.isNaN(durationSeconds) && durationSeconds > 0) {
  1349. avSessionDurationMs = durationSeconds * 1000;
  1350. this.duration = avSessionDurationMs;
  1351. this.durationTime = Math.floor(avSessionDurationMs / 1000);
  1352. this.durationStringTime = secondToTime(this.durationTime);
  1353. }
  1354. }
  1355. if (avSessionDurationMs > 0) {
  1356. this.avSessionController.setAVMetadataMusic(this.currentSong, avSessionDurationMs, this.lyricContent);
  1357. }
  1358. this.currentSong = cloneVideoItem(this.currentSong);
  1359. AppStorage.setOrCreate('currentSong', this.currentSong);
  1360. }
  1361. const primaryTarget = targets.length > 0 ? targets[0] : undefined;
  1362. if (primaryTarget) {
  1363. this.persistRemoteMetadataToDb(primaryTarget).catch((error: Error) => {
  1364. Logger.error(TAG, `缓存元数据持久化失败: ${error.message}`);
  1365. });
  1366. }
  1367. if (remoteMetadataUpdates.size > 0) {
  1368. const eventUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
  1369. emitter.emit(eventUpdate, { data: Array.from(remoteMetadataUpdates.values()) });
  1370. }
  1371. this.refreshLazyListViews(mainListUpdated, playlistUpdated);
  1372. }
  1373. private handleEditMusicResult(result: WorkerEditMusicResult): void {
  1374. // 关闭进度条
  1375. DialogHelper.closeDialog(this.loadingDialogId)
  1376. if (result.success) {
  1377. console.log("heanup 编辑信息成功,数据库已同步");
  1378. if (result.coverResult) {
  1379. ToastUtil.showToast('内嵌封面成功');
  1380. }
  1381. ToastUtil.showToast('内嵌音乐标签成功');
  1382. this.isShowMoreView = false;
  1383. this.name = this.titleStr;
  1384. // 同步当前播放的歌曲信息
  1385. if (this.editingItem && this.currentSong && this.editingItem.filePath == this.currentSong.filePath) {
  1386. this.currentSong.name = this.titleStr;
  1387. this.artist = this.artistStr;
  1388. this.currentSong.artist = this.artistStr;
  1389. this.currentSong.album = this.ablumStr;
  1390. this.currentSong.year = this.yearStr;
  1391. this.currentSong.genre = this.genreStr;
  1392. this.currentSong.track = this.trackStr;
  1393. this.currentSong.lyricContent = this.lyricConStr;
  1394. this.currentSong.ALBUMARTIST = this.albumArtistStr;
  1395. this.currentSong.COMPOSER = this.composerStr;
  1396. this.currentSong.LYRICIST = this.lyricistStr;
  1397. this.currentSong.COMMENT = this.commentStr;
  1398. }
  1399. // if (result.needRefreshList && this.modeType == 0) {
  1400. // this.deleteCache(this.currentPath);
  1401. // this.getSortedFiles(this.currentPath);
  1402. // }
  1403. // 同步编辑字段到本地列表
  1404. if (this.editingItem) {
  1405. this.syncEditedFields(this.editingItem);
  1406. this.syncListsAfterEdit(this.editingItem.filePath);
  1407. this.doUpateEditedFields(this.editingItem);
  1408. }
  1409. // 清理临时变量
  1410. this.longItemFilePath = '';
  1411. this.tempLyricContent = '';
  1412. this.isShowEdit = false;
  1413. this.imagePathStr = '';
  1414. } else {
  1415. console.error("heanup 编辑信息失败: " + result.error);
  1416. ToastUtil.showToast('编辑失败: ' + (result.error || '未知错误'));
  1417. // 清理临时变量
  1418. this.longItemFilePath = '';
  1419. this.tempLyricContent = '';
  1420. this.isShowEdit = false;
  1421. this.imagePathStr = '';
  1422. }
  1423. }
  1424. private assignStringMetadata(target: VideoItem, key: keyof VideoItem, value?: string | null, allowEmpty = false): void {
  1425. if (value === undefined || value === null) {
  1426. return;
  1427. }
  1428. const text = value.toString();
  1429. if (!allowEmpty && text.trim().length === 0) {
  1430. return;
  1431. }
  1432. Reflect.set(target, key as string, value);
  1433. }
  1434. private assignNumberMetadata(target: VideoItem, key: keyof VideoItem, value?: number | null): void {
  1435. if (value === undefined || value === null || Number.isNaN(value)) {
  1436. return;
  1437. }
  1438. Reflect.set(target, key as string, value);
  1439. }
  1440. private mergeVideoItemWithPayload(target: VideoItem, payload: WorkerMetadataPayload): void {
  1441. if (!target || !payload) {
  1442. return;
  1443. }
  1444. this.assignStringMetadata(target, 'name', payload.name);
  1445. this.assignStringMetadata(target, 'artist', payload.artist);
  1446. this.assignStringMetadata(target, 'album', payload.album);
  1447. this.assignStringMetadata(target, 'bit_rate', payload.bit_rate);
  1448. this.assignStringMetadata(target, 'duration', payload.duration);
  1449. this.assignStringMetadata(target, 'sampleRate', payload.sampleRate);
  1450. this.assignStringMetadata(target, 'mimeType', payload.mimeType);
  1451. this.assignStringMetadata(target, 'size', payload.size);
  1452. this.assignStringMetadata(target, 'pixelMapPath', payload.pixelMapPath);
  1453. this.assignStringMetadata(target, 'lyricContent', payload.lyricContent, true);
  1454. this.assignStringMetadata(target, 'genre', payload.genre);
  1455. this.assignStringMetadata(target, 'track', payload.track);
  1456. this.assignStringMetadata(target, 'bits_per_raw_sample', payload.bits_per_raw_sample);
  1457. this.assignStringMetadata(target, 'channels', payload.channels);
  1458. this.assignStringMetadata(target, 'channel_layout', payload.channel_layout);
  1459. this.assignStringMetadata(target, 'start_time', payload.start_time);
  1460. this.assignStringMetadata(target, 'year', payload.year);
  1461. this.assignStringMetadata(target, 'disc', payload.disc);
  1462. this.assignStringMetadata(target, 'ALBUMARTIST', payload.ALBUMARTIST);
  1463. this.assignStringMetadata(target, 'COMPOSER', payload.COMPOSER);
  1464. this.assignStringMetadata(target, 'LYRICIST', payload.LYRICIST);
  1465. this.assignStringMetadata(target, 'COMMENT', payload.COMMENT, true);
  1466. this.assignNumberMetadata(target, 'videoSize', payload.videoSize);
  1467. this.assignNumberMetadata(target, 'probe_score', payload.probe_score);
  1468. this.assignNumberMetadata(target, 'nb_streams', payload.nb_streams);
  1469. this.assignNumberMetadata(target, 'nb_programs', payload.nb_programs);
  1470. }
  1471. private mergeVideoItemFromSource(target: VideoItem, source: VideoItem): void {
  1472. if (!target || !source) {
  1473. return;
  1474. }
  1475. this.assignStringMetadata(target, 'name', source.name);
  1476. this.assignStringMetadata(target, 'artist', source.artist);
  1477. this.assignStringMetadata(target, 'album', source.album);
  1478. this.assignStringMetadata(target, 'bit_rate', source.bit_rate);
  1479. this.assignStringMetadata(target, 'duration', source.duration);
  1480. this.assignStringMetadata(target, 'sampleRate', source.sampleRate);
  1481. this.assignStringMetadata(target, 'trackCount', source.trackCount);
  1482. this.assignStringMetadata(target, 'mimeType', source.mimeType);
  1483. this.assignStringMetadata(target, 'size', source.size);
  1484. this.assignStringMetadata(target, 'pixelMapPath', source.pixelMapPath);
  1485. this.assignStringMetadata(target, 'lyricContent', source.lyricContent, true);
  1486. this.assignStringMetadata(target, 'genre', source.genre);
  1487. this.assignStringMetadata(target, 'track', source.track);
  1488. this.assignStringMetadata(target, 'bits_per_raw_sample', source.bits_per_raw_sample);
  1489. this.assignStringMetadata(target, 'channels', source.channels);
  1490. this.assignStringMetadata(target, 'channel_layout', source.channel_layout);
  1491. this.assignStringMetadata(target, 'start_time', source.start_time);
  1492. this.assignStringMetadata(target, 'year', source.year);
  1493. this.assignStringMetadata(target, 'disc', source.disc);
  1494. this.assignStringMetadata(target, 'ALBUMARTIST', source.ALBUMARTIST);
  1495. this.assignStringMetadata(target, 'COMPOSER', source.COMPOSER);
  1496. this.assignStringMetadata(target, 'LYRICIST', source.LYRICIST);
  1497. this.assignStringMetadata(target, 'COMMENT', source.COMMENT, true);
  1498. this.assignNumberMetadata(target, 'videoSize', source.videoSize);
  1499. this.assignNumberMetadata(target, 'probe_score', source.probe_score);
  1500. this.assignNumberMetadata(target, 'nb_streams', source.nb_streams);
  1501. this.assignNumberMetadata(target, 'nb_programs', source.nb_programs);
  1502. if (source.remote_rel_path && StrUtil.isEmpty(target.remote_rel_path)) {
  1503. target.remote_rel_path = source.remote_rel_path;
  1504. }
  1505. }
  1506. private async hydrateRemoteSongFromDb(item: VideoItem | undefined): Promise<void> {
  1507. if (!item || !isRemoteCloudType(item.type)) {
  1508. return;
  1509. }
  1510. const storagePath = item.remote_rel_path || WebDavUrlUtil.toStoragePath(item.filePath);
  1511. if (!storagePath) {
  1512. return;
  1513. }
  1514. try {
  1515. const cached = await this.table.queryVideoByFilePath(storagePath);
  1516. if (!cached) {
  1517. return;
  1518. }
  1519. this.mergeVideoItemFromSource(item, cached);
  1520. if (StrUtil.isEmpty(item.remote_rel_path)) {
  1521. item.remote_rel_path = storagePath;
  1522. }
  1523. if (item === this.currentSong) {
  1524. if (StrUtil.isNotEmpty(item.name)) {
  1525. this.name = item.name;
  1526. }
  1527. if (StrUtil.isNotEmpty(item.artist)) {
  1528. this.artist = item.artist!;
  1529. }
  1530. if (StrUtil.isNotEmpty(item.pixelMapPath)) {
  1531. this.cover = item.pixelMapPath!;
  1532. }
  1533. if (StrUtil.isNotEmpty(item.lyricContent) && StrUtil.isEmpty(this.lyricContent)) {
  1534. this.applyInlineLyricContent(item.lyricContent as string);
  1535. }
  1536. }
  1537. } catch (error) {
  1538. Logger.error(TAG, `hydrateRemoteSongFromDb 失败: ${(error as Error).message}`);
  1539. }
  1540. }
  1541. private applyInlineLyricContent(content: string): void {
  1542. if (StrUtil.isEmpty(content)) {
  1543. return;
  1544. }
  1545. this.lyricContent = content;
  1546. const lines: string[] = content.split('\n').map((line: string) => line.trim());
  1547. const lyric: Lyric = this.parser.parse(lines);
  1548. this.lyricController.setLyric(lyric);
  1549. this.lyricControllerXF.setLyric(lyric);
  1550. this.lyricControllerSingle.setLyric(lyric);
  1551. }
  1552. private extractParentPathFromStoragePath(path: string): string {
  1553. if (!path) {
  1554. return '';
  1555. }
  1556. const lastSlash = path.lastIndexOf('/');
  1557. if (lastSlash <= 0) {
  1558. return '';
  1559. }
  1560. return path.substring(0, lastSlash);
  1561. }
  1562. private resolveRemoteStoragePath(target: VideoItem): string | null {
  1563. if (!target || !isRemoteCloudType(target.type)) {
  1564. return null;
  1565. }
  1566. if (isWebDavType(target.type)) {
  1567. const storagePath = target.remote_rel_path || WebDavUrlUtil.toStoragePath(target.filePath);
  1568. if (storagePath) {
  1569. target.remote_rel_path = storagePath;
  1570. return storagePath;
  1571. }
  1572. return null;
  1573. }
  1574. if (target.remote_rel_path && target.remote_rel_path.length > 0) {
  1575. return target.remote_rel_path;
  1576. }
  1577. return null;
  1578. }
  1579. private async persistRemoteMetadataToDb(target: VideoItem): Promise<void> {
  1580. if (!this.context || !target || !isRemoteCloudType(target.type)) {
  1581. return;
  1582. }
  1583. const storagePath = this.resolveRemoteStoragePath(target);
  1584. if (!storagePath) {
  1585. return;
  1586. }
  1587. const table = new MediaTable(this.context);
  1588. await new Promise<void>((resolve) => {
  1589. table.getRdbStore(this.context as Context, () => resolve());
  1590. });
  1591. const cloneItem = cloneVideoItem(target);
  1592. cloneItem.filePath = storagePath;
  1593. cloneItem.remote_rel_path = storagePath;
  1594. cloneItem.parentPath = this.extractParentPathFromStoragePath(storagePath);
  1595. await table.saveOrUpdateWebDavItem(cloneItem);
  1596. }
  1597. onPageHide(): void {
  1598. this.knockController?.immersiveDisableListening();
  1599. }
  1600. @State isFirstStartPlay: boolean = false
  1601. private async startFileDeletionWatcher(): Promise<void> {
  1602. if (!this.rootPath) {
  1603. return;
  1604. }
  1605. if (!this.deletionWatcher) {
  1606. this.deletionWatcher = new FileDeletionWatcher(this.context, this.table);
  1607. }
  1608. try {
  1609. await this.deletionWatcher.watchDirectories([
  1610. this.rootPath,
  1611. this.lockPath,
  1612. this.favPath,
  1613. this.historyPath
  1614. ]);
  1615. } catch (error) {
  1616. Logger.error(TAG, `初始化文件删除监听失败: ${(error as Error).message}`);
  1617. }
  1618. }
  1619. //获取download_path
  1620. async mkDownLoadDir() {
  1621. const documentViewPicker = new picker.DocumentViewPicker()
  1622. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  1623. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  1624. PreferencesUtil.putSync('download_path', this.rootPath+'/')
  1625. this.currentPath = this.rootPath
  1626. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  1627. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  1628. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  1629. Logger.info('onecold rootPath = ' + this.rootPath)
  1630. Logger.info('onecold lockPath = ' + this.lockPath)
  1631. if (!FileUtil.accessSync(this.lockPath)) {
  1632. FileUtil.mkdirSync(this.lockPath)
  1633. }
  1634. if (!FileUtil.accessSync(this.favPath)) {
  1635. FileUtil.mkdirSync(this.favPath)
  1636. }
  1637. if (!FileUtil.accessSync(this.historyPath)) {
  1638. FileUtil.mkdirSync(this.historyPath)
  1639. }
  1640. // await this.startFileDeletionWatcher();
  1641. this.getSortedFiles(this.rootPath).then(async () => {
  1642. this.isFavMusic = false
  1643. //穿山甲
  1644. // this.loadBannerAd(CSJUtil.getBannerID())
  1645. this.restoreLastPlayContext();
  1646. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  1647. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  1648. if (ArrayUtil.isEmpty(this.songList)) {
  1649. this.songList = this.getCurFileList()
  1650. } else {
  1651. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  1652. }
  1653. if (ArrayUtil.isNotEmpty(this.songList)) {
  1654. this.isFirstStartPlay = true
  1655. this.sonDataSource.pushArrayData(this.songList)
  1656. if (this.currentSong === undefined) {
  1657. this.isFirstStartPlay = false
  1658. this.currentSong = this.songList[0]
  1659. }
  1660. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  1661. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  1662. context: this.context,
  1663. autoParseMusicName: this.autoParseMusicName
  1664. });
  1665. Logger.info(TAG, `WebDAV URL同步构建完成: ${this.videoUrl}`);
  1666. this.name = this.currentSong.name
  1667. this.cover = this.currentSong.pixelMapPath
  1668. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  1669. } else {
  1670. this.name = '空空如也'
  1671. }
  1672. })
  1673. this.getFavList(false)
  1674. }
  1675. getFavList(isFavRefresh: boolean) {
  1676. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  1677. this.favList = result
  1678. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  1679. this.videoLocalList = this.favList
  1680. this.updateListData(this.videoLocalList, true)
  1681. }
  1682. })
  1683. }
  1684. getHistoryList(isRefresh: boolean) {
  1685. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  1686. this.historyList = result
  1687. // for (let i = 0; i < this.historyList.length; i++) {
  1688. //
  1689. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  1690. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  1691. // }
  1692. if (isRefresh) {
  1693. this.videoLocalList = this.historyList
  1694. this.updateListData(this.videoLocalList, true)
  1695. }
  1696. })
  1697. }
  1698. // 组件消失生命周期
  1699. aboutToDisappear() {
  1700. console.info('LifeCycleComponent aboutToDisappear');
  1701. this.deletionWatcher?.stop();
  1702. this.knockController?.immersiveDisableListening();
  1703. this.curIndex = 0
  1704. emitter.off(EventConstants.EVENT_AUDIO_OPEN);
  1705. emitter.off(EventConstants.EVENT_SCAN_UPDATE);
  1706. emitter.off(EventConstants.EVENT_SWIPE_BACK_UPDATE);
  1707. emitter.off(EventConstants.EVENT_SETTING_UPDATE);
  1708. emitter.off(EventConstants.EVENT_WEBDAV_METADATA_UPDATED);
  1709. emitter.off(EventConstants.EVENT_EQUALIZER_CHANGED);
  1710. this.mDestroyPage = true;
  1711. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  1712. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  1713. this.stop();
  1714. }
  1715. this.mIjkMediaPlayer.off('audioInterrupt');
  1716. this.mIjkMediaPlayer.off('deviceChange');
  1717. if (workerInstance) {
  1718. workerInstance.terminate();
  1719. }
  1720. this.stopPip();
  1721. this.destroyPipController()
  1722. this.getUIContext().getHostContext()!.eventHub.off('playOrPause');
  1723. this.getUIContext().getHostContext()!.eventHub.off('playPrevious');
  1724. this.getUIContext().getHostContext()!.eventHub.off('playNext');
  1725. this.getUIContext().getHostContext()!.eventHub.off('showPlayerView');
  1726. this.getUIContext().getHostContext()!.eventHub.off('openPlayList');
  1727. }
  1728. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean,openItem?:VideoItem) {
  1729. this.isFavMusic = false
  1730. console.info('onecold getSortedFiles 1 curPath '+curPath)
  1731. if (isWorkerPost) {
  1732. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1733. }
  1734. if (this.modeType !== 0) {
  1735. return
  1736. }
  1737. console.info('onecold getSortedFiles 2')
  1738. this.isCanBack = false
  1739. this.currentPath = curPath
  1740. console.info('onecold getSortedFiles this.currentPath ='+this.currentPath)
  1741. this.titleName = getFileDirName(this.currentPath,this.rootPath)
  1742. if (curPath === this.rootPath) {
  1743. this.rightTopImage = $r('sys.symbol.sort')
  1744. } else {
  1745. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  1746. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  1747. this.rightTopImage = $r('sys.symbol.chevron_left')
  1748. }
  1749. }
  1750. // Get the current file list and calculate its hash
  1751. this.fileList = FileUtil.listFileSync(curPath);
  1752. const currentHash = simpleHash(this.fileList);
  1753. // Check cache
  1754. const cachedValue = this.findCache(curPath);
  1755. Logger.info('onecold cachedValue = ' + cachedValue)
  1756. const cachedHash = this.findStringCache(curPath + '_hash');
  1757. const cachedDirList = this.findCache(curPath + "_dirList");
  1758. if (cachedValue !== undefined&&!this.isRefreshing) {
  1759. // this.videoLocalList = cachedValue;
  1760. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  1761. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  1762. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  1763. }
  1764. this.isRefreshing = false
  1765. this.updateListData(cachedValue)
  1766. }
  1767. if (cachedDirList !== undefined) {
  1768. this.dirList = cachedDirList
  1769. }
  1770. //通过当前hash值和缓存hash判断list有没有变化
  1771. if (cachedValue && cachedHash === currentHash) {
  1772. return;
  1773. }
  1774. // this.fileList = FileUtil.listFileSync(curPath)
  1775. let directories: Array<VideoItem> = [];
  1776. let files: Array<VideoItem> = [];
  1777. for (let i = 0; i < this.fileList.length; i++) {
  1778. // console.info(`The name of file: ${this.fileList[i]}`);
  1779. let path = curPath + '/' + this.fileList[i]
  1780. if (FileUtil.isDirectory(path)) {
  1781. let item: VideoItem =
  1782. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  1783. '')
  1784. if (this.isShowDir(item.name)) {
  1785. directories.push(item);
  1786. }
  1787. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1788. // Utility.doSortListAscending(directories)
  1789. } else {
  1790. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  1791. let item: VideoItem =
  1792. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  1793. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  1794. files.push(item);
  1795. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1796. // this.doSortListAscending(files)
  1797. }
  1798. }
  1799. }
  1800. }
  1801. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  1802. if (this.currentPath !== this.lockPath) {
  1803. files = result;
  1804. }
  1805. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1806. Utility.doSortListAscending(files)
  1807. if (this.currentPath === this.rootPath) {
  1808. this.dirList = directories
  1809. this.addCache(curPath + "_dirList", this.dirList);
  1810. }
  1811. //插入广告先注释掉
  1812. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  1813. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  1814. // directories.push(adItem)
  1815. // }
  1816. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  1817. this.videoLocalList = directories.concat(files);
  1818. this.updateListData(this.videoLocalList)
  1819. if (ArrayUtil.isNotEmpty(files)) {
  1820. if (this.currentPath != this.rootPath) {
  1821. if (files) {
  1822. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  1823. }
  1824. }
  1825. // 缓存结果
  1826. this.addCache(curPath, this.videoLocalList);
  1827. await this.saveCacheToStorage(); // 保存缓存至本地存储
  1828. this.addStringCache(curPath + '_hash', currentHash);
  1829. }
  1830. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  1831. for (let i = 0; i < this.videoLocalList.length; i++) {
  1832. console.info(`onecold gengxin 1: ${this.videoLocalList[i].name}`);
  1833. }
  1834. // this.setButtonStatus()
  1835. this.openMusic(isOpen, destPath,openItem)
  1836. this.isRefreshing = false
  1837. });
  1838. }
  1839. //第三方app打开天天静听导入音乐后播放
  1840. openMusic(isOpen?: boolean, destPath?: string,openItem?:VideoItem){
  1841. if (isOpen&&destPath) {
  1842. if (destPath === undefined) {
  1843. // 处理 destPath 为 undefined 的情况
  1844. return
  1845. }
  1846. if (destPath.endsWith('.lrc')) {
  1847. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  1848. if (StrUtil.isNotEmpty(this.videoUrl)) {
  1849. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  1850. this.initLyric(lyricPath);
  1851. }
  1852. return
  1853. }
  1854. if(openItem){
  1855. this.doPlay(openItem,0,false,true)
  1856. // this.isShowPlay = true
  1857. this.setShowPlayTrue()
  1858. }
  1859. }
  1860. }
  1861. //扫描文件夹入库
  1862. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  1863. const files = FileUtil.listFileSync(curPath);
  1864. let mediaItems: VideoItem[] = [];
  1865. Logger.info('onecold scanDirectory start ')
  1866. for (const file of files) {
  1867. const fPath = `${curPath}/${file}`;
  1868. if (fPath === this.lockPath) {
  1869. Logger.info(`Skipping locked path: ${fPath}`);
  1870. continue;
  1871. }
  1872. if (FileUtil.isDirectory(fPath)) {
  1873. // Recursively scan subdirectories
  1874. const subDirItems = await this.scanDirectory(fPath);
  1875. mediaItems = mediaItems.concat(subDirItems);
  1876. } else {
  1877. Logger.info('onecold scanDirectory filePath = ' + fPath)
  1878. // Process media files
  1879. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  1880. let mediaItem: VideoItem =
  1881. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1882. mediaItems.push(mediaItem);
  1883. this.table.insert(mediaItem, (id: number) => {
  1884. });
  1885. }
  1886. }
  1887. }
  1888. return mediaItems;
  1889. }
  1890. updateListData(mList: Array<VideoItem>, noSort?: boolean) {
  1891. this.isShowTitleBar = true
  1892. this.getUIContext().animateTo({ duration: 666 }, () => {
  1893. this.opacityItem = 0.5;
  1894. });
  1895. setTimeout(() => {
  1896. this.videoLocalList = mList;
  1897. if (!noSort) {
  1898. if (this.modeType === 0 || this.modeType === 1) {
  1899. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1900. this.doSortType(this.sortType)
  1901. }
  1902. }
  1903. this.dataSource.pushArrayData(this.videoLocalList)
  1904. this.getUIContext().animateTo({ duration: 666 }, () => {
  1905. this.opacityItem = 1;
  1906. });
  1907. this.setButtonStatus()
  1908. //添加到字母索引表
  1909. this.setAlphaBet()
  1910. }, 200);
  1911. }
  1912. getCurFileList(): Array<VideoItem> {
  1913. if(this.isSearchMode){
  1914. return this.filteredList
  1915. }
  1916. let files: Array<VideoItem> = [];
  1917. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1918. for (let i = 0; i < this.videoLocalList.length; i++) {
  1919. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  1920. files.push(this.videoLocalList[i]);
  1921. }
  1922. }
  1923. }
  1924. return files
  1925. }
  1926. setButtonStatus() {
  1927. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1928. this.isZero = false
  1929. } else {
  1930. this.isZero = true
  1931. }
  1932. if (this.currentPath !== this.rootPath &&
  1933. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  1934. this.isHasDir = true //不为空,说明有子文件夹
  1935. } else {
  1936. this.isHasDir = false
  1937. }
  1938. }
  1939. private getPlayListDisplayCount(): number {
  1940. if (this.playQueueScope === 'history') {
  1941. return this.historyList.length;
  1942. }
  1943. if (this.playQueueScope === 'fav') {
  1944. return this.favList.length;
  1945. }
  1946. if (this.playQueueScope === 'playlist') {
  1947. return this.currentSongList.length;
  1948. }
  1949. if (this.playQueueScope === 'view' && this.modeType === 1 && this.totalCount > 0) {
  1950. return this.totalCount;
  1951. }
  1952. return this.songList.length;
  1953. }
  1954. private restoreLastPlayContext(): void {
  1955. const scope = PreferencesUtil.getStringSync('LastPlayQueueScope', 'view') as string;
  1956. if (scope === 'history' || scope === 'fav' || scope === 'playlist' || scope === 'single') {
  1957. this.playQueueScope = scope;
  1958. } else {
  1959. this.playQueueScope = 'view';
  1960. }
  1961. const lastModeType = PreferencesUtil.getNumberSync('LastPlayModeType', this.modeType);
  1962. const lastTotalCount = PreferencesUtil.getNumberSync('LastPlayTotalCount', 0);
  1963. if (lastModeType === 1 && this.totalCount === 0 && lastTotalCount > 0) {
  1964. this.totalCount = lastTotalCount;
  1965. }
  1966. }
  1967. private async hydrateFullMediaPlayListIfNeeded(isSonList:boolean = true): Promise<void> {
  1968. if (this.isHydratingPlayList) {
  1969. return;
  1970. }
  1971. if (this.playQueueScope !== 'view' || this.modeType !== 1) {
  1972. return;
  1973. }
  1974. if (this.totalCount === 0 || this.songList.length >= this.totalCount) {
  1975. return;
  1976. }
  1977. this.isHydratingPlayList = true;
  1978. try {
  1979. const fullList: VideoItem[] = [];
  1980. let pageIndex = 0;
  1981. let hasMore = true;
  1982. while (hasMore) {
  1983. const result = await this.table.queryMediaLibraryPaged({
  1984. pageIndex,
  1985. pageSize: this.pageSize,
  1986. sortType: this.sortType,
  1987. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  1988. isShowFileName: this.isShowFileName
  1989. });
  1990. if (result.items.length === 0) {
  1991. break;
  1992. }
  1993. fullList.push(...result.items);
  1994. hasMore = result.hasMore;
  1995. pageIndex += 1;
  1996. if (fullList.length >= result.totalCount) {
  1997. hasMore = false;
  1998. }
  1999. }
  2000. if (fullList.length > 0) {
  2001. if(isSonList){
  2002. this.songList = fullList;
  2003. this.sonDataSource.pushArrayData(this.songList);
  2004. }else{
  2005. this.videoLocalList = fullList;
  2006. this.dataSource.pushArrayData(this.videoLocalList);
  2007. }
  2008. }
  2009. } finally {
  2010. this.isHydratingPlayList = false;
  2011. }
  2012. }
  2013. @Builder
  2014. SortMenuBuilder() {
  2015. Menu() {
  2016. MenuItem({
  2017. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.person')),
  2018. content: "按艺术家",
  2019. builder: this.SubSortBuilder(SortMode.ByArtist),
  2020. symbolEndIcon: this.isSortTypeInRange(SortMode.ByArtist) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2021. })
  2022. MenuItem({
  2023. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat_size_square')),
  2024. content: "按专辑",
  2025. builder: this.SubSortBuilder(SortMode.ByAlbum),
  2026. symbolEndIcon: this.isSortTypeInRange(SortMode.ByAlbum) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2027. })
  2028. MenuItem({
  2029. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat')),
  2030. content: "按名称",
  2031. builder: this.SubSortBuilder(SortMode.ByName),
  2032. symbolEndIcon: this.isSortTypeInRange(SortMode.ByName) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2033. })
  2034. MenuItem({
  2035. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2036. content: $r('app.string.sort_by_time'),
  2037. builder: this.SubSortBuilder(SortMode.ByTime),
  2038. symbolEndIcon: this.isSortTypeInRange(SortMode.ByTime) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2039. })
  2040. MenuItem({
  2041. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  2042. content: '按碟片音轨号',
  2043. builder: this.SubSortBuilder(SortMode.ByDiscTrack),
  2044. symbolEndIcon: this.isSortTypeInRange(SortMode.ByDiscTrack) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2045. })
  2046. .visibility((this.modeType==0||(this.modeType==2&&this.isCanBack)||
  2047. (this.modeType==3&&this.isCanBack))?Visibility.Visible:Visibility.None)
  2048. }.attributeModifier(new MenuModifier())
  2049. }
  2050. @Builder
  2051. SortMenuForArtistAblumBuilder() {
  2052. Menu() {
  2053. MenuItem({
  2054. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat')),
  2055. content: "按名称",
  2056. builder: this.SubSortBuilder(SortMode.ByName),
  2057. symbolEndIcon: this.isSortTypeInRange(SortMode.ByName) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2058. })
  2059. MenuItem({
  2060. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2061. content: '按数量',
  2062. builder: this.SubSortBuilder(SortMode.ByCount),
  2063. symbolEndIcon: this.isSortTypeInRange(SortMode.ByCount) ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2064. })
  2065. }.attributeModifier(new MenuModifier())
  2066. }
  2067. @Builder SubSortBuilder(sortType: number){
  2068. Menu(){
  2069. MenuItem({
  2070. content: "升序",
  2071. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_up')),
  2072. symbolEndIcon: this.sortType === sortType ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2073. })
  2074. .onClick(async () => {
  2075. await this.doSortType(sortType)
  2076. })
  2077. MenuItem({
  2078. content: "降序",
  2079. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_down')),
  2080. symbolEndIcon: this.sortType === sortType + 1 ? new SymbolGlyphModifier($r('sys.symbol.checkmark')) : undefined
  2081. })
  2082. .onClick(async () => {
  2083. await this.doSortType(sortType + 1) // 降序的sortType = 升序的sortType + 1
  2084. })
  2085. }
  2086. }
  2087. async doSortType(index: number): Promise<void> {
  2088. Logger.info('heanup LocalMusic', `doSortType: 切换排序方式 sortType=${index}, mode=${this.modeType}, isCanBack=${this.isCanBack}`);
  2089. this.sortType = index;
  2090. this.saveSortTypeForCurrentMode(index);
  2091. // 详情页模式(modeType=2/3 且 isCanBack=true): 重新查询当前项目的歌曲
  2092. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  2093. await this.reloadCurrentDetailSongs();
  2094. } else {
  2095. // 分页模式下,排序需要重新从数据库查询
  2096. await this.resetAndLoadFirstPage();
  2097. }
  2098. }
  2099. /**
  2100. * 重新加载当前详情页(专辑/艺术家)的歌曲数据
  2101. * 用于详情页切换排序方式时重新查询并排序
  2102. */
  2103. private async reloadCurrentDetailSongs(): Promise<void> {
  2104. Logger.info('heanup LocalMusic', `reloadCurrentDetailSongs: modeType=${this.modeType}, titleName=${this.titleName}, sortType=${this.sortType}`);
  2105. try {
  2106. if (this.modeType === 2) {
  2107. // 艺术家详情页: 重新查询该艺术家的歌曲
  2108. const mList = await this.table.querySongsByArtist(this.titleName, this.sortType, this.isShowFileName);
  2109. if (ArrayUtil.isNotEmpty(mList)) {
  2110. // 使用带排序类型的缓存键
  2111. const cacheKey = `${this.titleName}_sort_${this.sortType}`;
  2112. this.artistMap.set(cacheKey, mList);
  2113. this.totalCount = mList.length;
  2114. // 使用 noSort=true 避免在 updateListData 中重新排序导致死循环
  2115. this.updateListData(mList, true);
  2116. Logger.info('heanup LocalMusic', `reloadCurrentDetailSongs: 艺术家详情页重新加载完成, 歌曲数=${mList.length}`);
  2117. }
  2118. } else if (this.modeType === 3) {
  2119. // 专辑详情页: 重新查询该专辑的歌曲
  2120. const albumList = await this.table.querySongsByAlbum(this.titleName, this.sortType, this.isShowFileName);
  2121. if (ArrayUtil.isNotEmpty(albumList)) {
  2122. // 使用带排序类型的缓存键
  2123. const cacheKey = `${this.titleName}_sort_${this.sortType}`;
  2124. this.albumMap.set(cacheKey, albumList);
  2125. this.totalCount = albumList.length;
  2126. // 使用 noSort=true 避免在 updateListData 中重新排序导致死循环
  2127. this.updateListData(albumList, true);
  2128. Logger.info('heanup LocalMusic', `reloadCurrentDetailSongs: 专辑详情页重新加载完成, 歌曲数=${albumList.length}`);
  2129. }
  2130. }
  2131. } catch (err) {
  2132. const error = err as Error;
  2133. Logger.error('heanup LocalMusic', `reloadCurrentDetailSongs error: ${error.message}`);
  2134. ToastUtil.showToast('重新加载数据失败');
  2135. }
  2136. }
  2137. /**
  2138. * 根据当前模式保存排序类型到不同的存储键
  2139. * 区分列表页和详情页的排序设置
  2140. */
  2141. private saveSortTypeForCurrentMode(sortType: number): void {
  2142. let storageKey = SettingPage.SORT_TYPE;
  2143. if (this.modeType === 2) {
  2144. // 艺术家模式
  2145. if (this.isCanBack) {
  2146. storageKey = 'SORT_TYPE_ARTIST_DETAIL'; // 艺术家详情页排序
  2147. } else {
  2148. storageKey = 'SORT_TYPE_ARTIST'; // 艺术家列表页排序
  2149. }
  2150. } else if (this.modeType === 3) {
  2151. // 专辑模式
  2152. if (this.isCanBack) {
  2153. storageKey = 'SORT_TYPE_ALBUM_DETAIL'; // 专辑详情页排序
  2154. } else {
  2155. storageKey = 'SORT_TYPE_ALBUM'; // 专辑列表页排序
  2156. }
  2157. } else {
  2158. storageKey = SettingPage.SORT_TYPE;
  2159. }
  2160. PreferencesUtil.putSync(storageKey, sortType);
  2161. Logger.info('heanup LocalMusic', `saveSortTypeForCurrentMode: mode=${this.modeType}, isCanBack=${this.isCanBack}, sortType=${sortType}, key=${storageKey}`);
  2162. }
  2163. /**
  2164. * 根据当前模式加载排序类型
  2165. * 区分列表页和详情页的排序设置
  2166. */
  2167. private loadSortTypeForCurrentMode(): number {
  2168. let storageKey = SettingPage.SORT_TYPE;
  2169. let defaultSortType = 4;
  2170. if (this.modeType === 2) {
  2171. // 艺术家模式
  2172. if (this.isCanBack) {
  2173. storageKey = 'SORT_TYPE_ARTIST_DETAIL'; // 艺术家详情页排序
  2174. defaultSortType = 4; // 详情页默认按名称升序
  2175. } else {
  2176. storageKey = 'SORT_TYPE_ARTIST'; // 艺术家列表页排序
  2177. defaultSortType = 9; // 列表页默认按数量降序
  2178. }
  2179. } else if (this.modeType === 3) {
  2180. // 专辑模式
  2181. if (this.isCanBack) {
  2182. storageKey = 'SORT_TYPE_ALBUM_DETAIL'; // 专辑详情页排序
  2183. defaultSortType = 4; // 详情页默认按名称升序
  2184. } else {
  2185. storageKey = 'SORT_TYPE_ALBUM'; // 专辑列表页排序
  2186. defaultSortType = 9; // 列表页默认按数量降序
  2187. }
  2188. }
  2189. return PreferencesUtil.getNumberSync(storageKey, defaultSortType);
  2190. }
  2191. /**
  2192. * 检查当前sortType是否在指定排序类型的范围内
  2193. * 用于判断是否显示打勾图标
  2194. * @param baseSortType 基础排序类型(升序的值)
  2195. * @returns 如果当前sortType是该排序类型的升序或降序,返回true
  2196. */
  2197. private isSortTypeInRange(baseSortType: number): boolean {
  2198. return this.sortType === baseSortType || this.sortType === baseSortType + 1;
  2199. }
  2200. showSheelDialog() {
  2201. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  2202. // this.showTips()
  2203. // return
  2204. // }
  2205. this.showAddDialog()
  2206. }
  2207. showAddDialog() {
  2208. if (this.modeType === 2 || this.modeType === 3) {
  2209. return
  2210. }
  2211. DialogHelper.showActionSheetDialog({
  2212. title: "请选择添加方式(建议歌词文件一起导入)",
  2213. sheets: [
  2214. { value: "新建文件夹", fontColor: $r('app.color.text_color') },
  2215. { value: "手动导入", fontColor: $r('app.color.text_color') },
  2216. { value: "自动导入", fontColor: $r('app.color.text_color') },
  2217. { value: "全选导入", fontColor: $r('app.color.text_color') },
  2218. ],
  2219. maskColor: Color.Transparent,
  2220. backgroundColor: $r('app.color.bg_card'),
  2221. transition: AnimationHelper.transitionInDown(555),
  2222. onAction: (index) => {
  2223. switch (index) {
  2224. case 0:
  2225. if (this.modeType === 0) {
  2226. this.showMkDialog()
  2227. } else {
  2228. ToastUtil.showToast('请切换到首页才能新建文件夹!')
  2229. }
  2230. break;
  2231. case 1:
  2232. this.callFilePickerSelectFile()
  2233. break;
  2234. case 2:
  2235. this.showTips()
  2236. break;
  2237. case 3:
  2238. this.goSelectMusic()
  2239. break;
  2240. }
  2241. }
  2242. })
  2243. }
  2244. //拉起音频
  2245. goSelectMusic() {
  2246. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  2247. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  2248. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  2249. ) {
  2250. ToastUtil.showToast('暂时不支持该设备')
  2251. return
  2252. }
  2253. try {
  2254. let documentSelectOptions = new picker.DocumentSelectOptions();
  2255. documentSelectOptions.authMode = true
  2256. documentSelectOptions.multiAuthMode = true
  2257. if( deviceInfo.sdkApiVersion>=21){//如果api大于21 ,可以支持1w首歌以上
  2258. documentSelectOptions.maxSelectNumber = 20000
  2259. }
  2260. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  2261. let documentPicker = new picker.DocumentViewPicker(this.context);
  2262. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  2263. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  2264. this.saveVideoDatas(documentSelectResult)
  2265. }
  2266. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  2267. JSON.stringify(documentSelectResult));
  2268. }).catch((err: BusinessError) => {
  2269. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  2270. });
  2271. } catch (error) {
  2272. let err: BusinessError = error as BusinessError;
  2273. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2274. }
  2275. }
  2276. async showTips() {
  2277. try {
  2278. this.getUIContext().getPromptAction().showDialog({
  2279. title: '导入指南',
  2280. message:'用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  2281. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  2282. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  2283. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后去文件扫描一下。\n',
  2284. buttons: [
  2285. {
  2286. text: '知道了',
  2287. color: '#000000'
  2288. },
  2289. ]
  2290. }, (err, data) => {
  2291. if (err) {
  2292. console.error('showDialog err: ' + err);
  2293. return;
  2294. }
  2295. console.info('showDialog success callback, click button: ' + data.index);
  2296. });
  2297. } catch (error) {
  2298. let message = (error as BusinessError).message;
  2299. let code = (error as BusinessError).code;
  2300. console.error(`showDialog args error code is ${code}, message is ${message}`);
  2301. };
  2302. }
  2303. showMkDialog() {
  2304. DialogHelper.showTextInputDialog({
  2305. title: '新建歌单',
  2306. maskColor: Color.Transparent,
  2307. text: '',
  2308. transition: AnimationHelper.transitionInDown(666),
  2309. onChange: (text) => {
  2310. console.error("onChange: " + text);
  2311. },
  2312. onAction: (action, dialogId, content) => {
  2313. // ToastUtil.showToast('content = ' +content)
  2314. if (action == DialogAction.TWO) {
  2315. const newName = content
  2316. const newPath = this.currentPath + '/' + newName
  2317. FileUtil.mkdir(newPath, true).then(() => {
  2318. this.cache.delete(this.currentPath); // 删除目标路径缓存
  2319. this.getSortedFiles(this.currentPath)
  2320. }).catch((error: BusinessError) => {
  2321. console.error(error.message);
  2322. });
  2323. }
  2324. }
  2325. })
  2326. }
  2327. @State progress: number = 0;
  2328. async saveVideoDatas(uris:string[],isOpen?:boolean){
  2329. if (ArrayUtil.isEmpty(uris)) {
  2330. return;
  2331. }
  2332. console.info('onecold this.isCopyFileToDownLoad = ' + this.isCopyFileToDownLoad);
  2333. if(this.isCopyFileToDownLoad||this.currentPath==this.lockPath||isOpen){
  2334. this.saveVideoDatasToDownLoad(uris,isOpen)
  2335. return
  2336. }
  2337. // 初始化进度条
  2338. this.progress = 0;
  2339. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  2340. progress: this.progress,
  2341. backCancel: false,
  2342. autoCancel: false,
  2343. loadColor: $r('app.color.title_bar_bg'),
  2344. fontColor: $r('app.color.title_bar_bg')
  2345. });
  2346. // 计算处理总数用于进度计算
  2347. const totalItems = uris.length;
  2348. let processedItems = 0;
  2349. for (let i = 0; i < uris.length; i++) {
  2350. let filePath = uris[i];
  2351. try {
  2352. if (this.currentPath !== this.lockPath) { // 判断不是私密音乐,才入库
  2353. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2354. let mediaItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context,
  2355. filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2356. console.info('onecold saveVideoDatas filePath = ' + filePath)
  2357. if (!filePath.includes(this.rootPath)) {
  2358. console.info('onecold saveVideoDatas mediaItem.parentPath111 = ' + mediaItem.parentPath)
  2359. mediaItem.parentPath = this.currentPath;
  2360. }
  2361. console.info('onecold saveVideoDatas mediaItem.parentPath = ' + mediaItem.parentPath)
  2362. this.table.insert(mediaItem, (id: number) => {
  2363. // 插入完成回调
  2364. });
  2365. }
  2366. }
  2367. // 更新进度
  2368. processedItems++;
  2369. this.progress = Math.floor((processedItems / totalItems) * 100);
  2370. DialogHelper.updateLoading(this.loadingProgressDialogId,` 正在处理 ${this.progress}%`, this.progress);
  2371. } catch (error) {
  2372. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2373. // 即使出错也更新进度
  2374. processedItems++;
  2375. this.progress = Math.floor((processedItems / totalItems) * 100);
  2376. DialogHelper.updateLoading(this.loadingProgressDialogId,` 正在处理 ${this.progress}%`, this.progress);
  2377. }
  2378. }
  2379. // 关闭进度条
  2380. DialogHelper.closeDialog(this.loadingProgressDialogId)
  2381. this.isZero = false
  2382. // 删除目标路径缓存
  2383. setTimeout(() => {
  2384. this.cache.delete(this.currentPath);
  2385. this.getSortedFiles(this.currentPath,false,uris[0],isOpen)
  2386. this.setButtonStatus()
  2387. }, 500);
  2388. }
  2389. async saveVideoDatasToDownLoad(uris: string[], isOpen?: boolean) {
  2390. if (ArrayUtil.isEmpty(uris)) {
  2391. return;
  2392. }
  2393. let newUris: string[] = [];
  2394. this.progress = 0
  2395. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  2396. progress: this.progress,
  2397. backCancel: false,
  2398. autoCancel: false,
  2399. loadColor: this.themeColor,
  2400. fontColor: this.themeColor
  2401. });
  2402. // 计算所有文件的总大小
  2403. let totalSize = 0;
  2404. for (let uri of uris) {
  2405. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  2406. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  2407. await fileIo.close(sourceFile.fd);
  2408. }
  2409. let totalRead = 0;
  2410. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  2411. Logger.info(TAG, 'destPath uri: ' + destPath);
  2412. for (let i = 0; i < uris.length; i++) {
  2413. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  2414. Logger.info(TAG, 'filePath uri: ' + filePath);
  2415. newUris.push(filePath);
  2416. try {
  2417. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  2418. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  2419. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  2420. const buffer = new ArrayBuffer(buffSize);
  2421. let len = await fileIo.read(sourceFile.fd, buffer);
  2422. while (len > 0) {
  2423. await fileIo.write(destFile.fd, buffer.slice(0, len));
  2424. totalRead += len;
  2425. // 计算总进度
  2426. this.progress = Math.floor((totalRead / totalSize) * 100);
  2427. DialogHelper.updateLoading( this.loadingProgressDialogId,`正在导入 ${this.progress}%`, this.progress);
  2428. len = await fileIo.read(sourceFile.fd, buffer);
  2429. }
  2430. await fileIo.close(sourceFile.fd);
  2431. await fileIo.close(destFile.fd);
  2432. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  2433. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2434. let mediaItem: VideoItem =
  2435. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2436. this.table.insert(mediaItem, (id: number) => {
  2437. // 删除目标路径缓存
  2438. this.cache.delete(this.currentPath);
  2439. this.getSortedFiles(this.currentPath, true, destPath, isOpen,mediaItem)
  2440. });
  2441. }
  2442. }
  2443. } catch (error) {
  2444. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2445. }
  2446. }
  2447. DialogHelper.closeDialog(this.loadingProgressDialogId);
  2448. this.isZero = false
  2449. Logger.info(TAG, 'scan select video result:' + newUris)
  2450. }
  2451. //拉起音频
  2452. // goSelectMusic(){
  2453. //
  2454. // try {
  2455. // let audioSelectOptions = new picker.AudioSelectOptions();
  2456. // let audioPicker = new picker.AudioViewPicker(this.context);
  2457. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  2458. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  2459. // this.saveVideoDatas(audioSelectResult)
  2460. // }
  2461. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  2462. // }).catch((err: BusinessError) => {
  2463. //
  2464. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  2465. // });
  2466. // } catch (error) {
  2467. // let err: BusinessError = error as BusinessError;
  2468. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2469. // }
  2470. //
  2471. //
  2472. //
  2473. // }
  2474. async goSelectImage(item: VideoItem): Promise<string | undefined> {
  2475. if (!item) {
  2476. return undefined;
  2477. }
  2478. try {
  2479. let selectUris: Array<string> = [];
  2480. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  2481. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  2482. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  2483. photoSelectOptions.maxSelectNumber = 1;
  2484. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  2485. selectUris = photoSelectResult.photoUris;
  2486. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  2487. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  2488. console.info('file fd: ' + file.fd);
  2489. let name = await MD5.digestSync(this.videoUrl)+'.jpg'
  2490. let imagePath = this.context.filesDir + FileUtil.separator + name
  2491. imagePath = fileUri.getUriFromPath(imagePath)
  2492. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  2493. fileIo.copyFileSync(file.fd, file2.fd)
  2494. fileIo.closeSync(file);
  2495. fileIo.closeSync(file2);
  2496. if (item.filePath == this.currentSong?.filePath) {
  2497. this.cover = imagePath
  2498. }
  2499. if (item) {
  2500. item.pixelMapPath = imagePath
  2501. }
  2502. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  2503. if (success) {
  2504. this.doUpdateData()
  2505. console.log("onecold 更新音乐封面成功,数据库已同步");
  2506. } else {
  2507. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  2508. }
  2509. });
  2510. LogUtil.debug("onecold this.cover =" + this.cover)
  2511. return FileUtil.getFilePath(imagePath); // Return the image path here
  2512. } catch (err) {
  2513. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  2514. return undefined;
  2515. }
  2516. }
  2517. // 拉起picker选择文件管理器
  2518. async callFilePickerSelectFile(): Promise<void> {
  2519. try {
  2520. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  2521. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  2522. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  2523. } else {
  2524. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  2525. }
  2526. let documentPicker = new picker.DocumentViewPicker();
  2527. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  2528. Logger.info(TAG,
  2529. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  2530. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  2531. this.saveVideoDatas(DocumentSelectResult)
  2532. }
  2533. }).catch((err: BusinessError) => {
  2534. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  2535. });
  2536. } catch (err) {
  2537. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  2538. }
  2539. }
  2540. //重命名的对话框
  2541. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  2542. if(!item.filePath.includes(this.packName)){
  2543. ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限重命名')
  2544. return
  2545. }
  2546. DialogHelper.showTextInputDialog({
  2547. title: '重命名',
  2548. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  2549. maskColor: Color.Transparent,
  2550. backgroundColor: Color.Grey,
  2551. transition: AnimationHelper.transitionInDown(666),
  2552. onChange: (text) => {
  2553. console.error("onChange: " + text);
  2554. },
  2555. onAction: (action, dialogId, content) => {
  2556. // ToastUtil.showToast('content = ' +content)
  2557. if (action == DialogAction.TWO) {
  2558. const newName = content
  2559. const newPath = this.currentPath + '/' + newName
  2560. console.log("onecold item = " + item.type);
  2561. this.doReName(index, newName, filePath, newPath, item)
  2562. }
  2563. }
  2564. })
  2565. }
  2566. //剪切 移动到另个文件夹的对话框
  2567. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  2568. Logger.info('onecold showCutDialog')
  2569. let mList: Array<string> = []
  2570. let rPath = this.rootPath
  2571. if (isCurrent) {
  2572. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2573. rPath = this.currentPath
  2574. } else {
  2575. mList = Utility.getNameList(this.dirList);
  2576. rPath = this.rootPath
  2577. }
  2578. let dataBean = new BubbleBean()
  2579. dataBean.data = mList
  2580. dataBean.color = this.themeColor
  2581. dataBean.onItemClick = (i) => {
  2582. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  2583. Logger.info('newPath = ' + newPath)
  2584. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  2585. ToastUtil.showToast('移动成功')
  2586. this.table.deleteData(item, () => {
  2587. });
  2588. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2589. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2590. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2591. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2592. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2593. this.table.insert(newItem, (id: number) => {
  2594. //加入数据库
  2595. });
  2596. }
  2597. this.cache.delete(this.currentPath); // 删除原路径缓存
  2598. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  2599. this.getSortedFiles(this.currentPath, true)
  2600. }).catch((error: BusinessError) => {
  2601. console.error(error.message);
  2602. });
  2603. XPopup.dismissTop()
  2604. }
  2605. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  2606. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  2607. popupPosition = PopupPosition.TOP
  2608. }
  2609. if (index <= 3) {
  2610. popupPosition = PopupPosition.BOTTOM
  2611. }
  2612. let pup: XPopup
  2613. if (this.isDarkMode) {
  2614. pup = XPopup.Builder()
  2615. .setPopupPosition(popupPosition)
  2616. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  2617. .setBackgroundColor(Color.Black)
  2618. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2619. .show()
  2620. } else {
  2621. pup = XPopup.Builder()
  2622. .setPopupPosition(popupPosition)
  2623. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  2624. .setBackgroundColor(Color.White)
  2625. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2626. .show()
  2627. }
  2628. }
  2629. //复制 到另个文件夹的对话框
  2630. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  2631. Logger.info('onecoldv showCopyDialog')
  2632. let mList: Array<string> = []
  2633. let rPath = this.rootPath
  2634. if (isCurrent) {
  2635. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2636. rPath = this.currentPath
  2637. } else {
  2638. mList = Utility.getNameList(this.dirList);
  2639. rPath = this.rootPath
  2640. }
  2641. let dataBean = new BubbleBean()
  2642. dataBean.data = mList
  2643. dataBean.isCopy = true
  2644. dataBean.color = this.themeColor
  2645. dataBean.onItemClick = (i) => {
  2646. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  2647. Logger.info('newPath = ' + newPath)
  2648. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  2649. ToastUtil.showToast('复制成功')
  2650. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  2651. this.getSortedFiles(this.currentPath)
  2652. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2653. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2654. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2655. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2656. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2657. this.table.insert(newItem, (id: number) => {
  2658. //加入数据库
  2659. });
  2660. }
  2661. }).catch((error: BusinessError) => {
  2662. console.error(error.message);
  2663. });
  2664. XPopup.dismissTop()
  2665. }
  2666. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  2667. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  2668. popupPosition = PopupPosition.TOP
  2669. }
  2670. if (index <= 3) {
  2671. popupPosition = PopupPosition.BOTTOM
  2672. }
  2673. let pup: XPopup
  2674. if (this.isDarkMode) {
  2675. pup = XPopup.Builder()
  2676. .setPopupPosition(popupPosition)
  2677. .atView(id)
  2678. .setMaxHeight('60%')
  2679. .setBackgroundColor(Color.Black)
  2680. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2681. .show();
  2682. } else {
  2683. pup = XPopup.Builder()
  2684. .setPopupPosition(popupPosition)
  2685. .atView(id)
  2686. .setMaxHeight('60%')
  2687. .setBackgroundColor(Color.White)
  2688. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2689. .show();
  2690. }
  2691. }
  2692. //重命名索引index的视频
  2693. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  2694. FileUtil.rename(oldPath, newPath).then(async () => {
  2695. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2696. if (info.type === CommonConstants.TYPE_IS_DIR) {
  2697. //如果是文件夹先删除源数据,再添加新数据
  2698. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  2699. if (success) {
  2700. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  2701. } else {
  2702. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  2703. }
  2704. });
  2705. this.scanDirectory(newPath)
  2706. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  2707. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  2708. if (success) {
  2709. console.log(" onecold 重命名成功,数据库已同步");
  2710. } else {
  2711. console.error(" onecold 重命名数据库失败原因: " + error);
  2712. }
  2713. });
  2714. }
  2715. let mediaItem: VideoItem =
  2716. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2717. this.videoLocalList[index] = mediaItem;
  2718. }
  2719. this.cache.delete(this.currentPath)
  2720. this.getSortedFiles(this.currentPath, true)
  2721. }).catch((error: BusinessError) => {
  2722. console.error(error.message);
  2723. });
  2724. }
  2725. build() {
  2726. Stack() {
  2727. this.ContentBuild()
  2728. Stack() {
  2729. Column()
  2730. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  2731. height: '95%',
  2732. dragBar: true,
  2733. showClose: true,
  2734. blurStyle: BlurStyle.Thin,
  2735. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  2736. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  2737. title: {
  2738. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  2739. + `(${this.getPlayListDisplayCount()}首)`
  2740. }
  2741. })
  2742. }
  2743. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  2744. modalTransition:ModalTransition.DEFAULT,
  2745. onWillDisappear: () => {
  2746. this.setShowPlayFalse()
  2747. },
  2748. })
  2749. }
  2750. .alignContent(Alignment.Bottom)
  2751. .width('100%')
  2752. .height('100%')
  2753. }
  2754. @Builder
  2755. ContentBuild() {
  2756. Scroll() {
  2757. Column() {
  2758. Stack() {
  2759. //libraryname加上去后onKeyEvent监听不了,因为目前的解决方案是上面的XComponent,去掉libraryname
  2760. XComponent({ id: 'for_onKeyEvent',type: XComponentType.SURFACE,
  2761. controller: this.xcomponentController })
  2762. .onLoad(async (event?: object) => {
  2763. })
  2764. .focusable(true)
  2765. .height(0)
  2766. .focusOnTouch(true)
  2767. .defaultFocus(true) // 自动获取键盘焦点
  2768. .onKeyEvent((event?: KeyEvent) => {
  2769. console.info('onecold点击 onKeyEvent')
  2770. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  2771. if (!event || event.type !== KeyType.Down) {
  2772. return;
  2773. }
  2774. console.info('onecold点击 onKeyEvent event.keyCode: ' + event.keyCode)
  2775. //空格键 Space key controls pause/play
  2776. if (event.keyCode === KeyCode.KEYCODE_SPACE|| event.keyCode === KeyCode.KEYCODE_MEDIA_PLAY_PAUSE) {
  2777. this.playOrPause()
  2778. }
  2779. if (event.keyCode === KeyCode.KEYCODE_DPAD_UP) {
  2780. this.playPrevious()
  2781. }
  2782. if (event.keyCode === KeyCode.KEYCODE_DPAD_DOWN) {
  2783. this.playNext()
  2784. }
  2785. // Right-click to fast forward
  2786. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  2787. this.fastForward()
  2788. }
  2789. // Left-click to rewind
  2790. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  2791. this.backForward()
  2792. }
  2793. })
  2794. Column() {
  2795. XComponent({
  2796. id: 'xcomponentId',
  2797. type: 'surface',
  2798. libraryname: 'ijkplayer_napi',
  2799. controller: this.xcomponentController
  2800. })
  2801. .onLoad((event?: object) => {
  2802. if (!!event) {
  2803. this.initDelayPlay(event);
  2804. }
  2805. })
  2806. .onDestroy(() => {
  2807. })
  2808. .width('100%')// .width(this.videoWidth)
  2809. .aspectRatio(this.videoAspectRatio)
  2810. }
  2811. .aspectRatio(this.videoAspectRatio)
  2812. .justifyContent(FlexAlign.Center)
  2813. .backgroundColor(Color.Transparent)
  2814. .visibility(Visibility.Hidden)
  2815. .height(CommonConstants.FULL_PERCENT)
  2816. .width(CommonConstants.FULL_PERCENT)
  2817. .bindSheet($$this.isABSheet, this.ABLoopSheet(), {
  2818. height:this.isLandscape?'80%': '43%',
  2819. dragBar: true,
  2820. showClose: true,
  2821. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  2822. blurStyle:BlurStyle.Thin,
  2823. backgroundColor:Color.Transparent,
  2824. title: { title: 'AB循环' }
  2825. })
  2826. Stack() {
  2827. Column() {
  2828. if(this.twoFingerType==4){
  2829. this.getWaterView()
  2830. }else{
  2831. if(this.isGridMusic){
  2832. this.getGridView()
  2833. }else {
  2834. this.getListView()
  2835. }
  2836. }
  2837. if (this.modeType ==0||this.modeType==4) {
  2838. Column() {
  2839. emptyView(this.themeColor)
  2840. }
  2841. .padding({ right:10 })
  2842. .onClick(()=>{
  2843. this.asyncCurrentPathOnlyFile()
  2844. })
  2845. .alignItems(HorizontalAlign.Center)
  2846. .position({ top: 200 })
  2847. .justifyContent(FlexAlign.Center)
  2848. .opacity(this.isZero ? 1 : 0)
  2849. .visibility(this.isZero&&!this.isLoadingPage && !this.isFavMusic && !this.isHistory
  2850. ? Visibility.Visible : Visibility.None)
  2851. .animation({
  2852. duration: 500,
  2853. curve: Curve.Friction // 可选动画曲线
  2854. })
  2855. .width('100%')
  2856. }
  2857. }
  2858. .layoutWeight(1)
  2859. .height('100%')
  2860. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  2861. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  2862. .onDrop((event?: DragEvent) => {
  2863. try {
  2864. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  2865. if (dragData !== undefined) {
  2866. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  2867. if (records.length > 0) {
  2868. for (let i = 0; i < records.length; i++) {
  2869. let types = records[i].getTypes();
  2870. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  2871. const fileUriUds =
  2872. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  2873. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  2874. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  2875. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  2876. this.targetFile = fileUriUds.oriUri;
  2877. this.saveVideoDatas([this.targetFile])
  2878. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  2879. }
  2880. }
  2881. }
  2882. } else {
  2883. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  2884. }
  2885. } else {
  2886. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  2887. }
  2888. } catch (error) {
  2889. const err = error as BusinessError;
  2890. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  2891. }
  2892. })
  2893. // 右侧居中的字母表索引
  2894. this.indexBuilder()
  2895. this.topTitleBar()
  2896. }
  2897. .alignContent(Alignment.Top)
  2898. .layoutWeight(1)
  2899. .height('100%')
  2900. Row() {
  2901. Button(this.isAllSelected ? '反选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  2902. .width(45)
  2903. .height(45)
  2904. .fontSize(10)
  2905. .margin({ top: 10, bottom: 10, right: 6 })
  2906. .backgroundColor(this.themeColor)
  2907. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2908. .onClick(() => {
  2909. if (this.isAllSelected) {
  2910. // 全不选
  2911. this.selectedFiles = [];
  2912. } else {
  2913. // 全选
  2914. this.selectedFiles = [...this.getCurFileList()];
  2915. }
  2916. this.isAllSelected = !this.isAllSelected;
  2917. })
  2918. Button('内嵌标签', { type: ButtonType.Capsule, stateEffect: true })
  2919. .width(72)
  2920. .height(45)
  2921. .fontSize(10)
  2922. .margin({ top: 10, bottom: 10, right: 6 })
  2923. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2924. .backgroundColor(this.themeColor)
  2925. .bindContentCover($$this.isOneKeyTags, this.TagsContentCoverBuilder(), {
  2926. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2927. })
  2928. .onClick(() => {
  2929. // if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  2930. this.isOneKeyTags = !this.isOneKeyTags
  2931. // }else{
  2932. // ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限批量内嵌标签,导入的时候请勾选复制一份。')
  2933. // }
  2934. })
  2935. Button('合并', { type: ButtonType.Circle, stateEffect: true })
  2936. .width(45)
  2937. .height(45)
  2938. .fontSize(10)
  2939. .margin({ top: 10, bottom: 10, right: 6 })
  2940. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2941. .backgroundColor(this.themeColor)
  2942. .bindContentCover($$this.isMergeAudio, this.MergeAudioBuilder(), {
  2943. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2944. })
  2945. .onClick(() => {
  2946. if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  2947. this.isMergeAudio = !this.isMergeAudio
  2948. }else{
  2949. ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限合并')
  2950. }
  2951. })
  2952. Button('+歌单', { type: ButtonType.Circle, stateEffect: true })
  2953. .width(45)
  2954. .height(45)
  2955. .fontSize(10)
  2956. .margin({ top: 10, bottom: 10, right: 6 })
  2957. .backgroundColor(this.themeColor)
  2958. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2959. .onClick(async () => {
  2960. this.longItemFilePath = ''
  2961. await this.openAddToPlaylistDialog(this.selectedFiles)
  2962. })
  2963. // Button('乱码', { type: ButtonType.Circle, stateEffect: true })
  2964. // .width(45)
  2965. // .height(45)
  2966. // .fontSize(10)
  2967. // .margin({ top: 10, bottom: 10, right: 6 })
  2968. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2969. // .backgroundColor(this.themeColor)
  2970. // .bindContentCover($$this.isFixMessy, this.FixMessyViewBuilder(), {
  2971. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2972. // })
  2973. // .onClick(() => {
  2974. // this.isFixMessy = !this.isFixMessy
  2975. // })
  2976. // Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  2977. // .width('35%')
  2978. // .height(60)
  2979. // .id('music_cut')
  2980. // .margin({ top: 10, bottom: 10, right: 6 })
  2981. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2982. // .backgroundColor(this.themeColor)
  2983. // .onClick(() => {
  2984. // this.showCutDialogForMultipleFiles(false, 'music_cut')
  2985. // })
  2986. //
  2987. // Button('移动', { type: ButtonType.Circle, stateEffect: true })
  2988. // .width('35%')
  2989. // .height(60)
  2990. // .id('music_cut_current')
  2991. // .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  2992. // .margin({ top: 10, bottom: 10, right: 6 })
  2993. // .backgroundColor(this.themeColor)
  2994. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2995. // .onClick(() => {
  2996. //
  2997. // this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  2998. // })
  2999. // Button('复制', { type: ButtonType.Circle, stateEffect: true })
  3000. // .width('35%')
  3001. // .height(60)
  3002. // .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  3003. // .margin({ top: 10, bottom: 10, right: 6 })
  3004. // .backgroundColor(this.themeColor)
  3005. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3006. // .onClick(() => {
  3007. // this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  3008. // })
  3009. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  3010. .width(45)
  3011. .height(45)
  3012. .fontSize(10)
  3013. .margin({ top: 10, bottom: 10, right: 6 })
  3014. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  3015. .backgroundColor(this.themeColor)
  3016. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3017. .onClick(() => {
  3018. this.showWarnIsDelete()
  3019. })
  3020. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  3021. .width(45)
  3022. .height(45)
  3023. .fontSize(10)
  3024. .margin({ top: 10, bottom: 10, right: 6 })
  3025. .backgroundColor(this.themeColor)
  3026. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3027. .onClick(() => {
  3028. this.selectedFiles = [];
  3029. this.isAllSelected = false
  3030. this.isMultiSelect = false
  3031. })
  3032. }
  3033. .width('100%')
  3034. .justifyContent(FlexAlign.Center)
  3035. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  3036. .opacity(this.isMultiSelect ? 1 : 0)
  3037. .animation({
  3038. duration: 666,
  3039. curve: 'ease-in-out' // 可选动画曲线
  3040. })
  3041. .position({ bottom: 20 }) // 将 Row 固定在底部
  3042. }
  3043. .width('100%')
  3044. .height('100%')
  3045. .alignContent(Alignment.Top)
  3046. }
  3047. .width('100%')
  3048. .height('100%')
  3049. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  3050. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  3051. .backgroundImagePosition(Alignment.Center)
  3052. .backdropBlur(this.blurValue)
  3053. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  3054. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  3055. }
  3056. }
  3057. //字母表索引
  3058. @Builder
  3059. indexBuilder(){
  3060. Column({space: 5}){
  3061. if(this.showZMIndex&&this.enableShowAlphabet){
  3062. if(this.isShowAlphaBet&&!(this.modeType==2&&!this.isCanBack)
  3063. &&!(this.modeType==3&&!this.isCanBack)){
  3064. AlphabetIndexer({arrayValue: this.alphaBet,selected: this.selectAlphaBetIndex})
  3065. .attributeModifier(this.alphaBetStyle)
  3066. .usingPopup(this.isTouchingAlphaBet)
  3067. .onAreaChange((old_value,new_value)=>{
  3068. this.alphabetHeight = new_value.height as number
  3069. })
  3070. .popupPosition({
  3071. x: 40,
  3072. y: this.alphabetHeight / 2
  3073. })
  3074. .onSelect((index: number) => {
  3075. void this.onSelectIndexItem(this.alphaBet[index])
  3076. })
  3077. .onTouch((event: TouchEvent) =>{
  3078. this.showAlphabetIndex()
  3079. if(event.type === TouchType.Up || event.type === TouchType.Cancel){
  3080. this.isTouchingAlphaBet = false
  3081. this.hideAlphabetIndexAfterDelay(1500)
  3082. }else{
  3083. this.isTouchingAlphaBet = true
  3084. }
  3085. })
  3086. .transition(
  3087. TransitionEffect.translate({x: 10})
  3088. .combine(TransitionEffect.opacity(0.1))
  3089. .animation({
  3090. duration: 150,
  3091. curve: Curve.EaseInOut,
  3092. })
  3093. )
  3094. }
  3095. }
  3096. if(this.showFindLocation){
  3097. if(!(this.showZMIndex&&this.enableShowAlphabet)){
  3098. Blank()
  3099. .layoutWeight(1)
  3100. }
  3101. PointLightDefaultButton({
  3102. isSysBol:true,
  3103. pointColor:Color.Gray,
  3104. imageResource:$r('sys.symbol.local_fill'),
  3105. isPx: false,
  3106. builderHeight: 30,
  3107. builderWidth: 30,
  3108. })
  3109. .onClick(() =>{
  3110. void this.locateCurrentSong();
  3111. })
  3112. .clickEffect({level:ClickEffectLevel.LIGHT,scale: 0.5})
  3113. .margin({
  3114. bottom: this.bottomSafeHeight+100,right:10
  3115. })
  3116. }
  3117. }
  3118. .padding({
  3119. bottom: 0
  3120. })
  3121. .margin({right:5})
  3122. .position({x:'92%'})
  3123. .height('100%')
  3124. .justifyContent(FlexAlign.Center)
  3125. .bindSheet($$this.isEqualizerSheet, this.EqualizerSheet(), {
  3126. height: '100%',
  3127. dragBar: true,
  3128. showClose: true,
  3129. preferType: SheetType.CENTER ,
  3130. blurStyle: BlurStyle.Thin,
  3131. title: { title: '均衡器' },
  3132. onDisappear: () => {
  3133. this.isEqualizerSheet = false
  3134. }
  3135. })
  3136. }
  3137. async onSelectIndexItem(letter: string) {
  3138. await this.ensureFullListForAlphabetIndex();
  3139. const findTargetIndex = (): number => {
  3140. const songs = this.videoLocalList;
  3141. for (let i = 0; i < songs.length; i++) {
  3142. const song = songs[i];
  3143. let text = this.isShowFileName ? song.fileName :
  3144. (song.type != CommonConstants.TYPE_IS_DIR && song.pyStr) ? song.pyStr : song.name;
  3145. if (this.sortType === 0 || this.sortType == 1) {
  3146. text = song.artist;
  3147. } else if (this.sortType === 2 || this.sortType == 3) {
  3148. text = song.album;
  3149. }
  3150. if (text) {
  3151. const firstPinyin = getFirstLetter(text);
  3152. if (firstPinyin && firstPinyin === letter) {
  3153. return i;
  3154. }
  3155. }
  3156. }
  3157. return -1;
  3158. };
  3159. const targetIndex = findTargetIndex();
  3160. if (targetIndex !== -1) {
  3161. if (this.isGridMusic || this.twoFingerType == 4) {
  3162. this.scroller.scrollToIndex(targetIndex, false);
  3163. } else {
  3164. this.listScroller.scrollToIndex(targetIndex);
  3165. }
  3166. }
  3167. }
  3168. private showAlphabetIndex(): void {
  3169. this.isShowAlphaBet = true;
  3170. if (this.alphaBetHideTimer) {
  3171. clearTimeout(this.alphaBetHideTimer);
  3172. this.alphaBetHideTimer = 0;
  3173. }
  3174. }
  3175. private hideAlphabetIndexAfterDelay(delayMs: number): void {
  3176. if (this.alphaBetHideTimer) {
  3177. clearTimeout(this.alphaBetHideTimer);
  3178. }
  3179. this.alphaBetHideTimer = setTimeout(() => {
  3180. if (!this.isTouchingAlphaBet) {
  3181. this.isShowAlphaBet = false;
  3182. }
  3183. this.alphaBetHideTimer = 0;
  3184. }, delayMs) as number;
  3185. }
  3186. private async ensureFullListForAlphabetIndex(): Promise<void> {
  3187. if (this.isLoadingPage) {
  3188. return;
  3189. }
  3190. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  3191. return;
  3192. }
  3193. if (this.totalCount === 0 || this.videoLocalList.length >= this.totalCount) {
  3194. return;
  3195. }
  3196. if (this.modeType !== 0 && this.modeType !== 1) {
  3197. return;
  3198. }
  3199. this.isLoadingPage = true;
  3200. try {
  3201. const options: PageQueryOptions = {
  3202. pageIndex: 0,
  3203. pageSize: this.totalCount,
  3204. sortType: this.sortType,
  3205. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  3206. isShowFileName: this.isShowFileName
  3207. };
  3208. if (this.modeType === 0) {
  3209. options.parentPath = this.currentPath;
  3210. }
  3211. let result: PageQueryResult;
  3212. if (this.modeType === 0) {
  3213. result = await this.table.queryByParentPathPaged(options);
  3214. if (!this.isSearchMode) {
  3215. const directories: VideoItem[] = await this.loadDirectories(this.currentPath);
  3216. result.items = [...directories, ...result.items];
  3217. result.totalCount += directories.length;
  3218. }
  3219. } else {
  3220. result = await this.table.queryMediaLibraryPaged(options);
  3221. }
  3222. this.videoLocalList = result.items;
  3223. this.dataSource.pushArrayData(this.videoLocalList);
  3224. this.pageCache.clear();
  3225. this.currentPage = 0;
  3226. this.totalCount = result.totalCount;
  3227. this.hasMoreData = false;
  3228. if (this.modeType === 1) {
  3229. this.mediaKuCount = result.totalCount;
  3230. }
  3231. this.setButtonStatus();
  3232. this.setAlphaBet();
  3233. } catch (err) {
  3234. const error = err as Error;
  3235. Logger.warn('heanup LocalMusic', `ensureFullListForAlphabetIndex error: ${error.message}`);
  3236. } finally {
  3237. this.isLoadingPage = false;
  3238. }
  3239. }
  3240. // 找到对应字母表的索引
  3241. findAlphaBetIndex(song: VideoItem):number{
  3242. let text = this.isShowFileName?song.fileName:
  3243. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  3244. if(this.sortType === 0||this.sortType==1){
  3245. text = song.artist
  3246. }else if(this.sortType === 2||this.sortType==3){
  3247. text = song.album
  3248. }
  3249. if(text){
  3250. let firstLetter = getFirstLetter(text)
  3251. for(let i=0;i<this.alphaBet.length;i++){
  3252. if(this.alphaBet[i] === firstLetter){
  3253. return i
  3254. }
  3255. }
  3256. }
  3257. return 0
  3258. }
  3259. async setAlphaBet(){
  3260. if(!this.showZMIndex){
  3261. return
  3262. }
  3263. if (this.modeType === 1 && this.totalCount > this.videoLocalList.length) {
  3264. await this.refreshAlphaBetFromMediaLibrary()
  3265. return
  3266. }
  3267. return new Promise<void>((resolve,reject) => {
  3268. try {
  3269. let songs = this.videoLocalList
  3270. if(songs.length > 40000){
  3271. this.alphaBet = []
  3272. resolve()
  3273. return
  3274. }
  3275. let alphabetSet = new Set<string>();
  3276. for (let song of songs) {
  3277. let text = this.isShowFileName?song.fileName:
  3278. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  3279. if(this.sortType === 0||this.sortType==1){
  3280. text = song.artist
  3281. }else if(this.sortType === 2||this.sortType==3){
  3282. text = song.album
  3283. }
  3284. if(text){
  3285. let firstPinyin = getFirstLetter(text)
  3286. if(!alphabetSet.has(firstPinyin)){
  3287. alphabetSet.add(firstPinyin)
  3288. }
  3289. }
  3290. // const pyStr = song.pyStr
  3291. // if(pyStr){
  3292. // if(!alphabetSet.has(pyStr)){
  3293. // alphabetSet.add(pyStr)
  3294. // }
  3295. // }
  3296. }
  3297. this.alphaBet = Array.from(alphabetSet).sort((a,b)=>{
  3298. if(this.sortType ===4||this.sortType==0||this.sortType==2||this.sortType==6){
  3299. return a.localeCompare(b)
  3300. }else{
  3301. return b.localeCompare(a)
  3302. }
  3303. })
  3304. if(this.videoLocalList.length > 0){
  3305. this.listScroller.scrollToIndex(0)
  3306. this.selectAlphaBetIndex = 0
  3307. }
  3308. resolve()
  3309. }catch (e) {
  3310. console.error('testTag','排序字母表出错',JSON.stringify(e))
  3311. resolve()
  3312. }
  3313. })
  3314. }
  3315. private async refreshAlphaBetFromMediaLibrary(): Promise<void> {
  3316. if (this.totalCount <= 0) {
  3317. return
  3318. }
  3319. if (this.totalCount > 40000) {
  3320. this.alphaBet = []
  3321. return
  3322. }
  3323. const keyword = this.isSearchMode ? this.searchText : ''
  3324. const cacheKey = `${this.modeType}-${this.sortType}-${this.isShowFileName}-${keyword}-${this.totalCount}`
  3325. if (this.alphaBetCacheKey === cacheKey && this.alphaBet.length > 0) {
  3326. return
  3327. }
  3328. const result = await this.table.queryMediaLibraryPaged({
  3329. pageIndex: 0,
  3330. pageSize: this.totalCount,
  3331. sortType: this.sortType,
  3332. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  3333. isShowFileName: this.isShowFileName
  3334. })
  3335. let alphabetSet = new Set<string>()
  3336. for (let song of result.items) {
  3337. let text = this.isShowFileName ? song.fileName :
  3338. (song.type != CommonConstants.TYPE_IS_DIR && song.pyStr) ? song.pyStr : song.name
  3339. if (this.sortType === 0 || this.sortType == 1) {
  3340. text = song.artist
  3341. } else if (this.sortType === 2 || this.sortType == 3) {
  3342. text = song.album
  3343. }
  3344. if (text) {
  3345. let firstPinyin = getFirstLetter(text)
  3346. if (!alphabetSet.has(firstPinyin)) {
  3347. alphabetSet.add(firstPinyin)
  3348. }
  3349. }
  3350. }
  3351. this.alphaBet = Array.from(alphabetSet).sort((a, b) => {
  3352. if (this.sortType === 4 || this.sortType == 0 || this.sortType == 2 || this.sortType == 6) {
  3353. return a.localeCompare(b)
  3354. } else {
  3355. return b.localeCompare(a)
  3356. }
  3357. })
  3358. this.alphaBetCacheKey = cacheKey
  3359. }
  3360. @Builder
  3361. topTitleBar(){
  3362. Column() {
  3363. Row({ space: 15 }) {
  3364. if (!this.isSearchMode ) {
  3365. //左侧滑动按钮
  3366. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3367. SymbolGlyph(this.rightTopImage)
  3368. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3369. }
  3370. .attributeModifier(new ButtonFancyModifier(40, 40))
  3371. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3372. .animation({ duration: 300, curve: Curve.Ease })
  3373. .onClick(() => {
  3374. this.doSwipBack()
  3375. })
  3376. .attributeModifier(new ShadowModifier())
  3377. .zIndex(0)
  3378. }else{
  3379. //左侧搜索返回按钮
  3380. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3381. SymbolGlyph($r('sys.symbol.chevron_left'))
  3382. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3383. }
  3384. .attributeModifier(new ButtonFancyModifier(40, 40))
  3385. .margin({bottom:5})
  3386. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3387. .animation({ duration: 300, curve: Curve.Ease })
  3388. .onClick(() => {
  3389. this.isSearchMode = false
  3390. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  3391. this.searchText = ''
  3392. this.getSortedFiles(this.currentPath)
  3393. return
  3394. }
  3395. this.onSearchInput('')
  3396. })
  3397. .attributeModifier(new ShadowModifier())
  3398. .zIndex(0)
  3399. }
  3400. if (!this.isSearchMode) {
  3401. Text(this.modeType==1?`${this.titleName}(${this.mediaKuCount}首)`:this.titleName)
  3402. .margin({left:3,right:10})
  3403. .fontColor($r('app.color.text_color'))
  3404. .fontSize(this.twoFingerType==3?17:16)
  3405. .maxLines(1)
  3406. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3407. .layoutWeight(1)
  3408. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3409. }
  3410. //搜索框
  3411. Search({ controller: this.searchController,value: this.searchText, placeholder: '搜索标题、艺术家...' })
  3412. .searchButton('搜索',{fontColor:this.themeColor})
  3413. .searchIcon({
  3414. src: $r('sys.media.ohos_ic_public_search_filled')
  3415. })
  3416. .cancelButton({
  3417. style: CancelButtonStyle.CONSTANT,
  3418. icon: {
  3419. src: $r('sys.media.ohos_ic_public_cancel_filled')
  3420. }
  3421. })
  3422. .layoutWeight(1)
  3423. .height(40)
  3424. .maxLength(20)
  3425. .backgroundColor(this.isDarkMode?Color.Black:'#F5F5F5')
  3426. .placeholderColor(Color.Grey)
  3427. .placeholderFont({ size: 14, weight: 400 })
  3428. .textFont({ size: 14, weight: 400 })
  3429. .onSubmit((value: string) => {
  3430. console.log('onecold onSubmit ='+value)
  3431. this.searchController.stopEditing()
  3432. if(this.modeType==0){
  3433. this.modeType =1//如果是首页 切换到媒体库搜索
  3434. }
  3435. this.onSearchInput(this.searchText);
  3436. })
  3437. .onChange((value: string) => {
  3438. console.log('onecold onChange ='+value)
  3439. if(this.modeType==0){
  3440. this.modeType =1//如果是首页 切换到媒体库搜索
  3441. }
  3442. this.onSearchInput(value);
  3443. })
  3444. .visibility(this.isSearchMode?Visibility.Visible:Visibility.None)
  3445. .animation({ duration: 300, curve: Curve.Ease })
  3446. //搜索按钮
  3447. if (!this.isSearchMode) {
  3448. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3449. SymbolGlyph($r('sys.symbol.magnifyingglass'))
  3450. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3451. }
  3452. .attributeModifier(new ButtonFancyModifier(40, 40))
  3453. .animation({ duration: 300, curve: Curve.Ease })
  3454. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3455. .attributeModifier(new ShadowModifier())
  3456. .zIndex(0)
  3457. .onClick(()=>{
  3458. this.isSearchMode = true
  3459. })
  3460. //排序按钮
  3461. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3462. SymbolGlyph($r('sys.symbol.list_number'))
  3463. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3464. }
  3465. .attributeModifier(new ButtonFancyModifier(40, 40))
  3466. .animation({ duration: 300, curve: Curve.Ease })
  3467. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3468. .bindMenu((this.modeType==2&&!this.isCanBack)||(this.modeType==3&&!this.isCanBack)
  3469. ?this.SortMenuForArtistAblumBuilder:this.SortMenuBuilder)
  3470. .attributeModifier(new ShadowModifier())
  3471. .zIndex(0)
  3472. //添加按钮
  3473. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3474. SymbolGlyph($r('sys.symbol.plus'))
  3475. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3476. }
  3477. .attributeModifier(new ButtonFancyModifier(40, 40))
  3478. .animation({ duration: 300, curve: Curve.Ease })
  3479. .visibility(this.modeType==0||this.modeType==1?Visibility.Visible:Visibility.None)
  3480. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3481. .bindSheet($$this.showAddSheet, this.addSheet(), {
  3482. height: SheetSize.FIT_CONTENT,
  3483. dragBar: true,
  3484. showClose: true,
  3485. preferType: SheetType.CENTER ,
  3486. title: {
  3487. title: '导入音乐'
  3488. }
  3489. })
  3490. .onClick(() => {
  3491. this.showAddSheet = !this.showAddSheet;
  3492. })
  3493. .attributeModifier(new ShadowModifier())
  3494. .zIndex(0)
  3495. }
  3496. }
  3497. }
  3498. .padding({ top: this.topSafeHeight+10, left: 10, right: 10 })
  3499. .width('100%')
  3500. .visibility(this.isShowTitleBar?Visibility.Visible:
  3501. this.autoHideTitle?Visibility.None:Visibility.Visible)
  3502. .animation({
  3503. duration: 500,
  3504. curve: Curve.Friction // 可选动画曲线
  3505. })
  3506. }
  3507. @Builder
  3508. addSheet() {
  3509. Scroll() {
  3510. Column() {
  3511. Column() {
  3512. Row() {
  3513. SymbolGlyph($r('sys.symbol.info_circle'))
  3514. .fontSize(22)
  3515. .fontColor([this.themeColor])
  3516. .alignSelf(ItemAlign.Center)
  3517. .margin({ left: 8 })
  3518. Text('导入音乐复制到DownLoad目录')
  3519. .margin({ left: 8 })
  3520. .fontSize(14)
  3521. .fontColor($r('app.color.text_color'))
  3522. .fontWeight(480)
  3523. .layoutWeight(1)
  3524. Toggle({ type: ToggleType.Switch, isOn: this.isCopyFileToDownLoad })
  3525. .selectedColor(this.themeColor)
  3526. .switchPointColor(Color.White)
  3527. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  3528. .margin({ right: 2 })
  3529. .onChange((checked: boolean) => {
  3530. this.isCopyFileToDownLoad = checked;
  3531. PreferencesUtil.put(SettingPage.IS_COPYFILE_TO_DOWNLOAD, this.isCopyFileToDownLoad)
  3532. })
  3533. .width(50)
  3534. .height(30);
  3535. }
  3536. .height(72)
  3537. .padding({ left:8,right:8 })
  3538. }
  3539. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3540. .backgroundColor($r('app.color.start_window_background'))
  3541. .borderRadius(15)
  3542. .width('85%')
  3543. .margin({
  3544. top: 10,
  3545. bottom: 10
  3546. })
  3547. .padding(0)
  3548. .border({
  3549. color: Color.White,
  3550. width: 1.8
  3551. })
  3552. Menu() {
  3553. MenuItem({
  3554. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder_badge_plus')),
  3555. content: "新建文件夹"
  3556. })
  3557. .backgroundColor($r('app.color.silvery'))
  3558. .border({
  3559. width: { bottom: 1 },
  3560. color: '#12ec5c87'
  3561. })
  3562. .margin(10)
  3563. .height(60)
  3564. .padding({left:15,right:15})
  3565. .onClick(async () => {
  3566. this.showMkDialog()
  3567. this.showAddSheet = !this.showAddSheet
  3568. })
  3569. MenuItem({
  3570. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder')),
  3571. content: $r('app.string.import_from_files')
  3572. })
  3573. .padding({left:15,right:15})
  3574. .backgroundColor($r('app.color.silvery'))
  3575. .border({
  3576. width: { bottom: 1 },
  3577. color: '#12ec5c87'
  3578. })
  3579. .margin(10)
  3580. .height(60)
  3581. .onClick(async () => {
  3582. this.callFilePickerSelectFile()
  3583. this.showAddSheet = !this.showAddSheet
  3584. })
  3585. MenuItem({
  3586. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square')),
  3587. content: '全选导入'
  3588. // content: '从下载文件夹导入(路径:Download/' +
  3589. // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
  3590. })
  3591. .padding({left:15,right:15})
  3592. .backgroundColor($r('app.color.silvery'))
  3593. .border({
  3594. width: { bottom: 1 },
  3595. color: '#12ec5c87'
  3596. })
  3597. .margin(10)
  3598. .height(60)
  3599. .onClick(async () => {
  3600. this.goSelectMusic()
  3601. this.showAddSheet = !this.showAddSheet
  3602. })
  3603. MenuItem({
  3604. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.save')),
  3605. content: '自动导入教程'
  3606. })
  3607. .padding({left:15,right:15})
  3608. .backgroundColor($r('app.color.silvery'))
  3609. .border({
  3610. width: { bottom: 1 },
  3611. color: '#12ec5c87'
  3612. })
  3613. .margin(10)
  3614. .height(60)
  3615. .onClick(async () => {
  3616. this.showTips()
  3617. this.showAddSheet = !this.showAddSheet
  3618. })
  3619. MenuItem({
  3620. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.questionmark_circle')),
  3621. content: '导入疑问'
  3622. })
  3623. .height(60)
  3624. .padding({left:15,right:15})
  3625. .backgroundColor($r('app.color.silvery'))
  3626. .border({
  3627. width: { bottom: 1 },
  3628. color: '#12ec5c87'
  3629. })
  3630. .margin(10)
  3631. .onClick(async () => {
  3632. this.showProblomTips()
  3633. this.showAddSheet = !this.showAddSheet
  3634. })
  3635. }.attributeModifier(new MenuModifier())
  3636. .margin({bottom:30})
  3637. .width('90%')
  3638. .borderRadius(15)
  3639. }
  3640. .layoutWeight(1)
  3641. }
  3642. }
  3643. async showProblomTips() {
  3644. try {
  3645. this.getUIContext().getPromptAction().showDialog({
  3646. title: '导入疑问',
  3647. message:'为什么有些歌曲导入成功后,内嵌标签或者其他功能不能用?:\n\n1、由于鸿蒙系统的安全策略,文件权限不够,请将文件移动到Download/天天静听目录下。' +
  3648. '这样内嵌标签功能就没有权限问题。\n\n2、导入可以也选择不复制,这样可以省略空间。\n\n',
  3649. buttons: [
  3650. {
  3651. text: '知道了',
  3652. color: '#000000'
  3653. },
  3654. ]
  3655. }, (err, data) => {
  3656. if (err) {
  3657. console.error('showDialog err: ' + err);
  3658. return;
  3659. }
  3660. console.info('showDialog success callback, click button: ' + data.index);
  3661. });
  3662. } catch (error) {
  3663. let message = (error as BusinessError).message;
  3664. let code = (error as BusinessError).code;
  3665. console.error(`showDialog args error code is ${code}, message is ${message}`);
  3666. };
  3667. }
  3668. @Builder
  3669. TagsContentCoverBuilder() {
  3670. Scroll() {
  3671. Column() {
  3672. TagsContentCover(
  3673. {
  3674. selectedFiles:this.selectedFiles,
  3675. isOneKeyTags:this.isOneKeyTags,
  3676. onSeePath:(path:string)=>{
  3677. this.modeType = 0
  3678. this.deleteCache(path)
  3679. this.getSortedFiles(path)
  3680. },
  3681. onTagsResult:(result: boolean,deleteCache_path?:string)=>{
  3682. this.isMultiSelect = false
  3683. if(result){//如果嵌入成功,更新数据
  3684. this.listRefreshKey++
  3685. setTimeout(()=>{
  3686. this.doUpdateData()
  3687. },500)
  3688. }
  3689. console.info('onecold onTagsResult deleteCache_path =' +deleteCache_path)
  3690. if(deleteCache_path){
  3691. this.deleteCache(deleteCache_path)
  3692. }
  3693. }
  3694. }
  3695. )
  3696. }
  3697. }
  3698. .width('100%')
  3699. .height('100%')
  3700. }
  3701. @Builder
  3702. FixMessyViewBuilder() {
  3703. Scroll() {
  3704. Column() {
  3705. FixMessyView(
  3706. {
  3707. selectedFiles:this.selectedFiles,
  3708. isFixMessy:this.isFixMessy,
  3709. onFixResult:(result: boolean)=>{
  3710. this.isMultiSelect = false
  3711. if(result){//如果嵌入成功,更新数据
  3712. this.deleteCache(this.currentPath)
  3713. this.doUpdateData()
  3714. }
  3715. }
  3716. }
  3717. )
  3718. }
  3719. }
  3720. .width('100%')
  3721. .height('100%')
  3722. }
  3723. //剪辑音频
  3724. @Builder
  3725. EditAudioBuilder(item:VideoItem) {
  3726. Scroll() {
  3727. Column() {
  3728. EditAudio(
  3729. {
  3730. mVideoItem:item,
  3731. currentPath:this.currentPath,
  3732. videoUrl:this.videoUrl,
  3733. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3734. currentTime:this.currentTime,
  3735. progressValue:this.progressValue,
  3736. onBack:()=>{
  3737. this.isEditAudio = !this.isEditAudio
  3738. },
  3739. onSeeOutputPath:(outPutPath:string)=>{
  3740. this.isEditAudio = !this.isEditAudio
  3741. this.longItemFilePath = ''
  3742. this.modeType = 0
  3743. this.isShowFileName = true
  3744. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3745. },
  3746. onPlayOrPause:()=>{
  3747. if(this.videoUrl==item.filePath){
  3748. this.playOrPause()
  3749. }else{//如果不是当前播放的,则播放该文件
  3750. this.videoUrl==item.filePath
  3751. this.doPlay(item,0,false,true)
  3752. }
  3753. },
  3754. onSliderChange:(value:number)=>{
  3755. if(this.videoUrl!=item.filePath){
  3756. this.videoUrl==item.filePath
  3757. return
  3758. }
  3759. this.isSeekTo = true;
  3760. this.mDestroyPage = false;
  3761. this.showLoadIng();
  3762. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  3763. let seekValue = value * (this.getActiveDuration() / 100);
  3764. this.seekTo(seekValue + "");
  3765. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  3766. this.isSeekTo = false;
  3767. },
  3768. onResult:(result: boolean,outPath:string)=>{
  3769. if(result){//如果剪辑成功,更新数据
  3770. this.doUpdateData()
  3771. }else{
  3772. ToastUtil.showToast('剪辑失败')
  3773. }
  3774. }
  3775. }
  3776. )
  3777. }
  3778. }
  3779. .width('100%')
  3780. .height('100%')
  3781. }
  3782. //提取伴奏
  3783. @Builder
  3784. ConverterBuilder(item:VideoItem) {
  3785. Scroll() {
  3786. Column() {
  3787. AudioFormatConverter(
  3788. {
  3789. mVideoItem:item,
  3790. videoUrl:this.videoUrl,
  3791. currentPath:this.currentPath,
  3792. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3793. currentTime:this.currentTime,
  3794. progressValue:this.progressValue,
  3795. onBack:()=>{
  3796. this.isConverter = !this.isConverter
  3797. this.longItemFilePath = ''
  3798. },
  3799. onPlayOrPause:()=>{
  3800. if(this.videoUrl==item.filePath){
  3801. this.playOrPause()
  3802. }else{//如果不是当前播放的,则播放该文件
  3803. this.videoUrl==item.filePath
  3804. this.doPlay(item,0,false,true)
  3805. }
  3806. },
  3807. onSeeOutputPath:(outPutPath:string)=>{
  3808. this.isConverter = !this.isConverter
  3809. this.longItemFilePath = ''
  3810. this.modeType = 0
  3811. this.isShowFileName = true
  3812. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3813. },
  3814. onSliderChange:(value:number)=>{
  3815. if(this.videoUrl!=item.filePath){
  3816. this.videoUrl==item.filePath
  3817. return
  3818. }
  3819. this.isSeekTo = true;
  3820. this.mDestroyPage = false;
  3821. this.showLoadIng();
  3822. let seekValue = value * (this.getActiveDuration() / 100);
  3823. this.seekTo(seekValue + "");
  3824. this.isSeekTo = false;
  3825. },
  3826. onResult:(result: boolean,outPath:string)=>{
  3827. if(result){//如果成功,更新数据
  3828. this.doUpdateData()
  3829. }else{
  3830. ToastUtil.showToast('格式转化失败')
  3831. }
  3832. }
  3833. }
  3834. )
  3835. }
  3836. }
  3837. .width('100%')
  3838. .height('100%')
  3839. }
  3840. //提取伴奏
  3841. @Builder
  3842. ExtractAccBuilder(item:VideoItem) {
  3843. Scroll() {
  3844. Column() {
  3845. ExtractAccompaniment(
  3846. {
  3847. mVideoItem:item,
  3848. currentPath:this.currentPath,
  3849. videoUrl:this.videoUrl,
  3850. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3851. currentTime:this.currentTime,
  3852. progressValue:this.progressValue,
  3853. onBack:()=>{
  3854. this.isExtractAcc = !this.isExtractAcc
  3855. this.longItemFilePath = ''
  3856. },
  3857. onPlayOrPause:()=>{
  3858. if(this.videoUrl==item.filePath){
  3859. this.playOrPause()
  3860. }else{//如果不是当前播放的,则播放该文件
  3861. this.videoUrl==item.filePath
  3862. this.doPlay(item,0,false,true)
  3863. }
  3864. },
  3865. onSeeOutputPath:(outPutPath:string)=>{
  3866. this.isExtractAcc = !this.isExtractAcc
  3867. this.longItemFilePath = ''
  3868. this.modeType = 0
  3869. this.isShowFileName = true
  3870. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3871. },
  3872. onSliderChange:(value:number)=>{
  3873. if(this.videoUrl!=item.filePath){
  3874. this.videoUrl==item.filePath
  3875. return
  3876. }
  3877. this.isSeekTo = true;
  3878. this.mDestroyPage = false;
  3879. this.showLoadIng();
  3880. let seekValue = value * (this.getActiveDuration() / 100);
  3881. this.seekTo(seekValue + "");
  3882. this.isSeekTo = false;
  3883. },
  3884. onResult:(result: boolean,outPath:string)=>{
  3885. if(result){//如果成功,更新数据
  3886. this.doUpdateData()
  3887. }else{
  3888. ToastUtil.showToast('提取伴奏失败')
  3889. }
  3890. }
  3891. }
  3892. )
  3893. }
  3894. }
  3895. .width('100%')
  3896. .height('100%')
  3897. }
  3898. //AI人声分离
  3899. @Builder
  3900. AiBuilder(item:VideoItem) {
  3901. Scroll() {
  3902. Column() {
  3903. AIVoiceSeparation(
  3904. {
  3905. mVideoItem:item,
  3906. videoUrl:this.videoUrl,
  3907. currentPath:this.currentPath,
  3908. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3909. currentTime:this.currentTime,
  3910. progressValue:this.progressValue,
  3911. onBack:()=>{
  3912. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  3913. this.longItemFilePath = ''
  3914. },
  3915. onPlayOrPause:()=>{
  3916. if(this.videoUrl==item.filePath||this.isPlaying){
  3917. this.playOrPause()
  3918. }else{//如果不是当前播放的,则播放该文件
  3919. this.videoUrl==item.filePath
  3920. this.doPlay(item,0,false,true)
  3921. }
  3922. },
  3923. onPlayPath:(path:string)=>{
  3924. this.videoUrl==path
  3925. const itemP = Utility.getItemByFilePath(this.videoLocalList,path)
  3926. if(itemP)
  3927. this.doPlay(itemP,0,false,true)
  3928. },
  3929. onSeeOutputPath:(outPutPath:string)=>{
  3930. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  3931. this.longItemFilePath = ''
  3932. this.modeType = 0
  3933. this.isShowFileName = true
  3934. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3935. },
  3936. onSliderChange:(value:number)=>{
  3937. if(this.videoUrl!=item.filePath){
  3938. this.videoUrl==item.filePath
  3939. return
  3940. }
  3941. this.isSeekTo = true;
  3942. this.mDestroyPage = false;
  3943. this.showLoadIng();
  3944. let seekValue = value * (this.getActiveDuration() / 100);
  3945. this.seekTo(seekValue + "");
  3946. this.isSeekTo = false;
  3947. },
  3948. onResult:(result: boolean,outPath:string)=>{
  3949. if(result){//如果成功,更新数据
  3950. this.doUpdateData()
  3951. }else{
  3952. ToastUtil.showToast('Ai人声分离失败')
  3953. }
  3954. }
  3955. }
  3956. )
  3957. }
  3958. }
  3959. .width('100%')
  3960. .height('100%')
  3961. }
  3962. //变速变调
  3963. @Builder
  3964. ChangeToneBuilder(item:VideoItem) {
  3965. Scroll() {
  3966. Column() {
  3967. ChangeTone(
  3968. {
  3969. mVideoItem:item,
  3970. currentPath:this.currentPath,
  3971. videoUrl:this.videoUrl,
  3972. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3973. currentTime:this.currentTime,
  3974. progressValue:this.progressValue,
  3975. onBack:()=>{
  3976. this.isChangeTone = !this.isChangeTone
  3977. this.longItemFilePath = ''
  3978. },
  3979. onPlayOrPause:()=>{
  3980. if(this.videoUrl==item.filePath){
  3981. this.playOrPause()
  3982. }else{//如果不是当前播放的,则播放该文件
  3983. this.videoUrl==item.filePath
  3984. this.doPlay(item,0,false,true)
  3985. }
  3986. },
  3987. onSeeOutputPath:(outPutPath:string)=>{
  3988. this.isChangeTone = !this.isChangeTone
  3989. this.longItemFilePath = ''
  3990. this.modeType = 0
  3991. this.isShowFileName = true
  3992. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3993. },
  3994. onSliderChange:(value:number)=>{
  3995. if(this.videoUrl!=item.filePath){
  3996. this.videoUrl==item.filePath
  3997. return
  3998. }
  3999. this.isSeekTo = true;
  4000. this.mDestroyPage = false;
  4001. this.showLoadIng();
  4002. let seekValue = value * (this.getActiveDuration() / 100);
  4003. this.seekTo(seekValue + "");
  4004. this.isSeekTo = false;
  4005. },
  4006. onResult:(result: boolean,outPath:string)=>{
  4007. if(result){//如果成功,更新数据
  4008. this.doUpdateData()
  4009. }else{
  4010. ToastUtil.showToast('变速变调失败')
  4011. }
  4012. }
  4013. }
  4014. )
  4015. }
  4016. }
  4017. .width('100%')
  4018. .height('100%')
  4019. }
  4020. //提取视频中的音频
  4021. @Builder
  4022. extractAudioFromVideoBuilder(item:VideoItem) {
  4023. Scroll() {
  4024. Column() {
  4025. ExtractAudioFromVideo(
  4026. {
  4027. mVideoItem:item,
  4028. currentPath:this.currentPath,
  4029. videoUrl:this.videoUrl,
  4030. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4031. currentTime:this.currentTime,
  4032. progressValue:this.progressValue,
  4033. onBack:()=>{
  4034. this.isExtractAudio = !this.isExtractAudio
  4035. this.longItemFilePath = ''
  4036. },
  4037. onPlayOrPause:()=>{
  4038. if(this.videoUrl==item.filePath){
  4039. this.playOrPause()
  4040. }else{//如果不是当前播放的,则播放该文件
  4041. this.videoUrl==item.filePath
  4042. this.doPlay(item,0,false,true)
  4043. }
  4044. },
  4045. onSeeOutputPath:(outPutPath:string)=>{
  4046. this.isExtractAudio = !this.isExtractAudio
  4047. this.longItemFilePath = ''
  4048. this.modeType = 0
  4049. this.isShowFileName = true
  4050. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4051. },
  4052. onSliderChange:(value:number)=>{
  4053. if(this.videoUrl!=item.filePath){
  4054. this.videoUrl==item.filePath
  4055. return
  4056. }
  4057. this.isSeekTo = true;
  4058. this.mDestroyPage = false;
  4059. this.showLoadIng();
  4060. let seekValue = value * (this.getActiveDuration() / 100);
  4061. this.seekTo(seekValue + "");
  4062. this.isSeekTo = false;
  4063. },
  4064. onResult:(result: boolean,outPath:string)=>{
  4065. if(result){//如果成功,更新数据
  4066. this.doUpdateData()
  4067. }else{
  4068. ToastUtil.showToast('提取音频失败')
  4069. }
  4070. }
  4071. }
  4072. )
  4073. }
  4074. }
  4075. .width('100%')
  4076. .height('100%')
  4077. }
  4078. //合并音频
  4079. @Builder
  4080. MergeAudioBuilder() {
  4081. Scroll() {
  4082. Column() {
  4083. MergeAudio(
  4084. {
  4085. videoUrl:this.videoUrl,
  4086. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  4087. currentPath:this.currentPath,
  4088. selectedFiles:this.selectedFiles,
  4089. currentTime:this.currentTime,
  4090. progressValue:this.progressValue,
  4091. onBack:()=>{
  4092. this.isMergeAudio = !this.isMergeAudio
  4093. this.longItemFilePath = ''
  4094. },
  4095. // onPlayPath:(path:string)=>{
  4096. // if(this.videoUrl==item.filePath){
  4097. // this.playOrPause()
  4098. // }else{//如果不是当前播放的,则播放该文件
  4099. // this.videoUrl==item.filePath
  4100. // this.doPlay(item,0,false,true)
  4101. // }
  4102. //
  4103. // },
  4104. onSeeOutputPath:(outPutPath:string)=>{
  4105. this.isMergeAudio = !this.isMergeAudio
  4106. this.longItemFilePath = ''
  4107. this.modeType = 0
  4108. this.isShowFileName = true
  4109. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  4110. },
  4111. onResult:(result: boolean,outPath:string)=>{
  4112. if(result){//如果成功,更新数据
  4113. this.doUpdateData()
  4114. }else{
  4115. if(this.selectedFiles.length>=3){
  4116. ToastUtil.showToast('合并数量太多导致失败')
  4117. }else{
  4118. ToastUtil.showToast('合并失败')
  4119. }
  4120. }
  4121. }
  4122. }
  4123. )
  4124. }
  4125. }
  4126. .width('100%')
  4127. .height('100%')
  4128. }
  4129. asyncCurrentPathData() {
  4130. if (this.modeType == 0) {
  4131. workerInstance.postMessage({
  4132. code: 1,
  4133. data1: this.context,
  4134. data2: this.currentPath,
  4135. data3: this.lockPath,
  4136. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  4137. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  4138. });
  4139. }
  4140. }
  4141. // 处理文件选择的函数
  4142. handleFileSelection(item: VideoItem, checked: boolean) {
  4143. if (checked) {
  4144. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  4145. this.selectedFiles.push(item);
  4146. }
  4147. } else {
  4148. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  4149. if (index > -1) {
  4150. this.selectedFiles.splice(index, 1);
  4151. }
  4152. }
  4153. }
  4154. private deleteComponentId: number = 0
  4155. //多选删除文件
  4156. showWarnIsDelete(){
  4157. this.getUIContext().getPromptAction().openCustomDialog({
  4158. builder: () => {
  4159. this.deleteComptentBuilder()
  4160. },
  4161. isModal:true,
  4162. showInSubWindow:false,
  4163. maskColor: Color.Transparent,
  4164. dialogTransition: // 设置弹窗内容显示的过渡效果
  4165. TransitionEffect.translate({ x: 0, y: 290, z: 0 })
  4166. .animation({ duration: 600, curve: Curve.Smooth }),
  4167. maskTransition: // 设置蒙层显示的过渡效果
  4168. TransitionEffect.opacity(0)
  4169. .animation({ duration: 600, curve: Curve.Smooth })
  4170. }).then((dialogId: number) => {
  4171. this.deleteComponentId = dialogId
  4172. })
  4173. .catch((error: BusinessError) => {
  4174. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  4175. })
  4176. }
  4177. @Builder
  4178. deleteComptentBuilder(){
  4179. DeleteComptent({
  4180. selectedFiles:this.selectedFiles,
  4181. onCancel:()=>{
  4182. this.isMultiSelect = false
  4183. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  4184. },
  4185. onDeleteResult:(result: boolean)=>{
  4186. this.isMultiSelect = false
  4187. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  4188. if(result){//如果删除成功,更新数据
  4189. this.selectedFiles = [];
  4190. this.isAllSelected = false
  4191. this.cache.delete(this.currentPath);
  4192. this.getSortedFiles(this.currentPath, true);
  4193. }
  4194. }
  4195. })
  4196. }
  4197. //多选移动文件
  4198. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  4199. Logger.info('onecold showCutDialogForMultipleFiles')
  4200. let mList: Array<string> = []
  4201. let rPath = this.rootPath
  4202. if (isCurrent) {
  4203. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  4204. rPath = this.currentPath
  4205. } else {
  4206. mList = Utility.getNameList(this.dirList);
  4207. rPath = this.rootPath
  4208. }
  4209. let dataBean = new BubbleBean();
  4210. dataBean.data = mList;
  4211. dataBean.color = this.themeColor
  4212. dataBean.onItemClick = (i) => {
  4213. const newDirPath = rPath + '/' + mList[i];
  4214. // Logger.info('newDirPath = ' + newDirPath)
  4215. this.selectedFiles.forEach((item) => {
  4216. const newPath = newDirPath + '/' + item.fileName;
  4217. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  4218. ToastUtil.showToast('移动成功');
  4219. this.table.deleteData(item, () => {
  4220. this.cache.delete(this.currentPath); // 删除原路径缓存
  4221. this.cache.delete(newDirPath); // 删除目标路径缓存
  4222. this.getSortedFiles(this.currentPath, true);
  4223. });
  4224. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  4225. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  4226. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  4227. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  4228. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  4229. this.table.insert(newItem, (id: number) => {
  4230. //加入数据库
  4231. });
  4232. }
  4233. }).catch((error: Error) => {
  4234. console.error(error.message);
  4235. });
  4236. });
  4237. this.isMultiSelect = false
  4238. this.selectedFiles = [];
  4239. this.isAllSelected = false
  4240. XPopup.dismissTop();
  4241. };
  4242. let pup: XPopup
  4243. if (this.isDarkMode) {
  4244. pup = XPopup.Builder()
  4245. .setPopupPosition(PopupPosition.TOP)
  4246. .atView(viewId)
  4247. .setBackgroundColor(Color.Black)
  4248. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4249. .show();
  4250. } else {
  4251. pup = XPopup.Builder()
  4252. .setPopupPosition(PopupPosition.TOP)
  4253. .atView(viewId)
  4254. .setBackgroundColor(Color.White)
  4255. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4256. .show();
  4257. }
  4258. }
  4259. /**
  4260. * 加载所有歌单
  4261. */
  4262. async loadAllPlaylists() {
  4263. try {
  4264. this.allPlaylists = await this.playlistTable?.queryAllPlaylists()!
  4265. LogUtil.info('heanup Loaded playlists: ' + this.allPlaylists.length)
  4266. } catch (error) {
  4267. LogUtil.error('heaunp Failed to load playlists: ' + error.message)
  4268. }
  4269. }
  4270. /**
  4271. * 显示添加到歌单对话框
  4272. */
  4273. async openAddToPlaylistDialog(items: VideoItem | VideoItem[]) {
  4274. const songs = Array.isArray(items) ? items : [items]
  4275. const musicItems = songs.filter(song => song.type !== CommonConstants.TYPE_IS_DIR)
  4276. if (musicItems.length === 0) {
  4277. ToastUtil.showToast('请选择要添加的歌曲')
  4278. return
  4279. }
  4280. // 加载最新的歌单列表
  4281. await this.loadAllPlaylists()
  4282. showAddToPlaylistDialog(
  4283. musicItems,
  4284. this.allPlaylists,
  4285. async (playlistId: string) => {
  4286. // 添加歌曲到歌单
  4287. const success = await this.playlistTable?.addSongsToPlaylist(playlistId,
  4288. musicItems.map(song => song.filePath))
  4289. if (success) {
  4290. const count = musicItems.length
  4291. ToastUtil.showToast(count > 1 ? `已添加 ${count} 首歌曲` : '已添加到歌单')
  4292. // 重新加载歌单列表
  4293. await this.loadAllPlaylists()
  4294. } else {
  4295. ToastUtil.showToast(musicItems.length > 1 ? '选中的歌曲已在该歌单中' : '歌曲已在该歌单中')
  4296. }
  4297. this.longItemFilePath = ''
  4298. if (this.isMultiSelect) {
  4299. this.isMultiSelect = false
  4300. this.isAllSelected = false
  4301. this.selectedFiles = []
  4302. }
  4303. },
  4304. () => {
  4305. LogUtil.info('取消添加到歌单')
  4306. },
  4307. () => {
  4308. // 创建新歌单
  4309. showCreatePlaylistDialog(
  4310. async (name: string, description: string, coverPath?: string) => {
  4311. const success = await this.playlistTable?.createPlaylist(name, description, coverPath)
  4312. if (success) {
  4313. ToastUtil.showToast('歌单创建成功')
  4314. // 重新加载歌单列表并打开添加对话框
  4315. await this.loadAllPlaylists()
  4316. await this.openAddToPlaylistDialog(musicItems)
  4317. } else {
  4318. ToastUtil.showToast('歌单创建失败')
  4319. }
  4320. },
  4321. () => {
  4322. // 取消创建歌单
  4323. }
  4324. )
  4325. }
  4326. )
  4327. }
  4328. doFav(item: VideoItem) {
  4329. LogUtil.info('onecold doFav isFav=' + item.isFav)
  4330. let isFav = 0
  4331. if (Utility.getIsFav(this.favList, item)) {
  4332. isFav = 0
  4333. } else {
  4334. isFav = 1
  4335. }
  4336. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  4337. if (result) {
  4338. if (isFav === 1) {
  4339. ToastUtil.showToast('收藏成功');
  4340. } else {
  4341. ToastUtil.showToast('取消收藏成功');
  4342. }
  4343. this.deleteCache(this.currentPath)
  4344. this.getFavList(false)
  4345. if (this.modeType === 0 && !this.isFavMusic) {
  4346. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  4347. this.getSortedFiles(this.currentPath)
  4348. }
  4349. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  4350. workerInstance.postMessage({ code: 3, data: this.context });
  4351. workerInstance.postMessage({ code: 4, data: this.context });
  4352. }
  4353. })
  4354. }
  4355. //多选复制文件
  4356. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  4357. console.log('onecold showCopyDialogForMultipleFiles');
  4358. let mList: Array<string> = []
  4359. let rPath = this.rootPath
  4360. if (isCurrent) {
  4361. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  4362. rPath = this.currentPath
  4363. } else {
  4364. mList = Utility.getNameList(this.dirList);
  4365. rPath = this.rootPath
  4366. }
  4367. let dataBean = new BubbleBean();
  4368. dataBean.data = mList;
  4369. dataBean.isCopy = true
  4370. dataBean.color = this.themeColor
  4371. dataBean.onItemClick = (i) => {
  4372. const newDirPath = rPath + '/' + mList[i];
  4373. // Logger.info('newDirPath = ' + newDirPath)
  4374. this.selectedFiles.forEach((item) => {
  4375. const newPath = newDirPath + '/' + item.fileName;
  4376. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  4377. ToastUtil.showToast('复制成功');
  4378. this.cache.delete(newDirPath); // 删除目标路径缓存
  4379. this.getSortedFiles(this.currentPath);
  4380. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  4381. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  4382. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  4383. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  4384. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  4385. this.table.insert(newItem, (id: number) => {
  4386. //加入数据库
  4387. });
  4388. }
  4389. }).catch((error: Error) => {
  4390. console.error(error.message);
  4391. });
  4392. });
  4393. this.isMultiSelect = false
  4394. this.selectedFiles = [];
  4395. this.isAllSelected = false
  4396. XPopup.dismissTop();
  4397. };
  4398. let pup: XPopup
  4399. if (this.isDarkMode) {
  4400. pup = XPopup.Builder()
  4401. .setPopupPosition(PopupPosition.TOP)
  4402. .atView(viewId)
  4403. .setBackgroundColor(Color.Black)
  4404. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4405. .show();
  4406. } else {
  4407. pup = XPopup.Builder()
  4408. .setPopupPosition(PopupPosition.TOP)
  4409. .atView(viewId)
  4410. .setBackgroundColor(Color.White)
  4411. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4412. .show();
  4413. }
  4414. }
  4415. @Builder
  4416. private DirItem(item: VideoItem, index?: number) {
  4417. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  4418. Row() {
  4419. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
  4420. $r('app.media.music_group'))
  4421. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4422. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4423. .fillColor(this.themeColor)// .fontSize(33)
  4424. .alt($r('app.media.music_group'))
  4425. .borderRadius(this.isCoverRectangle?9:'100%')
  4426. .clip(true)
  4427. .shadow({
  4428. radius: 2,
  4429. type: ShadowType.BLUR,
  4430. color: 'on_primary'
  4431. })
  4432. .sourceSize({width:38, height:38})
  4433. .margin({ left: 20, top: 8, bottom: 8 })
  4434. Column() {
  4435. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  4436. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4437. .maxLines(1)// .width('88%')
  4438. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4439. .animation({
  4440. duration: 555,
  4441. curve: 'ease-in-out',
  4442. })
  4443. .transition({
  4444. type: TransitionType.Insert,
  4445. opacity: 0,
  4446. translate: { x: 160 }
  4447. })
  4448. .margin({ left: 10, right: 20 })
  4449. .fontColor($r('app.color.text_color'))
  4450. Row() {
  4451. Text(`${this.getArtistSongCount(item.name)}首`)
  4452. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4453. .padding({ top: 8 })
  4454. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  4455. .fontColor($r('app.color.text_color'))
  4456. .margin({ left: 10 })
  4457. Text(`${this.getAlbumSongCount(item.name)}首`)
  4458. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4459. .padding({ top: 8 })
  4460. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  4461. .fontColor($r('app.color.text_color'))
  4462. .margin({ left: 10 })
  4463. Blank()
  4464. }
  4465. }
  4466. .height('100%')
  4467. .layoutWeight(1)
  4468. .justifyContent(FlexAlign.Center)
  4469. .alignItems(HorizontalAlign.Start)
  4470. Blank()
  4471. Image($r('app.media.arrow_right'))
  4472. .height(25)
  4473. .alignSelf(ItemAlign.Center)
  4474. .id(item.filePath)
  4475. .visibility(this.isShowAlphaBet?Visibility.None:Visibility.Visible)
  4476. .animation({ duration: 300, curve: Curve.Ease })
  4477. }
  4478. }
  4479. .backgroundColor(Color.Transparent)
  4480. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  4481. .width('98%')
  4482. .reuseId('dir_item')
  4483. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  4484. .opacity(this.opacityItem) // 绑定透明度
  4485. }
  4486. isShowDir(dirName: string) {
  4487. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  4488. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  4489. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  4490. if (dirName === undefined) {
  4491. return true
  4492. }
  4493. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  4494. return this.isShowSimi
  4495. }
  4496. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  4497. return this.isShowFAV
  4498. }
  4499. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  4500. return this.isShowHistory
  4501. }
  4502. return true
  4503. }
  4504. @State opacityItem: number = 1; // 控制透明度的状态变量
  4505. @Builder
  4506. private MusicItem(item: VideoItem, index?: number) {
  4507. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  4508. Row() {
  4509. Stack() {
  4510. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  4511. .fillColor(this.themeColor)
  4512. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4513. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4514. .alt($r('app.media.alt'))
  4515. .borderRadius(this.isCoverRectangle?9:'100%')
  4516. .clip(true)
  4517. .draggable(false)
  4518. .sourceSize({width:38, height:38})
  4519. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4520. // .autoResize(true) // 重采样,可减少内存占用
  4521. .opacity(this.opacityItem)// 绑定透明度
  4522. .margin({ left: 20 })
  4523. .shadow({
  4524. radius: StrUtil.isEmpty(item.pixelMapPath) ?6:14,
  4525. type: ShadowType.BLUR,
  4526. color: 'on_primary'
  4527. })
  4528. .onClick(()=>{
  4529. if (this.isMultiSelect) {
  4530. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  4531. this.handleFileSelection(item, !isChecked);
  4532. } else {
  4533. this.doPlay(item,index)
  4534. this.setShowPlayTrue()
  4535. }
  4536. })
  4537. }
  4538. Column() {
  4539. Column() {
  4540. Text(this.isShowFileName?item.fileName :item.name)
  4541. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4542. .maxLines(1)
  4543. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4544. .animation({
  4545. duration: 555,
  4546. curve: 'Linear',
  4547. })
  4548. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4549. $r('app.color.text_color'))
  4550. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4551. .padding({right:25})
  4552. .bindPopup(this.longItemFilePath === item.filePath, {
  4553. builder: this.MenuBuilder(item,index,item.filePath),
  4554. placement: Placement.Top,
  4555. // autoCancel: true,
  4556. mask: {color:'#33000000'},
  4557. // popupColor: Color.Yellow,
  4558. enableArrow: false,//是否显示箭头
  4559. showInSubWindow: false,
  4560. onStateChange: (e) => {
  4561. if (!e.isVisible) {
  4562. this.longItemFilePath = ''
  4563. this.tempLyricContent = ''
  4564. }
  4565. }
  4566. })
  4567. Row() {
  4568. Column(){
  4569. Text(item.md5Str?.includes('Lossless')?
  4570. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  4571. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  4572. .padding({ top: 3,right:6,left:6,bottom:3 })
  4573. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4574. $r('app.color.text_color'))
  4575. .fontWeight(500)
  4576. .borderRadius(12)
  4577. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  4578. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4579. .backgroundColor('#FFC107')
  4580. }
  4581. .padding({ top: 8 })
  4582. Text(StrUtil.isEmpty(item.artist) ? item.duration
  4583. :this.twoFingerType==2? item.artist +' ' + item.duration
  4584. : item.artist + ' ' + item?.duration)
  4585. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4586. .padding({ top: 8 ,right:25})
  4587. .visibility(this.isShowFileName?Visibility.None:Visibility.Visible)
  4588. .maxLines(1)
  4589. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4590. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4591. Color.Gray)
  4592. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4593. Blank()
  4594. Text(this.isShowFileName?item.duration:item.size)
  4595. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4596. .padding({ top: 8 })
  4597. .maxLines(1)
  4598. .visibility(this.isShowFileName?Visibility.Visible:StrUtil.isEmpty(item.artist)
  4599. ? Visibility.Visible : Visibility.None)
  4600. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4601. Color.Gray)
  4602. .margin({ left: StrUtil.isEmpty(item.artist) ?0:10 })
  4603. }
  4604. }
  4605. .height('100%')
  4606. .width('100%')
  4607. .margin({ right: 10 })
  4608. .justifyContent(FlexAlign.Center)
  4609. .alignItems(HorizontalAlign.Start)
  4610. }
  4611. .height('100%')
  4612. .margin({ left: 5 })
  4613. .layoutWeight(1)
  4614. Column() {
  4615. Checkbox({ name: 'checkbox' + index })
  4616. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  4617. .selectedColor(this.themeColor)
  4618. .shape(CheckBoxShape.CIRCLE)
  4619. .opacity(this.isMultiSelect ? 1 : 0)
  4620. .animation({
  4621. duration: 666,
  4622. curve: 'Smooth' // 可选动画曲线
  4623. })
  4624. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  4625. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  4626. .margin({ left: 20, top: 8, bottom: 8,right:18 })
  4627. .width(22)
  4628. .height(22)
  4629. ImageAnimator()
  4630. .images(this.imagesF)// 动画数组
  4631. .duration(1000)// 持续
  4632. .state(this.animationState)// 动画状态
  4633. .fillMode(FillMode.Forwards)
  4634. .width(18)
  4635. .margin({ right: 20, top: 8, bottom: 8 })
  4636. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  4637. Visibility.None)
  4638. .height(18)
  4639. .iterations(-1) // 播放次数
  4640. }
  4641. }
  4642. }
  4643. .gesture(LongPressGesture()
  4644. .onAction(async () => {
  4645. //如果是专辑和艺术家的首页,不能长按
  4646. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4647. return
  4648. //如果是我的收藏 最近播放等也不能长按
  4649. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4650. item.name === LocalMusic.STR_HISTORY_MUSIC
  4651. )
  4652. return
  4653. this.longItemFilePath = item.filePath
  4654. this.tempLyricContent = await this.getLyricContent(item)
  4655. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  4656. })
  4657. .onActionEnd((event: GestureEvent) => {
  4658. }))
  4659. .backgroundColor(Color.Transparent)
  4660. .width('100%')
  4661. .reuseId('file_item')
  4662. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  4663. }
  4664. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  4665. @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
  4666. buttons: [{ text: '文件夹' }, { text: '媒体库' },{ text: '艺术家' }, { text: '专辑' }],
  4667. direction: Direction.Ltr,
  4668. buttonPadding:{top:12,bottom:12},
  4669. backgroundColor: Color.Transparent,
  4670. fontSize:14,
  4671. selectedFontSize:15,
  4672. selectedFontColor:Color.White,
  4673. selectedBackgroundColor: this.themeColor,
  4674. localizedTextPadding: {
  4675. end: LengthMetrics.vp(20),
  4676. start: LengthMetrics.vp(20)
  4677. }
  4678. })
  4679. @State @Watch('capsuleSelectedIndexesChanged')tabSelectedIndexes: number[] = [0]
  4680. //当胶囊按钮的选择发生变化时调用此函数
  4681. capsuleSelectedIndexesChanged() {
  4682. this.modeType = this.tabSelectedIndexes[0]
  4683. }
  4684. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  4685. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  4686. isShowCoverHeader() {
  4687. if (!this.isShowHeader) {
  4688. return false
  4689. }
  4690. if (this.modeType == 0) {
  4691. if (this.isHistory || this.isFavMusic) {
  4692. return true
  4693. }
  4694. if (this.currentPath != this.rootPath) {
  4695. return true
  4696. }
  4697. }
  4698. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  4699. }
  4700. getCoverTitleBg(): ResourceStr | image.PixelMap {
  4701. if (this.isCustomizeBg) {
  4702. return ('rgba(255,255,255,0.2)')
  4703. }
  4704. if (this.isDarkMode) {
  4705. return $r('app.color.user_center_card_background')
  4706. }
  4707. return this.currentTitleCover
  4708. }
  4709. // 第二步:popup构造器定义弹框内容
  4710. @Builder popupBuilder() {
  4711. Column({ space: 2 }) {
  4712. Text('友情提示:双指缩放可以放大缩小列表')
  4713. .fontSize(12)
  4714. .fontWeight(FontWeight.Regular)
  4715. .fontColor($r('app.color.text_color'))
  4716. }
  4717. .justifyContent(FlexAlign.SpaceAround)
  4718. .width(220)
  4719. .height(55)
  4720. .padding(15)
  4721. }
  4722. //搜索功能的实现
  4723. @State searchText: string = ''; // 用户输入内容
  4724. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  4725. @State isSearchMode: boolean = false
  4726. // 实时搜索逻辑(带防抖)
  4727. private async onSearchInput(value: string): Promise<void> {
  4728. this.searchText = value.trim();
  4729. Logger.info('heanup LocalMusic', `onSearchInput: keyword="${this.searchText}", mode=${this.modeType}`);
  4730. // 新增条件判断:空输入时退出搜索模式
  4731. if (this.searchText === '') {
  4732. this.isSearchMode = false;
  4733. // 重新加载第一页(不带搜索条件)
  4734. await this.resetAndLoadFirstPage();
  4735. return;
  4736. }
  4737. // 进入搜索模式
  4738. if (!this.isSearchMode) {
  4739. this.isSearchMode = true;
  4740. }
  4741. // 使用数据库分页查询(带搜索条件)
  4742. await this.resetAndLoadFirstPage();
  4743. }
  4744. @State dragItem: number = -1
  4745. @State scaleItem: number = -1
  4746. @State neighborItem: number = -1
  4747. @State neighborScale: number = -1
  4748. @State offsetY: number = 0
  4749. private dragRefOffset: number = 0
  4750. private ITEM_INTV: number = 78
  4751. scaleSelect(item: number): number {
  4752. if (this.scaleItem === item) {
  4753. return 1.05
  4754. } else if (this.neighborItem === item) {
  4755. return this.neighborScale
  4756. } else {
  4757. return 1
  4758. }
  4759. }
  4760. itemMove(index: number, newIndex: number): void {
  4761. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  4762. return;
  4763. }
  4764. let tmp = this.videoLocalList.splice(index, 1);
  4765. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  4766. this.dataSource.pushArrayData(this.videoLocalList)
  4767. if(this.modeType==4&&this.playlistTable){
  4768. updateAllSongsSortOrder(this.playlistTable, this.videoLocalList,this.currentSongListID)
  4769. }
  4770. }
  4771. //瀑布流布局 支持双指缩放
  4772. @State columns: number = 2;
  4773. @State waterFlowScale: number = 1;
  4774. @State imageScale: number = 1;
  4775. @State waterFlowOpacity: number = 1;
  4776. @State waterFlowSnapshot: image.PixelMap | undefined = undefined;
  4777. private columnChanged: boolean = false;
  4778. private oldColumn: number = this.columns;
  4779. private pinchTime: number = 0;
  4780. // 根据缩放阈值改变列数,触发WaterFlow重新布局
  4781. changeColumns(scale: number): void {
  4782. if (scale > (this.columns / (this.columns - 0.5)) && this.columns > 1) {
  4783. this.columns--;
  4784. this.columnChanged = true;
  4785. } else if (scale < 1 && this.columns < 4) {
  4786. this.columns++;
  4787. this.columnChanged = true;
  4788. }
  4789. }
  4790. @Builder
  4791. getWaterView(){
  4792. Scroll(this.scroller) {
  4793. Column() {
  4794. Blank().height(this.topSafeHeight + 55)
  4795. WaterFlow({
  4796. scroller:this.waterScroller,
  4797. layoutMode: WaterFlowLayoutMode.SLIDING_WINDOW
  4798. }) {
  4799. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  4800. FlowItem() {
  4801. this.MusicWaterCardItem(item,index)
  4802. }
  4803. .width('100%')
  4804. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  4805. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  4806. {
  4807. preview: MenuPreviewMode.IMAGE,
  4808. previewAnimationOptions: { scale: [0.8, 1.0] },
  4809. })
  4810. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  4811. {
  4812. preview: MenuPreviewMode.IMAGE,
  4813. previewAnimationOptions: { scale: [0.8, 1.0] },
  4814. })
  4815. .transition(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }))
  4816. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  4817. TransitionEffect.scale({ x: 0, y: 0 })))
  4818. .gesture(
  4819. GestureGroup(GestureMode.Exclusive,
  4820. SwipeGesture({ direction: SwipeDirection.Horizontal })
  4821. .onAction((event: GestureEvent) => {
  4822. if (event) {
  4823. // this.sideBarController.openSideBar()
  4824. }
  4825. }),
  4826. TapGesture({ count: 1, fingers: 1 })
  4827. .onAction(async () => {
  4828. })
  4829. )
  4830. )
  4831. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  4832. }
  4833. // .columnsTemplate('repeat(auto-fit, 160)')
  4834. .id('waterflow') // 设置id用于截图
  4835. .columnsTemplate('1fr '.repeat(this.columns)) // 动态生成列模板,如:'1fr 1fr 1fr'表示3列等宽
  4836. .columnsGap(12) // 列间距
  4837. .rowsGap(16) // 行间距
  4838. .cachedCount(6)
  4839. .padding({bottom:this.bottomBarHeight+10})
  4840. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  4841. .animation({ duration: 500, curve: Curve.Ease }))
  4842. .scrollBar(BarState.Off)
  4843. // .fadingEdge(true, { fadingEdgeLength: LengthMetrics.vp(38) })
  4844. // 效果:只有向上或者向下滑动到顶部时才会有弹簧回弹效果
  4845. .edgeEffect(EdgeEffect.Spring, { alwaysEnabled: true })
  4846. .width('90%')
  4847. .height('100%')
  4848. .opacity(this.waterFlowOpacity)
  4849. .scale({
  4850. x: this.waterFlowScale,
  4851. y: this.waterFlowScale,
  4852. centerX: 0,
  4853. centerY: 0
  4854. })
  4855. .onReachEnd(() => {
  4856. if(this.modeType === 4 )
  4857. return;
  4858. // 触底加载下一页
  4859. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  4860. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  4861. return;
  4862. }
  4863. if (this.hasMoreData && !this.isLoadingPage) {
  4864. this.loadNextPage();
  4865. }
  4866. })
  4867. .onAppear(() => {
  4868. this.scroller.scrollEdge(Edge.Top)
  4869. })
  4870. .nestedScroll({
  4871. scrollForward: NestedScrollMode.PARENT_FIRST,
  4872. scrollBackward: NestedScrollMode.SELF_FIRST
  4873. })
  4874. .priorityGesture(
  4875. PinchGesture()
  4876. .onActionStart((event: GestureEvent) => {
  4877. // 双指捏合手势识别成功时截图
  4878. this.pinchTime = event.timestamp;
  4879. this.columnChanged = false;
  4880. this.oldColumn = this.columns;
  4881. this.getUIContext().getComponentSnapshot().get('waterflow', (error: Error, pixmap: image.PixelMap) => {
  4882. if (error) {
  4883. console.info('error:' + JSON.stringify(error));
  4884. return;
  4885. }
  4886. this.waterFlowSnapshot = pixmap;
  4887. if ((this.oldColumn === 1 ) && event.scale > 1|| (this.oldColumn === 4 && event.scale < 1)) {
  4888. console.info("onecold onActionStart oldColumn:" + this.oldColumn)
  4889. if (this.oldColumn ===4) {
  4890. this.twoFingerType =3
  4891. this.isGridMusic = true
  4892. }else if (this.oldColumn ===1) {
  4893. this.twoFingerType =1
  4894. this.isGridMusic = false
  4895. }
  4896. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  4897. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4898. return;
  4899. }
  4900. })
  4901. })
  4902. .onActionUpdate((event: GestureEvent) => {
  4903. // 手势更新:处理缩放逻辑和视觉效果
  4904. // 边界限制:防止超出列数范围时继续缩放
  4905. if ((this.oldColumn === 1 && event.scale > 1) || (this.oldColumn === 4 && event.scale < 1)) {
  4906. return;
  4907. }
  4908. // 节流处理:避免过于频繁的更新,提升性能
  4909. if (event.timestamp - this.pinchTime < 10000000) {
  4910. return;
  4911. }
  4912. this.pinchTime = event.timestamp;
  4913. this.waterFlowScale = event.scale;
  4914. this.imageScale = event.scale;
  4915. // 根据缩放比例设置WaterFlow透明度
  4916. this.waterFlowOpacity = (this.waterFlowScale > 1) ? (this.waterFlowScale - 1) : (1 - this.waterFlowScale);
  4917. this.waterFlowOpacity *= 3;
  4918. if (!this.columnChanged) {
  4919. this.changeColumns(event.scale);
  4920. }
  4921. // 列数改变后的缩放比例调整:避免出现空白区域
  4922. if (this.columnChanged) {
  4923. this.waterFlowScale = this.imageScale * this.columns / this.oldColumn;
  4924. // 限制缩放范围,确保视觉效果自然
  4925. if (event.scale < 1) {
  4926. this.waterFlowScale = this.waterFlowScale > 1 ? this.waterFlowScale : 1;
  4927. } else {
  4928. this.waterFlowScale = this.waterFlowScale < 1 ? this.waterFlowScale : 1;
  4929. }
  4930. }
  4931. })
  4932. .onActionEnd((event: GestureEvent) => {
  4933. // 手势结束:执行归位动画并保存状态
  4934. // 执行归位动画:平滑过渡到正常状态
  4935. this.getUIContext()?.animateTo({ duration: 300 }, () => {
  4936. this.waterFlowScale = 1;
  4937. this.waterFlowOpacity = 1;
  4938. })
  4939. // 持久化保存当前列数:下次启动时恢复
  4940. PreferencesUtil.putSync('lastColumns', this.columns);
  4941. })
  4942. )
  4943. .onScrollFrameBegin((offset: number) => {
  4944. // 获取当前滚动偏移量
  4945. if(this.autoHideTitle){
  4946. const currentOffsetY = this.waterScroller.currentOffset().yOffset;
  4947. // 判断滚动方向
  4948. if (currentOffsetY > this.prevOffsetY) {
  4949. // console.log("onecold 向上滚动");
  4950. this.isShowTitleBar = false
  4951. } else if (currentOffsetY < this.prevOffsetY) {
  4952. // console.log("onecold 向下滚动");
  4953. this.isShowTitleBar = true
  4954. }
  4955. // 更新前一次偏移量
  4956. this.prevOffsetY = currentOffsetY;
  4957. }
  4958. return { offsetRemain: offset };
  4959. })
  4960. }
  4961. }
  4962. .scrollBar(BarState.Off)
  4963. }
  4964. //瀑布流卡片布局
  4965. @Builder
  4966. private MusicWaterCardItem(item: VideoItem, index: number) {
  4967. Button({ type: ButtonType.Normal, stateEffect: false }) {
  4968. Stack() {
  4969. Column() {
  4970. Image(item.pixelMapPath)
  4971. .backgroundImageSize(ImageSize.Auto)
  4972. .borderRadius({
  4973. topLeft: 12,
  4974. topRight : 12,
  4975. bottomLeft: 0,
  4976. bottomRight: 0
  4977. })
  4978. .draggable(false)// 禁止长按手势拖动
  4979. .autoResize(true) // 重采样,可减少内存占用
  4980. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4981. .width('100%')
  4982. .height('auto')
  4983. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  4984. .objectFit(ImageFit.Auto)
  4985. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  4986. height: '99%' ,
  4987. dragBar: true,
  4988. onDisappear: () => {
  4989. this.longItemFilePath = '';
  4990. this.tempLyricContent = ''
  4991. },
  4992. showClose: true,
  4993. preferType: SheetType.CENTER ,
  4994. title: { title: '编辑标签' }
  4995. })
  4996. .draggable(false)
  4997. .opacity(this.opacityItem)// 绑定透明度
  4998. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  4999. // .animation({ duration: 500, curve: Curve.Ease }))
  5000. .animation({
  5001. duration: 666,
  5002. curve: 'ease-in-out' // 可选动画曲线
  5003. })
  5004. .margin({
  5005. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5006. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5007. })
  5008. Column() {
  5009. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  5010. .fontSize(this.columns == 4 ||this.columns==3? 12 : this.columns == 2 ? 15 : 18)
  5011. .maxLines(1)
  5012. .fontWeight(FontWeight.Bold)
  5013. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5014. .animation({
  5015. duration: 555,
  5016. curve: 'Linear',
  5017. })
  5018. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  5019. height: '95%',
  5020. dragBar: true,
  5021. showClose: true,
  5022. onDisappear: () => {
  5023. this.longItemFilePathDetail = '';
  5024. },
  5025. blurStyle:BlurStyle.Thin,
  5026. backgroundColor:Color.Transparent,
  5027. preferType: SheetType.CENTER ,
  5028. title: { title: '详情' }
  5029. })
  5030. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5031. $r('app.color.text_color'))
  5032. Column() {
  5033. Text(`${this.getArtistSongCount(item.name)}首`)
  5034. .fontSize(11)
  5035. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  5036. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5037. .fontColor($r('app.color.text_color'))
  5038. Text(`${this.getAlbumSongCount(item.name)}首`)
  5039. .fontSize(11)
  5040. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  5041. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5042. .fontColor($r('app.color.text_color'))
  5043. Row(){
  5044. Column(){
  5045. Text(item.md5Str?.includes('Lossless')?
  5046. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5047. .fontSize(this.columns == 4 ||this.columns==3? 8 : this.columns == 2 ? 9 : 11)
  5048. .padding({ top: 3,right:6,left:6,bottom:3 })
  5049. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5050. $r('app.color.text_color'))
  5051. .fontWeight(500)
  5052. .borderRadius(12)
  5053. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5054. .backgroundColor('#FFC107')
  5055. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  5056. }
  5057. .margin({ top: 2 ,right:6})
  5058. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  5059. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  5060. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  5061. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 13)
  5062. .maxLines(1)
  5063. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5064. .margin({ top: 2})
  5065. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  5066. || item.type == CommonConstants.TYPE_IS_ALBUM
  5067. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5068. .fontWeight(FontWeight.Medium)
  5069. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5070. $r('app.color.text_color'))
  5071. }
  5072. }
  5073. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  5074. }
  5075. .height(this.columns == 4 ||this.columns==3? item.type==CommonConstants.TYPE_IS_DIR?30:40
  5076. : this.columns == 2 ? (item.type==CommonConstants.TYPE_IS_DIR?38:48) :
  5077. (item.type==CommonConstants.TYPE_IS_DIR?48:58))
  5078. .width('100%')
  5079. .justifyContent(FlexAlign.Center)
  5080. .margin({
  5081. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5082. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5083. })
  5084. }
  5085. .width('100%')
  5086. .borderRadius(12)
  5087. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  5088. .backgroundImageSize({ height: '100%', width: '100%' })
  5089. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  5090. .animation({ curve: Curve.Sharp, duration: 300 })
  5091. Checkbox({ name: 'checkbox' + index })
  5092. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  5093. .selectedColor(this.themeColor)
  5094. .shape(CheckBoxShape.CIRCLE)
  5095. .opacity(this.isMultiSelect ? 1 : 0)
  5096. .animation({
  5097. duration: 666,
  5098. curve: 'Smooth' // 可选动画曲线
  5099. })
  5100. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  5101. Visibility.None)
  5102. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5103. .margin({ left: 20, top: 8, bottom: 8 })
  5104. .width(38)
  5105. .height(38)
  5106. }
  5107. }
  5108. .backgroundColor(Color.Transparent)
  5109. .width('100%')
  5110. .height('auto')
  5111. .padding({top:2})
  5112. .shadow({
  5113. radius: 10,
  5114. type: ShadowType.BLUR,
  5115. color: 'on_primary'
  5116. })
  5117. .reuseId('card_item')
  5118. .onClick(() => {
  5119. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5120. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5121. this.handleFileSelection(item, !isChecked);
  5122. } else {
  5123. this.doPlay(item, index)
  5124. }
  5125. })
  5126. }
  5127. // Grid布局的开始
  5128. private dragRefOffSetX: number = 0;
  5129. private dragRefOffSetY: number = 0;
  5130. private FIX_VP_X: number = 180;
  5131. private FIX_VP_Y: number = 84;
  5132. isDraggable(index: number): boolean {
  5133. return index >= 0;
  5134. }
  5135. getRowEnd(item: number) {
  5136. if (item.toString() === '0') {
  5137. return 1;
  5138. } else {
  5139. return 0;
  5140. }
  5141. }
  5142. isInLeft(index: number) {
  5143. return index % 2 == 0;
  5144. }
  5145. down(index: number): void {
  5146. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  5147. return;
  5148. }
  5149. this.offsetY -= this.FIX_VP_Y;
  5150. this.dragRefOffSetY += this.FIX_VP_Y;
  5151. this.itemMove(index, index + 1);
  5152. }
  5153. up(index: number): void {
  5154. if (!this.isDraggable(index - 2)) {
  5155. return;
  5156. }
  5157. this.offsetY += this.FIX_VP_Y;
  5158. this.dragRefOffSetY -= this.FIX_VP_Y;
  5159. this.itemMove(index, index - 1);
  5160. }
  5161. left(index: number): void {
  5162. if (this.isInLeft(index)) {
  5163. return;
  5164. }
  5165. if (!this.isDraggable(index - 1)) {
  5166. return;
  5167. }
  5168. this.offsetX += this.FIX_VP_X;
  5169. this.dragRefOffSetX -= this.FIX_VP_X;
  5170. this.itemMove(index, index - 1)
  5171. }
  5172. right(index: number): void {
  5173. if (!this.isInLeft(index)) {
  5174. return;
  5175. }
  5176. if (!this.isDraggable(index + 1)) {
  5177. return;
  5178. }
  5179. this.offsetX -= this.FIX_VP_X;
  5180. this.dragRefOffSetX += this.FIX_VP_X;
  5181. this.itemMove(index, index + 1)
  5182. }
  5183. private scroller: Scroller = new Scroller();
  5184. private waterScroller: Scroller = new Scroller();
  5185. @State startIndex: number = 0
  5186. @State endIndex: number = 0
  5187. @State scaleValue: number = 1
  5188. @State pinchValue: number = 1
  5189. layoutOptionsForHeader: GridLayoutOptions = {
  5190. regularSize: [1, 1], // 只支持[1, 1]
  5191. irregularIndexes: [0], // 索引为0的GridItem占用一行
  5192. };
  5193. @Builder
  5194. getGridView() {
  5195. Grid(this.scroller, this.layoutOptionsForHeader) {
  5196. GridItem() {
  5197. Column(){
  5198. Blank().height(this.topSafeHeight + 45)
  5199. }
  5200. }
  5201. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5202. GridItem() {
  5203. Stack({ alignContent: Alignment.Center }) {
  5204. this.MusicItemGrid(item, index)
  5205. }
  5206. }
  5207. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  5208. {
  5209. preview: MenuPreviewMode.IMAGE,
  5210. previewAnimationOptions: { scale: [0.8, 1.0] },
  5211. })
  5212. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  5213. {
  5214. preview: MenuPreviewMode.IMAGE,
  5215. previewAnimationOptions: { scale: [0.8, 1.0] },
  5216. })
  5217. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  5218. TransitionEffect.scale({ x: 0, y: 0 })))
  5219. .clickEffect({ level: ClickEffectLevel.LIGHT })
  5220. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  5221. .zIndex(this.dragItem === index ? 1 : 0)
  5222. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  5223. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5224. }
  5225. .width('94%')
  5226. .height('100%')
  5227. .editMode(true)
  5228. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  5229. .animation({ duration: 500, curve: Curve.Ease }))
  5230. .padding({bottom:this.bottomBarHeight+this.bottomSafeHeight+10})
  5231. .reuseId('grid_item')
  5232. .layoutWeight(1)
  5233. .scrollBar(BarState.Off)
  5234. .supportAnimation(true)
  5235. .onReachEnd(() => {
  5236. if(this.modeType === 4 )
  5237. return;
  5238. // 触底加载下一页
  5239. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  5240. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  5241. return;
  5242. }
  5243. if (this.hasMoreData && !this.isLoadingPage) {
  5244. this.loadNextPage();
  5245. }
  5246. })
  5247. .cachedCount(this.twoFingerType==1?5:this.twoFingerType==2?4:3)
  5248. .columnsTemplate(
  5249. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  5250. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  5251. )
  5252. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  5253. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  5254. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  5255. .gesture(PinchGesture({ fingers: 2 })
  5256. .onActionEnd((event: GestureEvent) => {
  5257. this.setGridTwoFingers()
  5258. })
  5259. .onActionUpdate(e => {
  5260. this.scaleValue = this.pinchValue * e.scale
  5261. })
  5262. .onActionStart(e => {
  5263. }))
  5264. .enableScrollInteraction(true)
  5265. .onScrollIndex((start: number, end: number) => {
  5266. this.startIndex = start
  5267. this.endIndex = end
  5268. })
  5269. .onScrollFrameBegin((offset: number) => {
  5270. if(this.autoHideTitle){
  5271. const currentOffsetY = this.scroller.currentOffset().yOffset;
  5272. // 判断滚动方向
  5273. if (currentOffsetY > this.prevOffsetY) {
  5274. // console.log("onecold 向上滚动");
  5275. this.isShowTitleBar = false
  5276. } else if (currentOffsetY < this.prevOffsetY) {
  5277. // console.log("onecold 向下滚动");
  5278. this.isShowTitleBar = true
  5279. }
  5280. // 更新前一次偏移量
  5281. this.prevOffsetY = currentOffsetY;
  5282. }
  5283. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  5284. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  5285. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  5286. if (this.isScrollHide) {
  5287. this.setBarHeightHide2(offset)
  5288. } else {
  5289. this.setBarHeightNormal()
  5290. }
  5291. } else {
  5292. this.setBarHeightHide(offset)
  5293. }
  5294. return { offsetRemain: offset };
  5295. })
  5296. }
  5297. @State targetFile: string = '';
  5298. setGridTwoFingers() {
  5299. this.pinchValue = this.scaleValue;
  5300. Logger.info('this.pinchValue = ' + this.pinchValue);
  5301. if (this.pinchValue >= 1) {
  5302. this.twoFingerType++
  5303. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  5304. if(this.twoFingerType >= 4){
  5305. this.twoFingerType = 4//切换成瀑布流
  5306. this.columns = 4
  5307. }
  5308. } else {
  5309. this.twoFingerType--
  5310. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  5311. if (this.twoFingerType < 1) {
  5312. this.twoFingerType = 3
  5313. this.isGridMusic = false
  5314. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5315. }
  5316. }
  5317. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  5318. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5319. this.pinchValue = 1;
  5320. this.scaleValue = 1;
  5321. }
  5322. @State longItemFilePath: string = ''
  5323. @State tempLyricContent: string = ''
  5324. @State editingItem: VideoItem | null = null
  5325. @Builder
  5326. private MusicItemGrid(item: VideoItem, index: number) {
  5327. Button({ type: ButtonType.Normal, stateEffect: false }) {
  5328. Stack() {
  5329. Column() {
  5330. Image(item.pixelMapPath)
  5331. .height(this.getGridHeight())
  5332. .width(this.getGridWight())
  5333. .draggable(false)
  5334. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  5335. .autoResize(true) // 重采样,可减少内存占用
  5336. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  5337. .clip(true)
  5338. .borderRadius({
  5339. topLeft: 12,
  5340. topRight: 12,
  5341. bottomLeft: 0,
  5342. bottomRight: 0
  5343. })
  5344. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  5345. height: '99%' ,
  5346. dragBar: true,
  5347. onDisappear: () => {
  5348. this.longItemFilePath = '';
  5349. this.tempLyricContent = ''
  5350. },
  5351. showClose: true,
  5352. preferType: SheetType.CENTER ,
  5353. title: { title: '编辑标签' }
  5354. })
  5355. .draggable(false)
  5356. .opacity(this.opacityItem)// 绑定透明度
  5357. .animation({
  5358. duration: 666,
  5359. curve: 'ease-in-out' // 可选动画曲线
  5360. })
  5361. .margin({
  5362. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5363. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5364. })
  5365. Column() {
  5366. Text(this.isShowFileName&&item.type!=CommonConstants.TYPE_IS_DIR?item.fileName :item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  5367. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5368. .maxLines(1)
  5369. .fontWeight(FontWeight.Bold)
  5370. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5371. .animation({
  5372. duration: 555,
  5373. curve: 'Linear',
  5374. })
  5375. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  5376. height: '100%',
  5377. dragBar: true,
  5378. showClose: true,
  5379. onDisappear: () => {
  5380. this.longItemFilePathDetail = '';
  5381. },
  5382. blurStyle:BlurStyle.Thin,
  5383. backgroundColor:Color.Transparent,
  5384. preferType: SheetType.CENTER ,
  5385. title: { title: '详情' }
  5386. })
  5387. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5388. $r('app.color.text_color'))
  5389. Column() {
  5390. Text(`${this.getArtistSongCount(item.name)}首`)
  5391. .fontSize(11)
  5392. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  5393. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5394. .fontColor($r('app.color.text_color'))
  5395. Text(`${this.getAlbumSongCount(item.name)}首`)
  5396. .fontSize(11)
  5397. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  5398. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5399. .fontColor($r('app.color.text_color'))
  5400. Row(){
  5401. Column(){
  5402. Text(item.md5Str?.includes('Lossless')?
  5403. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5404. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  5405. .padding({ top: 3,right:6,left:6,bottom:3 })
  5406. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5407. $r('app.color.text_color'))
  5408. .fontWeight(500)
  5409. .borderRadius(12)
  5410. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5411. .backgroundColor('#FFC107')
  5412. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  5413. }
  5414. .margin({ top: 2 ,right:6})
  5415. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  5416. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  5417. Text(this.isShowFileName?item.duration:StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  5418. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  5419. .maxLines(1)
  5420. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5421. .margin({ top: 2})
  5422. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  5423. || item.type == CommonConstants.TYPE_IS_ALBUM
  5424. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5425. .fontWeight(FontWeight.Medium)
  5426. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5427. $r('app.color.text_color'))
  5428. }
  5429. }
  5430. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  5431. }
  5432. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  5433. .width(this.getGridWight())
  5434. .justifyContent(FlexAlign.Center)
  5435. .margin({
  5436. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5437. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5438. })
  5439. }
  5440. .width(this.getGridWight())
  5441. .borderRadius(12)
  5442. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath)?$r('app.media.alt'):item.pixelMapPath)
  5443. .backgroundImageSize({ height: '100%', width: '100%' })
  5444. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  5445. .animation({ curve: Curve.Sharp, duration: 300 })
  5446. Checkbox({ name: 'checkbox' + index })
  5447. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  5448. .selectedColor(this.themeColor)
  5449. .shape(CheckBoxShape.CIRCLE)
  5450. .opacity(this.isMultiSelect ? 1 : 0)
  5451. .animation({
  5452. duration: 666,
  5453. curve: 'Smooth' // 可选动画曲线
  5454. })
  5455. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  5456. Visibility.None)
  5457. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5458. .margin({ left: 20, top: 8, bottom: 8 })
  5459. .width(38)
  5460. .height(38)
  5461. }
  5462. }
  5463. .backgroundColor(Color.Transparent)
  5464. .width('100%')
  5465. .padding({ top: 15 })
  5466. .height(this.getGridAllHeight())
  5467. .onClick(() => {
  5468. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5469. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5470. this.handleFileSelection(item, !isChecked);
  5471. } else {
  5472. this.doPlay(item, index)
  5473. }
  5474. })
  5475. }
  5476. getGridAllHeight() {
  5477. let heightG = 222
  5478. switch (this.twoFingerType) {
  5479. case 1:
  5480. heightG = 143
  5481. break;
  5482. case 2:
  5483. heightG = 178
  5484. break;
  5485. case 3:
  5486. heightG = 222
  5487. break;
  5488. }
  5489. return heightG
  5490. }
  5491. getGridHeight() {
  5492. let heightG = 150
  5493. switch (this.twoFingerType) {
  5494. case 1:
  5495. heightG = 80
  5496. break;
  5497. case 2:
  5498. heightG = 110
  5499. break;
  5500. case 3:
  5501. heightG = 150
  5502. break;
  5503. }
  5504. return heightG
  5505. }
  5506. getGridWight() {
  5507. let wightG = 158
  5508. switch (this.twoFingerType) {
  5509. case 1:
  5510. wightG = 80
  5511. break;
  5512. case 2:
  5513. wightG = 110
  5514. break;
  5515. case 3:
  5516. wightG = 158
  5517. break;
  5518. }
  5519. return wightG
  5520. }
  5521. @State isShowDetail:boolean = false
  5522. @State longItemFilePathDetail:string =''
  5523. @Builder
  5524. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  5525. if(
  5526. ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  5527. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5528. item.name === LocalMusic.STR_HISTORY_MUSIC)
  5529. ){
  5530. //如果是专辑和艺术家的首页,不能长按
  5531. //如果是我的收藏 最近播放等也不能长按
  5532. }else{
  5533. Scroll() {
  5534. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  5535. Menu() {
  5536. MenuItem({
  5537. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  5538. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  5539. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  5540. })
  5541. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5542. .onClick(() => {
  5543. if (item) {
  5544. this.doFav(item)
  5545. }
  5546. this.longItemFilePath = ''
  5547. })
  5548. MenuItem({
  5549. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  5550. content: '下一首播放'
  5551. })
  5552. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5553. .onClick(() => {
  5554. this.addToNextPlay(item);
  5555. this.longItemFilePath = ''
  5556. })
  5557. MenuItem({
  5558. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  5559. content: '添加到歌单'
  5560. })
  5561. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5562. .onClick(async () => {
  5563. this.longItemFilePath = ''
  5564. await this.openAddToPlaylistDialog(item)
  5565. })
  5566. MenuItem({
  5567. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  5568. content: '编辑标签'
  5569. })
  5570. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  5571. height: '99%',
  5572. dragBar: true,
  5573. showClose: true,
  5574. preferType: SheetType.CENTER ,
  5575. title: { title: '编辑标签' }
  5576. })
  5577. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5578. .onClick(async() => {
  5579. this.initEditFields(item)
  5580. this.tempLyricContent = await this.getLyricContent(item);
  5581. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  5582. this.lyricConStr = this.tempLyricContent
  5583. }
  5584. if(this.isGridMusic||this.twoFingerType==4){
  5585. this.longItemFilePath = item.filePath
  5586. }else{
  5587. this.isShowEdit = !this.isShowEdit;
  5588. }
  5589. })
  5590. MenuItem({
  5591. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  5592. content: $r('app.string.select_all')
  5593. })
  5594. .onClick(() => {
  5595. this.isMultiSelect = !this.isMultiSelect
  5596. this.longItemFilePath = ''
  5597. this.selectedFiles.push(item)
  5598. })
  5599. MenuItem({
  5600. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.cut')),
  5601. content: $r('app.string.edit_audio')
  5602. })
  5603. .bindContentCover($$this.isEditAudio, this.EditAudioBuilder(item), {
  5604. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5605. })
  5606. .onClick(() => {
  5607. this.isEditAudio = !this.isEditAudio
  5608. })
  5609. MenuItem({
  5610. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  5611. content: $r('app.string.extract_accompaniment')
  5612. })
  5613. .bindContentCover($$this.isExtractAcc, this.ExtractAccBuilder(item), {
  5614. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5615. })
  5616. .onClick(() => {
  5617. if (!Utility.isNoble()) {
  5618. this.showVipDialog()
  5619. return
  5620. }
  5621. this.isExtractAcc = !this.isExtractAcc
  5622. })
  5623. MenuItem({
  5624. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.repeat')),
  5625. content: $r('app.string.converter_audio')
  5626. })
  5627. .bindContentCover($$this.isConverter, this.ConverterBuilder(item), {
  5628. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5629. })
  5630. .onClick(() => {
  5631. if (!Utility.isNoble()) {
  5632. this.showVipDialog()
  5633. return
  5634. }
  5635. this.isConverter = !this.isConverter
  5636. })
  5637. MenuItem({
  5638. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.ai_edit')),
  5639. content: $r('app.string.vocal_separation')
  5640. })
  5641. .bindContentCover($$this.isAIVoiceSeparation, this.AiBuilder(item), {
  5642. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5643. })
  5644. .onClick(() => {
  5645. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  5646. })
  5647. MenuItem({
  5648. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_counterclockwise_clock')),
  5649. content: $r('app.string.change_tone')
  5650. })
  5651. .bindContentCover($$this.isChangeTone, this.ChangeToneBuilder(item), {
  5652. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5653. })
  5654. .onClick(() => {
  5655. this.isChangeTone = !this.isChangeTone
  5656. })
  5657. if(Utility.isVideoByExtension(item.filePath)){
  5658. MenuItem({
  5659. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.identify_song')),
  5660. content: $r('app.string.extract_audio')
  5661. })
  5662. .bindContentCover($$this.isExtractAudio, this.extractAudioFromVideoBuilder(item), {
  5663. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5664. })
  5665. .onClick(() => {
  5666. this.isExtractAudio = !this.isExtractAudio
  5667. })
  5668. }
  5669. MenuItem({
  5670. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.phone')),
  5671. content: $r('app.string.set_ring')
  5672. })
  5673. .onClick(async () => {
  5674. await PermissionUtil.activatePermission(item.filePath)
  5675. // if(item.filePath.includes(this.packName)){
  5676. setRingTone(this.context, item.filePath,item.name)
  5677. // }else{
  5678. // ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限设置铃声')
  5679. // }
  5680. this.longItemFilePath = ''
  5681. })
  5682. MenuItem({
  5683. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  5684. content: $r('app.string.rename')
  5685. })
  5686. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  5687. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5688. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  5689. .onClick(() => {
  5690. this.showReNameDialog(item, index + '', filePath)
  5691. this.longItemFilePath = ''
  5692. })
  5693. MenuItem({
  5694. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  5695. content: $r('app.string.delete')
  5696. })
  5697. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  5698. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5699. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  5700. .onClick(() => {
  5701. this.selectedFiles.push(item)
  5702. this.showWarnIsDelete()
  5703. this.longItemFilePath = ''
  5704. })
  5705. MenuItem({
  5706. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  5707. content: $r('app.string.detail')
  5708. })
  5709. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  5710. height:'100%',
  5711. dragBar: true,
  5712. showClose: true,
  5713. blurStyle:BlurStyle.Thin,
  5714. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  5715. backgroundColor:Color.Transparent,
  5716. title: { title: '详情信息' }
  5717. })
  5718. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5719. .onClick(() => {
  5720. if(this.isGridMusic||this.twoFingerType==4){
  5721. this.longItemFilePathDetail = item.filePath
  5722. }else{
  5723. this.isShowDetail = !this.isShowDetail
  5724. }
  5725. })
  5726. MenuItem({
  5727. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  5728. content: $r('app.string.share')
  5729. })
  5730. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5731. .onClick(() => {
  5732. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  5733. this.longItemFilePath = ''
  5734. })
  5735. }
  5736. .font({ size: 14, weight: FontWeight.Normal })
  5737. }
  5738. .width(180)
  5739. }
  5740. .height('auto')
  5741. .enableScrollInteraction(true)
  5742. .scrollBar(this.isGridMusic?BarState.On:BarState.Off)
  5743. }
  5744. }
  5745. private listMaxScrollOffsetY: number = 0
  5746. @State selectedIndex: number = -1
  5747. setlistTwoFingers() {
  5748. this.pinchValue = this.scaleValue;
  5749. Logger.info('this.pinchValue = ' + this.pinchValue);
  5750. if (this.pinchValue >= 1) {
  5751. this.twoFingerType++
  5752. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  5753. if (this.twoFingerType > 3) {
  5754. this.twoFingerType = 1
  5755. this.isGridMusic = true
  5756. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5757. }
  5758. } else {
  5759. this.twoFingerType--
  5760. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  5761. if (this.twoFingerType < 1) {
  5762. this.twoFingerType = 4
  5763. this.columns = 1
  5764. }
  5765. }
  5766. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  5767. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5768. this.pinchValue = 1;
  5769. this.scaleValue = 1;
  5770. }
  5771. @Builder
  5772. getList(){
  5773. Stack() {
  5774. Refresh({ refreshing: $$this.isRefreshing, refreshingContent: this.contentNode }) {
  5775. this.getListView()
  5776. }
  5777. .pullDownRatio(this.ratioL)
  5778. .pullToRefresh(true)
  5779. .refreshOffset(0)
  5780. .onOffsetChange((offset: number) => {
  5781. // 越接近最大距离,下拉跟手系数越小。
  5782. this.ratioL = 1 - Math.pow((offset / this.maxRefreshingHeight), 3);
  5783. })
  5784. .onStateChange((refreshStatus: RefreshStatus) => {
  5785. console.info('onecold Refresh onStatueChange state is ' + refreshStatus);
  5786. })
  5787. .onRefreshing(async () => {
  5788. if(this.modeType==0){
  5789. this.getHistoryList(false)
  5790. this.asyncCurrentPathOnlyFile()
  5791. }else if(this.modeType == 1){
  5792. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  5793. }else if(this.modeType == 2){
  5794. workerInstance.postMessage({ code: 3, data: this.context });
  5795. }else if(this.modeType == 3){
  5796. workerInstance.postMessage({ code: 4, data: this.context });
  5797. }else if(this.modeType == 4){
  5798. this.doSongListTask()
  5799. }
  5800. console.log('onRefreshing test');
  5801. })
  5802. }
  5803. }
  5804. // 扫描当前目录下的文件,不扫描子目录
  5805. asyncCurrentPathOnlyFile(){
  5806. if(this.modeType==0){
  5807. const task = new taskpool.Task(scanCurrentDirectoryTask, getContext(this), this.currentPath,
  5808. this.lockPath,PreferencesUtil.getStringSync('COVER_API',''));
  5809. taskpool.execute(task, taskpool.Priority.HIGH).then(()=>{
  5810. if(this.modeType==0){
  5811. setTimeout(()=>{
  5812. this.isRefreshing =false
  5813. this.deleteCache(this.currentPath)
  5814. this.getSortedFiles(this.currentPath)
  5815. },500)
  5816. }
  5817. }).catch((e:object)=>{
  5818. this.isRefreshing =false
  5819. console.info("onecold task1 catch e: " + e);
  5820. })
  5821. }
  5822. }
  5823. @Builder
  5824. getListView() {
  5825. List({ scroller: this.listScroller }) {
  5826. // ListItemGroup({ header: this.coverHeader() }) {
  5827. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5828. ListItem() {
  5829. Column() {
  5830. if (item.type === CommonConstants.TYPE_IS_DIR
  5831. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  5832. this.DirItem(item, index)
  5833. } else {
  5834. this.MusicItem(item, index)
  5835. }
  5836. }
  5837. .animation({ curve: Curve.Sharp, duration: 300 })
  5838. }
  5839. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.9, y: 0.9 })
  5840. .animation({ duration: 500 }),
  5841. TransitionEffect.scale({ x: 0, y: 0 })))
  5842. .clickEffect({ level: ClickEffectLevel.LIGHT })
  5843. .swipeAction((
  5844. (this.isSwipe&&this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack))
  5845. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  5846. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath),
  5847. start:null,edgeEffect: SwipeEdgeEffect.None } : {}) //左滑
  5848. .onClick(() => {
  5849. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5850. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5851. this.handleFileSelection(item, !isChecked);
  5852. } else {
  5853. this.doPlay(item, index)
  5854. }
  5855. })
  5856. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5857. // 加载中指示器
  5858. if (this.isLoadingPage) {
  5859. ListItem() {
  5860. Row() {
  5861. LoadingProgress()
  5862. .width(30)
  5863. .height(30)
  5864. .color(this.themeColor)
  5865. Text('加载中...')
  5866. .margin({ left: 10 })
  5867. .fontSize(14)
  5868. .fontColor($r('app.color.text_color'))
  5869. }
  5870. .width('100%')
  5871. .justifyContent(FlexAlign.Center)
  5872. .padding(20)
  5873. }
  5874. }
  5875. }
  5876. .onScrollStart(() => {
  5877. this.isScrolling = true
  5878. this.showAlphabetIndex()
  5879. })
  5880. .onScrollIndex((start: number,center:number,end:number) => {
  5881. this.selectedIndex = start
  5882. if(start >= 0 && start < this.videoLocalList.length){
  5883. this.selectAlphaBetIndex = this.findAlphaBetIndex(this.videoLocalList[start])
  5884. }
  5885. })
  5886. .onScrollStop(() => {
  5887. if(this.isScrolling){
  5888. this.isScrolling = false
  5889. }
  5890. this.hideAlphabetIndexAfterDelay(1500)
  5891. })
  5892. .onReachEnd(() => {
  5893. if(this.modeType === 4 )//歌单不能加载下一页
  5894. return;
  5895. // 触底加载下一页
  5896. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  5897. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  5898. return;
  5899. }
  5900. if (this.hasMoreData && !this.isLoadingPage) {
  5901. this.loadNextPage();
  5902. }
  5903. })
  5904. .scrollBar(BarState.Off)
  5905. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  5906. .gesture(PinchGesture({ fingers: 2 })
  5907. .onActionEnd((event: GestureEvent) => {
  5908. this.setlistTwoFingers()
  5909. })
  5910. .onActionUpdate(e => {
  5911. this.scaleValue = this.pinchValue * e.scale
  5912. })
  5913. .onActionStart(e => {
  5914. }))
  5915. .contentStartOffset(this.topSafeHeight + 55)
  5916. .scrollBar(BarState.Off)
  5917. .contentEndOffset(this.bottomBarHeight+this.bottomSafeHeight)
  5918. .cachedCount(10)
  5919. // .reuseId('list_item')
  5920. .borderRadius(20)
  5921. .layoutWeight(1)
  5922. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  5923. .lanes(
  5924. new BreakpointType<number>({
  5925. sm: 1,
  5926. md: 2,
  5927. lg: 2,
  5928. xl: 3,
  5929. xxl: 4
  5930. }).getValue(this.currentBreakpoint),
  5931. new BreakpointType<number>({
  5932. sm: 0,
  5933. md: 12,
  5934. lg: 12,
  5935. xl: 16,
  5936. xxl: 20
  5937. }).getValue(this.currentBreakpoint)
  5938. )
  5939. .onAreaChange((oldValue: Area, newValue: Area) => {
  5940. this.listArea = newValue
  5941. if (this.twoFingerType == 3) {
  5942. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  5943. } else if (this.twoFingerType == 2) {
  5944. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  5945. } else if (this.twoFingerType == 1) {
  5946. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  5947. }
  5948. })
  5949. .onScrollFrameBegin((offset: number) => {
  5950. // 获取当前滚动偏移量
  5951. if(this.autoHideTitle){
  5952. const currentOffsetY = this.listScroller.currentOffset().yOffset;
  5953. // 判断滚动方向
  5954. if (currentOffsetY > this.prevOffsetY) {
  5955. // console.log("onecold 向上滚动");
  5956. this.isShowTitleBar = false
  5957. } else if (currentOffsetY < this.prevOffsetY) {
  5958. // console.log("onecold 向下滚动");
  5959. this.isShowTitleBar = true
  5960. }
  5961. // 更新前一次偏移量
  5962. this.prevOffsetY = currentOffsetY;
  5963. }
  5964. return { offsetRemain: offset };
  5965. })
  5966. }
  5967. setBarHeightNormal() {
  5968. this.hideDone = false;
  5969. this.getUIContext().animateTo({
  5970. duration: 300
  5971. }, () => {
  5972. this.bottomBarHeight = 68 + 0;
  5973. this.topBarHeight = 50 + 0;
  5974. this.barOpacity = 1;
  5975. this.barBottomOpacity = 1
  5976. this.currentYOffset = 0;
  5977. this.isHiding = false;
  5978. });
  5979. }
  5980. setBarHeightHide(offset: number) {
  5981. if (offset > 0 && !this.hideDone) {
  5982. this.currentYOffset += offset;
  5983. if (this.currentYOffset <= 100) {
  5984. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  5985. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  5986. this.barOpacity = 1 - this.currentYOffset / 100;
  5987. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  5988. } else {
  5989. this.topBarHeight = 0;
  5990. this.bottomBarHeight = 0;
  5991. this.barBottomOpacity = 0
  5992. this.barOpacity = 0;
  5993. this.hideDone = true;
  5994. }
  5995. this.isHiding = true;
  5996. }
  5997. if (offset < 0 && this.isHiding) {
  5998. this.hideDone = false;
  5999. this.getUIContext().animateTo({
  6000. duration: 300
  6001. }, () => {
  6002. this.bottomBarHeight = 68 + 0;
  6003. this.topBarHeight = 50 + 0;
  6004. this.barOpacity = 1;
  6005. this.barBottomOpacity = 1
  6006. this.currentYOffset = 0;
  6007. this.isHiding = false;
  6008. });
  6009. }
  6010. }
  6011. //这个方法没隐藏bottomBar,只隐藏topbar
  6012. setBarHeightHide2(offset: number) {
  6013. if (offset > 0 && !this.hideDone) {
  6014. this.currentYOffset += offset;
  6015. if (this.currentYOffset <= 100) {
  6016. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  6017. this.barOpacity = 1 - this.currentYOffset / 100;
  6018. } else {
  6019. this.topBarHeight = 0;
  6020. this.barOpacity = 0;
  6021. this.hideDone = true;
  6022. }
  6023. this.isHiding = true;
  6024. }
  6025. if (offset < 0 && this.isHiding) {
  6026. this.hideDone = false;
  6027. this.getUIContext().animateTo({
  6028. duration: 300
  6029. }, () => {
  6030. this.topBarHeight = 50 + 0;
  6031. this.barOpacity = 1;
  6032. this.currentYOffset = 0;
  6033. this.isHiding = false;
  6034. });
  6035. }
  6036. }
  6037. private async doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean,isOpen?:boolean) {
  6038. Logger.info(`heanup doPlay被调用 - 歌曲: ${item.name}, 文件路径: ${item.filePath}, 索引: ${index}, 类型: ${item.type}, isFromSonPlayList: ${isFromSonPlayList}`)
  6039. switch (item.type) {
  6040. case CommonConstants.TYPE_IS_DIR:
  6041. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  6042. let offsetB = 0
  6043. if(this.twoFingerType==4){
  6044. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6045. let cur = this.waterScroller.currentOffset()
  6046. if (cur && typeof cur.yOffset === 'number') {
  6047. offsetB = cur.yOffset
  6048. }
  6049. }
  6050. this.mScrollMap.set('lastWaterDirScrollOffset', offsetB)
  6051. }else
  6052. if (this.isGridMusic) {
  6053. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6054. let cur = this.scroller.currentOffset()
  6055. if (cur && typeof cur.yOffset === 'number') {
  6056. offsetB = cur.yOffset
  6057. }
  6058. }
  6059. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  6060. } else {
  6061. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6062. let cur = this.listScroller.currentOffset()
  6063. if (cur && typeof cur.yOffset === 'number') {
  6064. offsetB = cur.yOffset
  6065. }
  6066. }
  6067. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  6068. }
  6069. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  6070. this.showVerifyDialog()
  6071. this.currentTitleName = '私密音频'
  6072. this.currentTitleCover = $r('app.media.alt')
  6073. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  6074. this.titleName = '最近播放'
  6075. this.currentTitleCover = $r('app.media.alt')
  6076. this.currentTitleName = '最近播放'
  6077. //加载动画效果
  6078. this.updateListData(this.historyList, true)
  6079. // this.videoLocalList = this.historyList
  6080. if (ArrayUtil.isEmpty(this.historyList)) {
  6081. ToastUtil.showToast('最近播放记录空空如也')
  6082. } else {
  6083. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  6084. }
  6085. this.isHistory = true
  6086. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  6087. this.titleName = '我的收藏'
  6088. this.currentTitleName = '我的收藏'
  6089. this.currentTitleCover = $r('app.media.alt')
  6090. //加载动画效果
  6091. this.updateListData(this.favList, true)
  6092. if (ArrayUtil.isEmpty(this.favList)) {
  6093. ToastUtil.showToast('无音乐收藏记录')
  6094. } else {
  6095. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  6096. }
  6097. this.isFavMusic = true
  6098. } else {
  6099. this.currentTitleName = item.name
  6100. this.currentPath = item.filePath
  6101. this.currentTitleCover = $r('app.media.alt')
  6102. this.getSortedFiles(this.currentPath)
  6103. }
  6104. //进入歌单的时候的滚动位置在顶部
  6105. if(this.twoFingerType==4){
  6106. setTimeout(() => {
  6107. this.waterScroller.scrollEdge(Edge.Top)
  6108. this.scroller.scrollEdge(Edge.Top)
  6109. }, 200)
  6110. }else{
  6111. if (this.isGridMusic) {
  6112. this.scroller.scrollToIndex(0,false)
  6113. }else{
  6114. this.listScroller.scrollToIndex(0,false)
  6115. }
  6116. }
  6117. this.rightTopImage = $r('sys.symbol.chevron_left')
  6118. break;
  6119. case CommonConstants.TYPE_IS_ARTIST:
  6120. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  6121. let offsetA = 0
  6122. if(this.twoFingerType==4){
  6123. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6124. let cur = this.waterScroller.currentOffset()
  6125. if (cur && typeof cur.yOffset === 'number') {
  6126. offsetA = cur.yOffset
  6127. }
  6128. }
  6129. this.mScrollMap.set('lastWaterArtistScrollOffset', offsetA)
  6130. }else
  6131. if (this.isGridMusic) {
  6132. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6133. let cur = this.scroller.currentOffset()
  6134. if (cur && typeof cur.yOffset === 'number') {
  6135. offsetA = cur.yOffset
  6136. }
  6137. }
  6138. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  6139. } else {
  6140. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6141. let cur = this.listScroller.currentOffset()
  6142. if (cur && typeof cur.yOffset === 'number') {
  6143. offsetA = cur.yOffset
  6144. }
  6145. }
  6146. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  6147. }
  6148. // 进入艺术家详情页前,先加载详情页的排序类型
  6149. // 注意:需要临时设置isCanBack=true,以便loadSortTypeForCurrentMode读取详情页的排序设置
  6150. const artistOriginalIsCanBack = this.isCanBack;
  6151. this.isCanBack = true;
  6152. const artistDetailSortType = this.loadSortTypeForCurrentMode();
  6153. this.isCanBack = artistOriginalIsCanBack; // 恢复原值
  6154. Logger.info('heanup LocalMusic', `进入艺术家详情页: 加载详情页排序 sortType=${artistDetailSortType}`);
  6155. // 缓存键需要包含排序类型,因为不同的排序类型会产生不同的数据
  6156. const artistCacheKey = `${item.name}_sort_${artistDetailSortType}`;
  6157. let mList = this.artistMap.get(artistCacheKey)
  6158. if (mList === undefined || ArrayUtil.isEmpty(mList)) {
  6159. // 使用详情页的排序类型查询
  6160. mList = await this.table.querySongsByArtist(item.name, artistDetailSortType, this.isShowFileName);
  6161. if (ArrayUtil.isNotEmpty(mList)) {
  6162. this.artistMap.set(artistCacheKey, mList);
  6163. }
  6164. }
  6165. // 设置当前排序类型为详情页排序
  6166. this.sortType = artistDetailSortType;
  6167. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  6168. // 注意:不再调用 Utility.doSortListAscending,因为数据已经按 artistDetailSortType 排序了
  6169. const nextArtistCountMap = new Map(this.artistSongCountMap);
  6170. nextArtistCountMap.set(item.name, mList.length);
  6171. this.artistSongCountMap = nextArtistCountMap;
  6172. this.isCanBack = true
  6173. this.hasMoreData = false
  6174. this.isLoadingPage = false
  6175. this.pageCache.clear()
  6176. this.totalCount = mList.length
  6177. this.titleName = item.name
  6178. this.currentTitleName = '艺术家:' + item.name
  6179. if (item.pixelMapPath) {
  6180. this.currentTitleCover = item.pixelMapPath
  6181. }
  6182. this.updateListData(mList, true) // 使用 true 跳过排序
  6183. } else {
  6184. ToastUtil.showToast('未找到该艺术家的歌曲');
  6185. return;
  6186. }
  6187. this.rightTopImage = $r('sys.symbol.chevron_left')
  6188. //进入歌单的时候的滚动位置在顶部
  6189. if(this.twoFingerType==4){
  6190. setTimeout(() => {
  6191. this.waterScroller.scrollEdge(Edge.Top)
  6192. this.scroller.scrollEdge(Edge.Top)
  6193. }, 380)
  6194. }else{
  6195. if (this.isGridMusic) {
  6196. this.scroller.scrollEdge(Edge.Top)
  6197. }else{
  6198. this.listScroller.scrollEdge(Edge.Top)
  6199. }
  6200. }
  6201. break;
  6202. case CommonConstants.TYPE_IS_ALBUM:
  6203. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  6204. let offset = 0
  6205. if(this.twoFingerType==4){
  6206. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6207. let cur = this.waterScroller.currentOffset()
  6208. if (cur && typeof cur.yOffset === 'number') {
  6209. offset = cur.yOffset
  6210. }
  6211. }
  6212. this.mScrollMap.set('lastWaterAlBumScrollOffset', offset)
  6213. }else
  6214. if (this.isGridMusic) {
  6215. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6216. let cur = this.scroller.currentOffset()
  6217. if (cur && typeof cur.yOffset === 'number') {
  6218. offset = cur.yOffset
  6219. }
  6220. }
  6221. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  6222. } else {
  6223. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6224. let cur = this.listScroller.currentOffset()
  6225. if (cur && typeof cur.yOffset === 'number') {
  6226. offset = cur.yOffset
  6227. }
  6228. }
  6229. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  6230. }
  6231. // 进入专辑详情页前,先加载详情页的排序类型
  6232. // 注意:需要临时设置isCanBack=true,以便loadSortTypeForCurrentMode读取详情页的排序设置
  6233. const albumOriginalIsCanBack = this.isCanBack;
  6234. this.isCanBack = true;
  6235. const albumDetailSortType = this.loadSortTypeForCurrentMode();
  6236. this.isCanBack = albumOriginalIsCanBack; // 恢复原值
  6237. Logger.info('heanup LocalMusic', `进入专辑详情页: 加载详情页排序 sortType=${albumDetailSortType}`);
  6238. // 缓存键需要包含排序类型,因为不同的排序类型会产生不同的数据
  6239. const albumCacheKey = `${item.name}_sort_${albumDetailSortType}`;
  6240. let albumList = this.albumMap.get(albumCacheKey)
  6241. if (albumList === undefined || ArrayUtil.isEmpty(albumList)) {
  6242. // 使用详情页的排序类型查询
  6243. albumList = await this.table.querySongsByAlbum(item.name, albumDetailSortType, this.isShowFileName);
  6244. if (ArrayUtil.isNotEmpty(albumList)) {
  6245. this.albumMap.set(albumCacheKey, albumList);
  6246. }
  6247. }
  6248. // 设置当前排序类型为详情页排序
  6249. this.sortType = albumDetailSortType;
  6250. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  6251. // 注意:不再调用 Utility.doSortListAscending,因为数据已经按 albumDetailSortType 排序了
  6252. const nextAlbumCountMap = new Map(this.albumSongCountMap);
  6253. nextAlbumCountMap.set(item.name, albumList.length);
  6254. this.albumSongCountMap = nextAlbumCountMap;
  6255. this.isCanBack = true
  6256. this.hasMoreData = false
  6257. this.isLoadingPage = false
  6258. this.pageCache.clear()
  6259. this.totalCount = albumList.length
  6260. this.titleName = item.name
  6261. this.currentTitleName = '专辑:' + item.name
  6262. if (item.pixelMapPath) {
  6263. this.currentTitleCover = item.pixelMapPath
  6264. }
  6265. this.updateListData(albumList, true) // 使用 true 跳过排序
  6266. this.mScrollMap.set(item.name, this.selectedIndex)
  6267. this.rightTopImage = $r('sys.symbol.chevron_left')
  6268. } else {
  6269. ToastUtil.showToast('未找到该专辑的歌曲');
  6270. return;
  6271. }
  6272. //进入歌单的时候的滚动位置在顶部
  6273. if(this.twoFingerType==4){
  6274. setTimeout(() => {
  6275. this.waterScroller.scrollEdge(Edge.Top)
  6276. this.scroller.scrollEdge(Edge.Top)
  6277. }, 380)
  6278. }else{
  6279. if (this.isGridMusic) {
  6280. this.scroller.scrollEdge(Edge.Top)
  6281. }else{
  6282. this.listScroller.scrollEdge(Edge.Top)
  6283. }
  6284. }
  6285. break;
  6286. case CommonConstants.TYPE_IS_CSJAD:
  6287. return
  6288. break;
  6289. case CommonConstants.TYPE_LOCAL:
  6290. if(item&&item.filePath.toLowerCase().endsWith('.cue')){
  6291. const cueinfo:CueInfo = await parseCueFile(item.filePath)
  6292. const cueTracks:CueTrack[] = cueinfo.tracks
  6293. console.log('onecold cue cueTracks =', JSON.stringify(cueTracks));
  6294. if(ArrayUtil.isNotEmpty(cueTracks)){
  6295. this.showCueDialog(cueTracks,cueinfo)
  6296. }
  6297. // this.showCueSheet = !this.showCueSheet
  6298. return
  6299. }
  6300. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6301. this.stop();
  6302. }
  6303. if (isOpen) {
  6304. this.currentSong = item
  6305. if (index !== undefined) {
  6306. this.curIndex = index
  6307. }
  6308. this.songList = []
  6309. this.songList.push(item)
  6310. this.sonDataSource.pushArrayData(this.songList)
  6311. this.playQueueScope = 'single'
  6312. }else if(isFromSonPlayList){ //点击来自右下角的播放列表
  6313. this.currentSong = item
  6314. if (index !== undefined) {
  6315. this.curIndex = index
  6316. }
  6317. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  6318. Logger.info(`heanup isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  6319. this.playQueueScope = 'playlist'
  6320. // 确保歌单路径列表已设置(从songList重新构建,以防被清空)
  6321. if (this.currentPlaylistSongFilePaths.length === 0 && this.songList.length > 0) {
  6322. this.currentPlaylistSongFilePaths = this.songList.map(song => song.filePath);
  6323. Logger.info(`heanup isFromSonPlayList - 重新构建歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  6324. }
  6325. }else {
  6326. const globalVideoList = this.buildPlayQueueFromView();
  6327. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  6328. if (this.curIndex < 0) {
  6329. globalVideoList.push(item);
  6330. this.curIndex = globalVideoList.length - 1;
  6331. }
  6332. this.songList = globalVideoList
  6333. this.sonDataSource.pushArrayData(this.songList)
  6334. this.currentSong = this.songList[this.curIndex]
  6335. // 只在非歌单模式下清空歌单路径列表
  6336. if (this.modeType !== 4) {
  6337. this.currentPlaylistSongFilePaths = [];
  6338. Logger.info(`heanup doPlay设置播放列表 - 总歌曲数: ${this.songList.length}, 当前索引: ${this.curIndex}, 当前歌曲: ${this.currentSong?.name}, 已清空歌单路径列表(modeType=${this.modeType})`)
  6339. } else {
  6340. // 歌单模式:确保歌单路径列表已设置
  6341. if (this.currentPlaylistSongFilePaths.length === 0 && this.songList.length > 0) {
  6342. this.currentPlaylistSongFilePaths = this.songList.map(song => song.filePath);
  6343. Logger.info(`heanup doPlay设置播放列表 - 从songList重新构建歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  6344. } else {
  6345. Logger.info(`heanup doPlay设置播放列表 - 歌单模式,保持歌单路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  6346. }
  6347. }
  6348. }
  6349. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  6350. this.videoUrl = this.currentSong.filePath
  6351. this.name = this.currentSong.name
  6352. this.cover = this.currentSong.pixelMapPath
  6353. this.artist = this.currentSong.artist
  6354. LogUtil.info('onecold this.currentSong.cover =' + this.currentSong.pixelMapPath)
  6355. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  6356. this.startPlayOrResumePlay()
  6357. break;
  6358. case CommonConstants.TYPE_WEBDAV:
  6359. case CommonConstants.TYPE_SMB:
  6360. case CommonConstants.TYPE_NAVIDROME:
  6361. case CommonConstants.TYPE_FTP:
  6362. case CommonConstants.TYPE_BAIDU:
  6363. case CommonConstants.TYPE_JELLYFIN:
  6364. case CommonConstants.TYPE_EMBY:
  6365. case CommonConstants.TYPE_AUDIOSTATION:
  6366. case CommonConstants.TYPE_PLEX:
  6367. case CommonConstants.TYPE_DAOLIYU:
  6368. // 处理网络音频播放(WebDAV/SMB/Navidrome/Jellyfin/Emby/AudioStation/Plex/道理鱼/Baidu)
  6369. Logger.info(`heanup 处理云端音频播放: ${item.name}, URL: ${item.filePath}`)
  6370. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6371. this.stop();
  6372. }
  6373. if (isOpen) {
  6374. this.currentSong = item
  6375. if (index !== undefined) {
  6376. this.curIndex = index
  6377. }
  6378. this.songList = []
  6379. this.songList.push(item)
  6380. this.sonDataSource.pushArrayData(this.songList)
  6381. } else if (isFromSonPlayList) {
  6382. // 点击来自右下角的播放列表
  6383. this.currentSong = item
  6384. if (index !== undefined) {
  6385. this.curIndex = index
  6386. }
  6387. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  6388. Logger.info(`heanup 网络音频 isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  6389. } else {
  6390. // 从全局网络音频列表中查找
  6391. let globalVideoList = this.videoLocalList.filter(video => isRemoteCloudType(video.type)) as VideoItem[];
  6392. this.curIndex = globalVideoList.findIndex(video => video.filePath === item.filePath);
  6393. if (this.curIndex === -1 && index !== undefined) {
  6394. this.curIndex = index;
  6395. }
  6396. this.songList = globalVideoList.length > 0 ? globalVideoList : [item];
  6397. this.currentSong = this.songList[this.curIndex];
  6398. this.sonDataSource.pushArrayData(this.songList)
  6399. }
  6400. await this.hydrateRemoteSongFromDb(this.currentSong);
  6401. await this.hydrateRemoteSongFromDb(this.currentSong);
  6402. AppStorage.setOrCreate('currentSong', this.currentSong);
  6403. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  6404. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  6405. context: this.context,
  6406. autoParseMusicName: this.autoParseMusicName
  6407. });
  6408. Logger.info(TAG, `WebDAV URL同步构建完成(分支2): ${this.videoUrl}`);
  6409. this.name = this.currentSong.name
  6410. this.cover = this.currentSong.pixelMapPath
  6411. this.artist = this.currentSong.artist
  6412. Logger.info(`heanup 准备播放网络音频 - 歌名: ${this.name}, 艺术家: ${this.artist}, 完整URL: ${this.videoUrl}`)
  6413. this.startPlayOrResumePlay()
  6414. break;
  6415. }
  6416. }
  6417. private cueComponentId: number = 0
  6418. //显示cue分轨列表对话框
  6419. showCueDialog(cueTracks:CueTrack[],cueinfo:CueInfo){
  6420. this.getUIContext().getPromptAction().openCustomDialog({
  6421. builder: () => {
  6422. this.cueComptentBuilder(cueTracks,cueinfo)
  6423. },
  6424. isModal:true,
  6425. showInSubWindow:false,
  6426. maskColor: Color.Transparent,
  6427. dialogTransition: // 设置弹窗内容显示的过渡效果
  6428. TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  6429. .animation({ duration: 600, curve: Curve.Smooth }),
  6430. maskTransition: // 设置蒙层显示的过渡效果
  6431. TransitionEffect.opacity(0.5)
  6432. .animation({ duration: 600, curve: Curve.Smooth })
  6433. }).then((dialogId: number) => {
  6434. this.cueComponentId = dialogId
  6435. })
  6436. .catch((error: BusinessError) => {
  6437. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  6438. })
  6439. }
  6440. @Builder
  6441. cueComptentBuilder(cueTracks:CueTrack[]=[],cueinfo:CueInfo){
  6442. CueComptent({
  6443. title:cueinfo.title,
  6444. cueTracks:cueTracks,
  6445. isLongNameRoLL:this.isLongNameRoLL,
  6446. onCancel:()=>{
  6447. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId)
  6448. },
  6449. onDoItemClick: async (item: CueTrack, index: number)=>{
  6450. //获取cueinfo对应的filePath
  6451. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  6452. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, cueinfo.filePath)
  6453. this.currentSong = Utility.getItemByFilePath(globalVideoList, cueinfo.filePath)
  6454. console.info('onecold cueinfo.filePath=', cueinfo.filePath)
  6455. console.info('onecold this.currentSong =', JSON.stringify(this.currentSong))
  6456. if (this.currentSong){
  6457. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6458. this.stop();//播放之前先停止之前播放。
  6459. }
  6460. this.songList = globalVideoList
  6461. this.sonDataSource.pushArrayData(this.songList)
  6462. if (this.currentSong) {
  6463. try {
  6464. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  6465. context: this.context,
  6466. autoParseMusicName: this.autoParseMusicName
  6467. });
  6468. } catch (error) {
  6469. Logger.error(TAG, `CUE 点播构建播放地址失败: ${(error as Error).message}`);
  6470. this.videoUrl = this.currentSong.filePath;
  6471. }
  6472. }
  6473. this.name = item.title||this.currentSong.name
  6474. this.cover = this.currentSong.pixelMapPath
  6475. this.artist = item.performer||this.currentSong.artist
  6476. this.currentSong.name = this.name
  6477. this.currentSong.artist = this.artist
  6478. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  6479. this.startPlayOrResumePlay(item.startOffset)//从cue的某个位置开始播放
  6480. }
  6481. }
  6482. })
  6483. }
  6484. @State isFrontWhite: boolean = false
  6485. setShowPlayTrue(){
  6486. this.getUIContext()?.animateTo({
  6487. duration: 500,
  6488. curve: Curve.Friction
  6489. }, () => {
  6490. this.isShowPlay = true;
  6491. });
  6492. }
  6493. setShowPlayFalse(){
  6494. this.getUIContext()?.animateTo({
  6495. duration: 500,
  6496. curve: Curve.Friction
  6497. }, () => {
  6498. this.isShowPlay = false;
  6499. });
  6500. }
  6501. //打开播放页
  6502. showPlayerView() {
  6503. console.info('onecold showPlayerView this.songList'+ JSON.stringify(this.songList))
  6504. if (ArrayUtil.isNotEmpty(this.songList)) {
  6505. // this.setShowPlayTrue()
  6506. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
  6507. this.initLyric(lyricPath);
  6508. this.startAutoHide();
  6509. } else {
  6510. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  6511. }
  6512. }
  6513. //打开播放列表
  6514. openPlayList(){
  6515. if (ArrayUtil.isNotEmpty(this.songList)) {
  6516. this.isShowSheet = !this.isShowSheet;
  6517. this.isFrontWhite = false
  6518. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  6519. this.scrollIndex()
  6520. // 只有在播放本地音乐时才自动加载完整列表
  6521. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_LOCAL) {
  6522. void this.hydrateFullMediaPlayListIfNeeded();
  6523. }
  6524. } else {
  6525. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  6526. }
  6527. }
  6528. scrollIndex(){
  6529. try {
  6530. setTimeout(() => {
  6531. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  6532. if(this.curIndex>60){
  6533. this.playListScroller.scrollToIndex(this.curIndex,false, ScrollAlign.CENTER)
  6534. }else{
  6535. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  6536. }
  6537. })
  6538. }, 123)
  6539. }catch (error) {
  6540. console.error(`onecold scrollIndex出错: ${error}`);
  6541. }
  6542. }
  6543. scrollIndexMain(dialogId?:string){
  6544. try {
  6545. setTimeout(() => {
  6546. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  6547. console.info('heanup scrollIndexMain this.curIndex='+this.curIndex)
  6548. if(dialogId)
  6549. DialogHelper.closeDialog(dialogId)
  6550. let isAni:boolean = false
  6551. if(this.curIndex<50){
  6552. isAni = true
  6553. }
  6554. if(this.twoFingerType==4){
  6555. this.waterScroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  6556. }else{
  6557. if(this.isGridMusic){
  6558. this.scroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  6559. }else{
  6560. this.listScroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  6561. }
  6562. }
  6563. })
  6564. }, 123)
  6565. }catch (error) {
  6566. console.error(`onecold scrollIndexMain出错: ${error}`);
  6567. }
  6568. }
  6569. // 智能定位当前播放歌曲,如果当前页没有则加载完整列表
  6570. async locateCurrentSong(): Promise<void> {
  6571. if (!this.currentSong) {
  6572. console.warn("heanup locateCurrentSong: 当前没有播放的歌曲");
  6573. return;
  6574. }
  6575. // 检查当前播放歌曲是否在已加载的列表中
  6576. const targetIndex = Utility.getIndexFromList(this.videoLocalList, this.currentSong.filePath);
  6577. if (targetIndex > 0) {
  6578. // 歌曲在当前列表中,直接滚动
  6579. console.info("heanup locateCurrentSong: 找到歌曲,索引=" + targetIndex);
  6580. this.curIndex = targetIndex;
  6581. this.scrollIndexMain();
  6582. } else {
  6583. // 歌曲不在当前列表中,加载当前歌曲再第几页完整列表后再定位
  6584. console.info("heanup locateCurrentSong: 歌曲不在当前列表,开始加载完整列表");
  6585. const dialogID = DialogHelper.showLoadingDialog()
  6586. await this.hydrateFullMediaPlayListIfNeeded(false);
  6587. this.curIndex = Utility.getIndexFromList(this.videoLocalList, this.currentSong.filePath);
  6588. this.scrollIndexMain(dialogID);
  6589. }
  6590. }
  6591. //播放列表布局
  6592. @Builder
  6593. PlayListSheet() {
  6594. Column() {
  6595. this.PlayList()
  6596. }
  6597. .width('100%')
  6598. .height('100%')
  6599. }
  6600. @State titleStr: string = ''
  6601. @State ablumStr: string = ''
  6602. @State artistStr: string = ''
  6603. @State lyricConStr: string = ''
  6604. @State currentEditItem: string = ''
  6605. @State yearStr: string = ''
  6606. @State trackStr: string = ''
  6607. @State genreStr: string = ''
  6608. @State imagePathStr: string = ''
  6609. @State albumArtistStr: string = ''
  6610. @State composerStr: string = ''
  6611. @State lyricistStr: string = ''
  6612. @State commentStr: string = ''
  6613. @State discStr: string = ''
  6614. doUpdateData() {
  6615. setTimeout(async () => {
  6616. if (this.modeType === 0) {
  6617. this.deleteCache(this.currentPath)
  6618. await this.resetAndLoadFirstPage();
  6619. }else if (this.modeType === 1){
  6620. await this.resetAndLoadFirstPage();
  6621. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6622. }
  6623. }, 500)
  6624. }
  6625. doAllUpdateData() {
  6626. setTimeout(async () => {
  6627. if (this.modeType === 0) {
  6628. this.deleteCache(this.currentPath)
  6629. await this.resetAndLoadFirstPage();
  6630. }else{
  6631. await this.resetAndLoadFirstPage();
  6632. }
  6633. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6634. workerInstance.postMessage({ code: 3, data: this.context });
  6635. workerInstance.postMessage({ code: 4, data: this.context });
  6636. }, 999)
  6637. }
  6638. /**
  6639. * 加载指定页的数据
  6640. */
  6641. private async loadPage(pageIndex: number, append: boolean = true): Promise<void> {
  6642. try {
  6643. // 1. 检查缓存
  6644. if (this.pageCache.has(pageIndex)) {
  6645. Logger.info('heanup LocalMusic', `loadPage: 从缓存加载 page=${pageIndex}`);
  6646. const cachedData = this.pageCache.get(pageIndex)!;
  6647. if (append) {
  6648. this.videoLocalList = [...this.videoLocalList, ...cachedData];
  6649. } else {
  6650. this.videoLocalList = cachedData;
  6651. }
  6652. this.dataSource.pushArrayData(this.videoLocalList);
  6653. return;
  6654. }
  6655. this.isLoadingPage = true;
  6656. Logger.info('heanup LocalMusic', `loadPage: 开始加载 page=${pageIndex}, size=${this.pageSize}, mode=${this.modeType}`);
  6657. // 2. 构造查询参数
  6658. const options: PageQueryOptions = {
  6659. pageIndex: pageIndex,
  6660. pageSize: this.pageSize,
  6661. sortType: this.sortType,
  6662. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  6663. isShowFileName: this.isShowFileName
  6664. };
  6665. // 根据 modeType 补充查询条件
  6666. if (this.modeType === 0) {
  6667. options.parentPath = this.currentPath;
  6668. }
  6669. // 3. 执行查询
  6670. let result: PageQueryResult = { items: [], totalCount: 0, hasMore: false };
  6671. switch (this.modeType) {
  6672. case 0:
  6673. result = await this.table.queryByParentPathPaged(options);
  6674. // modeType=0时,第一页需要添加文件夹列表
  6675. if (pageIndex === 0 && !this.isSearchMode) {
  6676. const directories: VideoItem[] = await this.loadDirectories(this.currentPath);
  6677. result.items = [...directories, ...result.items];
  6678. result.totalCount += directories.length;
  6679. }
  6680. break;
  6681. case 1:
  6682. result = await this.table.queryMediaLibraryPaged(options);
  6683. break;
  6684. case 2:
  6685. result = await this.table.queryArtistsPaged(options);
  6686. break;
  6687. case 3:
  6688. result = await this.table.queryAlbumsPaged(options);
  6689. break;
  6690. default:
  6691. result = await this.table.queryMediaLibraryPaged(options);
  6692. break;
  6693. }
  6694. if (!result || result.items.length === 0) {
  6695. Logger.info('heanup LocalMusic', 'loadPage: 查询结果为空');
  6696. this.isLoadingPage = false;
  6697. this.hasMoreData = false;
  6698. // 即使为空也要更新UI,显示空状态
  6699. this.totalCount = 0;
  6700. this.videoLocalList = [];
  6701. this.dataSource.pushArrayData(this.videoLocalList);
  6702. this.setButtonStatus();
  6703. return;
  6704. }
  6705. // 4. 更新状态和缓存
  6706. this.totalCount = result.totalCount;
  6707. this.hasMoreData = result.hasMore;
  6708. if (this.modeType === 1) {
  6709. this.mediaKuCount = result.totalCount;
  6710. }
  6711. if (this.modeType === 2 && result.countMap) {
  6712. this.mergeArtistCountMap(result.countMap);
  6713. } else if (this.modeType === 3 && result.countMap) {
  6714. this.mergeAlbumCountMap(result.countMap);
  6715. }
  6716. Logger.info('heanup LocalMusic', `loadPage: 查询完成 items=${result.items.length}, total=${result.totalCount}, hasMore=${result.hasMore}`);
  6717. // 缓存管理 - 只保留最近3页
  6718. this.pageCache.set(pageIndex, result.items);
  6719. this.cleanOldCache(pageIndex);
  6720. // 5. 更新显示列表
  6721. if (append) {
  6722. this.videoLocalList = [...this.videoLocalList, ...result.items];
  6723. } else {
  6724. this.videoLocalList = result.items;
  6725. }
  6726. this.dataSource.pushArrayData(this.videoLocalList);
  6727. this.setButtonStatus();
  6728. this.setAlphaBet();
  6729. void this.prefetchNextPage(pageIndex + 1);
  6730. this.isLoadingPage = false;
  6731. } catch (err) {
  6732. const error = err as Error;
  6733. Logger.error('heanup LocalMusic', `loadPage error: ${error.message}`);
  6734. ToastUtil.showToast('加载数据失败');
  6735. this.isLoadingPage = false;
  6736. this.hasMoreData = false;
  6737. }
  6738. }
  6739. /**
  6740. * 清理旧缓存 - 只保留当前页前后各1页
  6741. */
  6742. private cleanOldCache(currentPage: number): void {
  6743. const pagesToKeep = new Set([currentPage - 1, currentPage, currentPage + 1]);
  6744. const keysToDelete: number[] = [];
  6745. this.pageCache.forEach((_, page) => {
  6746. if (!pagesToKeep.has(page)) {
  6747. keysToDelete.push(page);
  6748. }
  6749. });
  6750. keysToDelete.forEach(page => this.pageCache.delete(page));
  6751. if (keysToDelete.length > 0) {
  6752. Logger.info('heanup LocalMusic', `cleanOldCache: 清理了 ${keysToDelete.length} 页缓存`);
  6753. }
  6754. }
  6755. private async prefetchNextPage(nextPage: number): Promise<void> {
  6756. if (this.modeType !== 2 && this.modeType !== 3) {
  6757. return;
  6758. }
  6759. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  6760. return;
  6761. }
  6762. if (!this.hasMoreData || this.pageCache.has(nextPage) || this.prefetchingPages.has(nextPage)) {
  6763. return;
  6764. }
  6765. this.prefetchingPages.add(nextPage);
  6766. try {
  6767. const options: PageQueryOptions = {
  6768. pageIndex: nextPage,
  6769. pageSize: this.pageSize,
  6770. sortType: this.sortType,
  6771. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  6772. isShowFileName: this.isShowFileName
  6773. };
  6774. let result: PageQueryResult = { items: [], totalCount: 0, hasMore: false };
  6775. if (this.modeType === 2) {
  6776. result = await this.table.queryArtistsPaged(options);
  6777. if (result.countMap) {
  6778. this.mergeArtistCountMap(result.countMap);
  6779. }
  6780. } else if (this.modeType === 3) {
  6781. result = await this.table.queryAlbumsPaged(options);
  6782. if (result.countMap) {
  6783. this.mergeAlbumCountMap(result.countMap);
  6784. }
  6785. }
  6786. if (result.items.length > 0) {
  6787. this.pageCache.set(nextPage, result.items);
  6788. this.cleanOldCache(nextPage);
  6789. }
  6790. } catch (err) {
  6791. const error = err as Error;
  6792. Logger.warn('heanup LocalMusic', `prefetchNextPage error: ${error.message}`);
  6793. } finally {
  6794. this.prefetchingPages.delete(nextPage);
  6795. }
  6796. }
  6797. private mergeArtistCountMap(countMap: Map<string, number>): void {
  6798. const nextMap = new Map(this.artistSongCountMap);
  6799. countMap.forEach((count, artist) => {
  6800. nextMap.set(artist, count);
  6801. });
  6802. this.artistSongCountMap = nextMap;
  6803. }
  6804. private mergeAlbumCountMap(countMap: Map<string, number>): void {
  6805. const nextMap = new Map(this.albumSongCountMap);
  6806. countMap.forEach((count, album) => {
  6807. nextMap.set(album, count);
  6808. });
  6809. this.albumSongCountMap = nextMap;
  6810. }
  6811. private getArtistSongCount(artist: string): number {
  6812. return this.artistSongCountMap.get(artist) ?? this.artistMap.get(artist)?.length ?? 0;
  6813. }
  6814. private getAlbumSongCount(album: string): number {
  6815. return this.albumSongCountMap.get(album) ?? this.albumMap.get(album)?.length ?? 0;
  6816. }
  6817. /**
  6818. * 加载文件夹列表(仅用于modeType=0的首页模式)
  6819. */
  6820. private async loadDirectories(curPath: string): Promise<VideoItem[]> {
  6821. try {
  6822. Logger.info('heanup LocalMusic', `loadDirectories: 开始加载文件夹 path=${curPath}`);
  6823. // 检查缓存
  6824. const cacheKey = curPath + "_dirList";
  6825. const cachedDirList = this.findCache(cacheKey);
  6826. if (cachedDirList !== undefined && Array.isArray(cachedDirList)) {
  6827. Logger.info('heanup LocalMusic', `loadDirectories: 从缓存加载 count=${cachedDirList.length}`);
  6828. return cachedDirList as VideoItem[];
  6829. }
  6830. // 从文件系统读取
  6831. const fileList = FileUtil.listFileSync(curPath);
  6832. const directories: VideoItem[] = [];
  6833. for (let i = 0; i < fileList.length; i++) {
  6834. const path = curPath + '/' + fileList[i];
  6835. if (FileUtil.isDirectory(path)) {
  6836. const item: VideoItem = new VideoItem(
  6837. fileList[i].toString(),
  6838. fileList[i].toString(),
  6839. path,
  6840. CommonConstants.TYPE_IS_DIR,
  6841. 0,
  6842. ''
  6843. );
  6844. if (this.isShowDir(item.name)) {
  6845. directories.push(item);
  6846. }
  6847. }
  6848. }
  6849. // 排序
  6850. Utility.doSortListAscending(directories);
  6851. // 缓存文件夹列表
  6852. if (curPath === this.rootPath) {
  6853. this.dirList = directories;
  6854. this.addCache(cacheKey, directories);
  6855. }
  6856. Logger.info('heanup LocalMusic', `loadDirectories: 加载完成 count=${directories.length}`);
  6857. return directories;
  6858. } catch (err) {
  6859. const error = err as Error;
  6860. Logger.error('heanup LocalMusic', `loadDirectories error: ${error.message}`);
  6861. return [];
  6862. }
  6863. }
  6864. /**
  6865. * 构建播放队列(避免一次性加载全量)
  6866. */
  6867. private buildPlayQueueFromView(): Array<VideoItem> {
  6868. if (this.modeType === 4) {
  6869. this.playQueueScope = 'playlist';
  6870. return this.currentSongList;
  6871. }
  6872. if (this.isHistory) {
  6873. this.playQueueScope = 'history';
  6874. return this.historyList;
  6875. }
  6876. if (this.isFavMusic) {
  6877. this.playQueueScope = 'fav';
  6878. return this.favList;
  6879. }
  6880. this.playQueueScope = 'view';
  6881. return this.videoLocalList.filter((item: VideoItem) => item.type === CommonConstants.TYPE_LOCAL);
  6882. }
  6883. private async tryLoadNextPageForPlayback(): Promise<void> {
  6884. if (this.playQueueScope !== 'view') {
  6885. return;
  6886. }
  6887. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  6888. return;
  6889. }
  6890. if (!this.hasMoreData || this.isLoadingPage) {
  6891. return;
  6892. }
  6893. await this.loadNextPage();
  6894. const nextList = this.videoLocalList.filter((item: VideoItem) => item.type === CommonConstants.TYPE_LOCAL);
  6895. if (nextList.length > this.songList.length) {
  6896. this.songList = nextList;
  6897. this.sonDataSource.pushArrayData(this.songList);
  6898. }
  6899. }
  6900. /**
  6901. * 重置分页状态并加载首页
  6902. */
  6903. private async resetAndLoadFirstPage(): Promise<void> {
  6904. Logger.info('heanup LocalMusic', 'resetAndLoadFirstPage: 重置分页状态');
  6905. this.currentPage = 0;
  6906. this.videoLocalList = [];
  6907. this.pageCache.clear();
  6908. this.hasMoreData = true;
  6909. this.totalCount = 0;
  6910. if (this.modeType === 2) {
  6911. this.artistSongCountMap = new Map();
  6912. } else if (this.modeType === 3) {
  6913. this.albumSongCountMap = new Map();
  6914. }
  6915. await this.loadPage(0, false);
  6916. }
  6917. /**
  6918. * 加载下一页
  6919. */
  6920. private async loadNextPage(): Promise<void> {
  6921. if (this.hasMoreData && !this.isLoadingPage) {
  6922. this.currentPage++;
  6923. Logger.info('heanup LocalMusic', `loadNextPage: 加载第 ${this.currentPage} 页`);
  6924. await this.loadPage(this.currentPage, true);
  6925. }
  6926. }
  6927. //编辑信息
  6928. async doEdit(item: VideoItem) {
  6929. if (!item) {
  6930. return
  6931. }
  6932. if (StrUtil.isEmpty(this.titleStr)) {
  6933. ToastUtil.showToast('标题不能为空')
  6934. return
  6935. }
  6936. //内嵌音乐标签不能开启监听
  6937. // this.deletionWatcher?.stop();
  6938. this.loadingDialogId = DialogHelper.showLoadingDialog()
  6939. await PermissionUtil.activatePermission(item.filePath)
  6940. let tempOutPath = ''
  6941. // 如果不是 packName 包下的文件,则直接路径用this.currentPath
  6942. if(!item.filePath.toLowerCase().includes(this.packName)){
  6943. tempOutPath = this.currentPath + '/' + item.fileName
  6944. }
  6945. console.info('onecold tempOutPath ='+tempOutPath)
  6946. //用户更改了封面,那就内嵌下封面
  6947. if(StrUtil.isNotEmpty(this.imagePathStr)){
  6948. const resultCover:boolean = await changeMusicCover(this.context,
  6949. item.filePath,this.imagePathStr,true,tempOutPath);
  6950. this.imagePathStr = ''
  6951. if(resultCover){
  6952. ToastUtil.showToast('内嵌封面成功')
  6953. }
  6954. }
  6955. const metadata:FFMpegTags = {
  6956. title: this.titleStr,
  6957. artist: this.artistStr,
  6958. album: this.ablumStr,
  6959. TYER:this.yearStr,
  6960. genre:this.genreStr,
  6961. track:this.trackStr,
  6962. album_artist:this.albumArtistStr,
  6963. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  6964. COMPOSER:this.composerStr,
  6965. lyricist:this.lyricistStr,
  6966. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  6967. comment:this.commentStr,
  6968. disc:this.discStr,
  6969. };
  6970. let newInput = item.filePath
  6971. //内嵌标签歌路径如果不是包含包名,输入newInput要赋值tempOutPath,然后tempOutPath为空
  6972. if(!item.filePath.toLowerCase().includes(this.packName)&&FileUtil.accessSync(tempOutPath)){
  6973. newInput = tempOutPath
  6974. tempOutPath = ''
  6975. }
  6976. const isWav:boolean = newInput.toLowerCase().endsWith('.wav')
  6977. ||newInput.toLowerCase().endsWith('.ape');
  6978. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  6979. const result:boolean = await repairAudioMetadata(
  6980. newInput,
  6981. this.lyricConStr,
  6982. metadata,
  6983. true,
  6984. tempOutPath
  6985. );
  6986. if (result||isWav) {
  6987. if(!item.filePath.includes(this.packName)){
  6988. //内嵌成功的歌路径如果不是包含包名,则要入库
  6989. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newInput,
  6990. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  6991. this.table.insert(newItem, (id: number) => {
  6992. //加入数据库
  6993. if(this.modeType==0){
  6994. this.deleteCache(this.currentPath)
  6995. this.getSortedFiles(this.currentPath)
  6996. }
  6997. });
  6998. }
  6999. const task = new taskpool.Task(
  7000. updateInfoDb,
  7001. this.context,
  7002. item.filePath,
  7003. this.titleStr,
  7004. this.artistStr,
  7005. this.ablumStr,
  7006. this.lyricConStr,
  7007. this.yearStr,this.genreStr,
  7008. this.trackStr,this.albumArtistStr,
  7009. this.composerStr, this.lyricistStr,
  7010. this.commentStr,this.discStr
  7011. );
  7012. taskpool.execute(task, taskpool.Priority.HIGH).then((result) => {
  7013. if (result) {
  7014. console.log(" onecold 编辑信息成功,数据库已同步");
  7015. if(isWav){
  7016. ToastUtil.showToast('wav或者ape格式有可能内嵌失败,但是编辑信息成功')
  7017. }else{
  7018. ToastUtil.showToast('内嵌音乐标签成功')
  7019. }
  7020. this.isShowMoreView = false
  7021. this.name = this.titleStr
  7022. this.syncEditedFields(item)
  7023. if (item.filePath == this.currentSong?.filePath) {
  7024. this.currentSong.name = this.titleStr
  7025. this.artist = this.artistStr
  7026. this.currentSong.artist = this.artistStr
  7027. this.currentSong.album = this.ablumStr
  7028. this.currentSong.year = this.yearStr
  7029. this.currentSong.genre = this.genreStr
  7030. this.currentSong.track = this.trackStr
  7031. this.currentSong.lyricContent = this.lyricConStr
  7032. this.currentSong.ALBUMARTIST = this.albumArtistStr
  7033. this.currentSong.COMPOSER = this.composerStr
  7034. this.currentSong.LYRICIST = this.lyricistStr
  7035. this.currentSong.COMMENT = this.commentStr
  7036. }
  7037. this.syncListsAfterEdit(item.filePath)
  7038. this.doUpateEditedFields(item)
  7039. //this.doUpdateData()
  7040. } else {
  7041. // ToastUtil.showToast('保存失败' + error?.toString())
  7042. console.error(" onecold 编辑信息数据库失败 ");
  7043. }
  7044. // 关闭进度条
  7045. DialogHelper.closeDialog(this.loadingDialogId)
  7046. }).catch((error: Error) => {
  7047. // 关闭进度条
  7048. DialogHelper.closeDialog(this.loadingDialogId)
  7049. console.error('onecold Subtitle sync failed:', error);
  7050. });
  7051. console.log(' onecold 元数据标签更新成功,');
  7052. } else {
  7053. // 关闭进度条
  7054. DialogHelper.closeDialog(this.loadingDialogId)
  7055. ToastUtil.showToast('内嵌音乐标签失败')
  7056. console.log('onecold 内嵌音乐标签失败');
  7057. }
  7058. this.longItemFilePath = ''
  7059. this.tempLyricContent = ''
  7060. this.isShowEdit = false
  7061. }
  7062. // 内嵌标签更新当前内嵌的Item
  7063. async doUpateEditedFields(item: VideoItem) {
  7064. // 找到当前项在 videoLocalList 中的索引
  7065. const index = this.videoLocalList.findIndex(video => video.filePath === item.filePath);
  7066. if (index !== -1) {
  7067. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  7068. const updatedItem = await this.table.queryVideoByFilePath(item.filePath)
  7069. // 只有当查询结果不为 null 时才更新列表
  7070. if (updatedItem !== null) {
  7071. // 更新 videoLocalList 中的项(通过创建新数组触发响应式更新)
  7072. this.videoLocalList = [
  7073. ...this.videoLocalList.slice(0, index),
  7074. updatedItem,
  7075. ...this.videoLocalList.slice(index + 1)
  7076. ];
  7077. // 同步更新 LazyDataSource
  7078. this.dataSource.pushArrayData(this.videoLocalList)
  7079. } else {
  7080. ToastUtil.showToast('未找到更新的数据');
  7081. }
  7082. }
  7083. DialogHelper.closeDialog(this.loadingDialogId)
  7084. }
  7085. @Builder
  7086. editSheet(item: VideoItem) {
  7087. Scroll() {
  7088. Column() {
  7089. this.editDetail(item)
  7090. }
  7091. }
  7092. .width('100%')
  7093. .height('100%')
  7094. }
  7095. @Builder
  7096. editDetail(item: VideoItem) {
  7097. Column() {
  7098. if (item) {
  7099. Row() {
  7100. Stack() {
  7101. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  7102. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  7103. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
  7104. item.pixelMapPath)
  7105. .fillColor(this.themeColor)
  7106. .height(88)
  7107. .width(88)
  7108. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  7109. .borderRadius(12)
  7110. .clip(true)
  7111. .opacity(this.opacityItem)// 绑定透明度
  7112. .margin({ left: 25 })
  7113. }
  7114. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  7115. .onClick(async () => {
  7116. const imagePath:string | undefined = await this.goSelectImage(item);
  7117. if (imagePath) {
  7118. //用户更改过图片
  7119. this.imagePathStr = imagePath
  7120. }
  7121. })
  7122. .width('28%')
  7123. Row() {
  7124. Column() {
  7125. Text(item.name)
  7126. .fontSize(17)
  7127. .maxLines(1)
  7128. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  7129. .animation({
  7130. duration: 555,
  7131. curve: 'Linear',
  7132. })
  7133. .fontColor(this.themeColor)
  7134. .margin({ left: 8 })
  7135. Row() {
  7136. Text(item.artist)
  7137. .fontSize(14)
  7138. .maxLines(1)
  7139. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  7140. .padding({ top: 8 })
  7141. .fontColor(this.themeColor)
  7142. .margin({ left: 8 })
  7143. }
  7144. }
  7145. .height('100%')
  7146. .width(100)
  7147. .layoutWeight(1)
  7148. .justifyContent(FlexAlign.Center)
  7149. .alignItems(HorizontalAlign.Start)
  7150. Column() {
  7151. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7152. Row(){
  7153. SymbolGlyph($r('sys.symbol.picture'))
  7154. .fontSize(18)
  7155. .fontColor([Color.White])
  7156. Text('获取封面')
  7157. .margin({ left: 4 })
  7158. .fontSize(11)
  7159. .fontColor(Color.White)
  7160. .fontWeight(480)
  7161. .textAlign(TextAlign.Center)
  7162. }
  7163. .justifyContent(FlexAlign.Center)
  7164. }
  7165. .height(38)
  7166. .width(100)
  7167. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7168. .backgroundColor(this.themeColor)
  7169. .stateEffect(true)
  7170. .margin({ right: 35 })
  7171. .onClick(async () => {
  7172. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  7173. this.showTipsDialog();
  7174. return; // Return empty string when no API is configured
  7175. }
  7176. const imagePath:string | undefined = await this.doSearchCover(item,
  7177. this.titleStr,this.artistStr);
  7178. console.info('onecold imagePath = '+imagePath)
  7179. if (StrUtil.isNotEmpty(imagePath)) {
  7180. //用户更改过图片
  7181. this.imagePathStr = imagePath
  7182. ToastUtil.showToast('获取封面成功')
  7183. }else{
  7184. ToastUtil.showToast('获取封面失败,请重试')
  7185. }
  7186. })
  7187. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7188. Row(){
  7189. SymbolGlyph($r('sys.symbol.input_mode'))
  7190. .fontSize(18)
  7191. .fontColor([Color.White])
  7192. Text('获取歌词')
  7193. .margin({ left: 4 })
  7194. .fontSize(11)
  7195. .fontColor(Color.White)
  7196. .fontWeight(480)
  7197. .textAlign(TextAlign.Center)
  7198. }
  7199. .justifyContent(FlexAlign.Center)
  7200. }
  7201. .height(38)
  7202. .width(100)
  7203. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7204. .backgroundColor(this.themeColor)
  7205. .stateEffect(true)
  7206. .margin({ top: 9, right: 35 })
  7207. .onClick(async () => {
  7208. //判断有没有设置api
  7209. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  7210. if (StrUtil.isEmpty(apiUrl)) {
  7211. this.isLyricSetting = false
  7212. this.showTipsDialog()
  7213. return
  7214. }
  7215. let res: string | undefined = await getApiLyric(apiUrl,
  7216. this.titleStr, this.artistStr, false);
  7217. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  7218. this.lyricConStr = res;
  7219. ToastUtil.showToast('获取歌词成功')
  7220. }else{
  7221. ToastUtil.showToast('获取歌词失败,请重试')
  7222. }
  7223. })
  7224. }
  7225. .justifyContent(FlexAlign.Start)
  7226. }
  7227. .height('100%')
  7228. .justifyContent(FlexAlign.Start)
  7229. .layoutWeight(1)
  7230. }
  7231. .width('100%')
  7232. .height(98)
  7233. Row() {
  7234. Text('标题:')
  7235. .fontSize(14)
  7236. .fontColor($r('app.color.text_color'))
  7237. .margin({ left: 22 })
  7238. TextInput({ text: this.titleStr })
  7239. .height(40)
  7240. .maxLines(1)
  7241. .fontSize(14)
  7242. .layoutWeight(1)
  7243. .fontColor($r('app.color.text_color'))
  7244. .margin({ right: 15, left: 10 })
  7245. .onChange((val: string) => {
  7246. this.titleStr = val
  7247. })
  7248. Button('修复乱码',{ type: ButtonType.Capsule, stateEffect: true})
  7249. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7250. .backgroundColor(this.themeColor)
  7251. .fontSize(10)
  7252. .margin({ right: 20})
  7253. .onClick(async () => {
  7254. let hwTags = await extractHwMediaMetadata(item.filePath)
  7255. let artist = hwTags?.artist|| '';
  7256. let title = hwTags?.title|| '';
  7257. let album = hwTags?.album|| '';
  7258. console.info('onecold 乱码修正 artist='+artist);
  7259. console.info('onecold 乱码修正 title='+title);
  7260. console.info('onecold 乱码修正 album='+album);
  7261. this.titleStr = title;
  7262. this.artistStr = artist;
  7263. this.ablumStr = album;
  7264. })
  7265. }
  7266. .width('100%')
  7267. .margin({ top: 10, bottom: 10 })
  7268. .justifyContent(FlexAlign.Start)
  7269. Row() {
  7270. Text('艺术家:')
  7271. .fontSize(14)
  7272. .fontColor($r('app.color.text_color'))
  7273. .margin({ left: 22 })
  7274. TextInput({ text: this.artistStr })
  7275. .height(40)
  7276. .maxLines(1)
  7277. .fontSize(14)
  7278. .layoutWeight(1)
  7279. .fontColor($r('app.color.text_color'))
  7280. .margin({ right: 20, left: 10 })
  7281. .onChange((val: string) => {
  7282. this.artistStr = val
  7283. })
  7284. }
  7285. .width('100%')
  7286. .margin({ top: 10, bottom: 10 })
  7287. .justifyContent(FlexAlign.Start)
  7288. Row() {
  7289. Text('专辑名:')
  7290. .fontSize(14)
  7291. .fontColor($r('app.color.text_color'))
  7292. .margin({ left: 22 })
  7293. TextInput({ text: this.ablumStr})
  7294. .height(40)
  7295. .maxLines(1)
  7296. .fontSize(14)
  7297. .layoutWeight(1)
  7298. .fontColor($r('app.color.text_color'))
  7299. .margin({ right: 20, left: 10 })
  7300. .onChange((val: string) => {
  7301. this.ablumStr = val
  7302. })
  7303. }
  7304. .width('100%')
  7305. .margin({ top: 10, bottom: 10 })
  7306. .justifyContent(FlexAlign.Start)
  7307. Row() {
  7308. Column(){
  7309. Column(){
  7310. Text('歌词:')
  7311. .fontSize(14)
  7312. .fontColor($r('app.color.text_color'))
  7313. .margin({ top:9,left: 22 })
  7314. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7315. SymbolGlyph($r('sys.symbol.trash_fill'))
  7316. .fontSize(25)
  7317. .alignSelf(ItemAlign.Center)
  7318. .margin({ left: 22,top:25})
  7319. }
  7320. .backgroundColor(Color.Transparent)
  7321. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  7322. Visibility.None:Visibility.Visible)
  7323. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7324. .onClick(()=>{
  7325. this.lyricConStr = ''
  7326. this.lyricContent = ''
  7327. this.tempLyricContent = ''
  7328. })
  7329. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7330. SymbolGlyph($r('sys.symbol.plus'))
  7331. .fontSize(25)
  7332. .alignSelf(ItemAlign.Center)
  7333. .margin({ left: 22,top:25})
  7334. }
  7335. .backgroundColor(Color.Transparent)
  7336. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7337. .onClick( ()=>{
  7338. this.callFilePickerSelectFileForLyric()
  7339. })
  7340. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7341. SymbolGlyph($r('sys.symbol.traditional_square'))
  7342. .fontSize(25)
  7343. .alignSelf(ItemAlign.Center)
  7344. .margin({ left: 22,top:25})
  7345. }
  7346. .backgroundColor(Color.Transparent)
  7347. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  7348. Visibility.None:Visibility.Visible)
  7349. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7350. .onClick( ()=>{
  7351. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  7352. this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
  7353. })
  7354. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7355. Image($r('app.media.jianti'))
  7356. .height(25)
  7357. .fillColor($r('app.color.text_color'))
  7358. .alignSelf(ItemAlign.Center)
  7359. .margin({ left: 22,top:25})
  7360. }
  7361. .backgroundColor(Color.Transparent)
  7362. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  7363. Visibility.None:Visibility.Visible)
  7364. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7365. .onClick( ()=>{
  7366. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  7367. this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
  7368. })
  7369. }
  7370. .layoutWeight(1)
  7371. }
  7372. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  7373. this.tempLyricContent })
  7374. .type(TextAreaType.NORMAL)
  7375. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
  7376. .fontSize(14)
  7377. .layoutWeight(1)
  7378. .fontColor($r('app.color.text_color'))
  7379. .margin({ right: 20, left: 10 })
  7380. .onChange((val: string) => {
  7381. this.lyricConStr = val
  7382. })
  7383. }
  7384. .width('100%')
  7385. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
  7386. .margin({ top: 10, bottom: 10 })
  7387. .justifyContent(FlexAlign.Start)
  7388. Row() {
  7389. Text('年份:')
  7390. .fontSize(14)
  7391. .fontColor($r('app.color.text_color'))
  7392. .margin({ left: 22 })
  7393. TextInput({ text: item.year })
  7394. .height(40)
  7395. .maxLines(1)
  7396. .fontSize(14)
  7397. .type(InputType.Number)
  7398. .layoutWeight(1)
  7399. .fontColor($r('app.color.text_color'))
  7400. .margin({ right: 20, left: 10 })
  7401. .onChange((val: string) => {
  7402. this.yearStr = val
  7403. })
  7404. }
  7405. .width('100%')
  7406. .margin({ top: 10, bottom: 10 })
  7407. .justifyContent(FlexAlign.Start)
  7408. Row() {
  7409. Text('音轨号:')
  7410. .fontSize(14)
  7411. .fontColor($r('app.color.text_color'))
  7412. .margin({ left: 22 })
  7413. TextInput({ text:item.track=='未知'?'': item.track })
  7414. .height(40)
  7415. .maxLines(1)
  7416. .fontSize(14)
  7417. .type(InputType.Number)
  7418. .layoutWeight(1)
  7419. .fontColor($r('app.color.text_color'))
  7420. .margin({ right: 20, left: 10 })
  7421. .onChange((val: string) => {
  7422. this.trackStr = val
  7423. })
  7424. }
  7425. .width('100%')
  7426. .margin({ top: 10, bottom: 10 })
  7427. .justifyContent(FlexAlign.Start)
  7428. Row() {
  7429. Text('碟号:')
  7430. .fontSize(14)
  7431. .fontColor($r('app.color.text_color'))
  7432. .margin({ left: 22 })
  7433. TextInput({ text:item.disc })
  7434. .height(40)
  7435. .maxLines(1)
  7436. .fontSize(14)
  7437. .type(InputType.Number)
  7438. .layoutWeight(1)
  7439. .fontColor($r('app.color.text_color'))
  7440. .margin({ right: 20, left: 10 })
  7441. .onChange((val: string) => {
  7442. this.discStr = val
  7443. })
  7444. }
  7445. .width('100%')
  7446. .margin({ top: 10, bottom: 10 })
  7447. .justifyContent(FlexAlign.Start)
  7448. Row() {
  7449. Text('风格:')
  7450. .fontSize(14)
  7451. .fontColor($r('app.color.text_color'))
  7452. .margin({ left: 22 })
  7453. TextInput({ text: item.genre })
  7454. .height(40)
  7455. .maxLines(1)
  7456. .fontSize(14)
  7457. .layoutWeight(1)
  7458. .fontColor($r('app.color.text_color'))
  7459. .margin({ right: 20, left: 10 })
  7460. .onChange((val: string) => {
  7461. this.genreStr = val
  7462. })
  7463. }
  7464. .width('100%')
  7465. .margin({ top: 10, bottom: 10 })
  7466. .justifyContent(FlexAlign.Start)
  7467. Row() {
  7468. Text('专辑艺术家:')
  7469. .fontSize(14)
  7470. .fontColor($r('app.color.text_color'))
  7471. .margin({ left: 22 })
  7472. TextInput({ text: item.ALBUMARTIST })
  7473. .height(40)
  7474. .maxLines(1)
  7475. .fontSize(14)
  7476. .layoutWeight(1)
  7477. .fontColor($r('app.color.text_color'))
  7478. .margin({ right: 20, left: 10 })
  7479. .onChange((val: string) => {
  7480. this.albumArtistStr = val
  7481. })
  7482. }
  7483. .width('100%')
  7484. .margin({ top: 10, bottom: 10 })
  7485. .justifyContent(FlexAlign.Start)
  7486. Row() {
  7487. Text('作曲:')
  7488. .fontSize(14)
  7489. .fontColor($r('app.color.text_color'))
  7490. .margin({ left: 22 })
  7491. TextInput({ text: item.COMPOSER })
  7492. .height(40)
  7493. .maxLines(1)
  7494. .fontSize(14)
  7495. .layoutWeight(1)
  7496. .fontColor($r('app.color.text_color'))
  7497. .margin({ right: 20, left: 10 })
  7498. .onChange((val: string) => {
  7499. this.composerStr = val
  7500. })
  7501. }
  7502. .width('100%')
  7503. .margin({ top: 10, bottom: 10 })
  7504. .justifyContent(FlexAlign.Start)
  7505. Row() {
  7506. Text('作词:')
  7507. .fontSize(14)
  7508. .fontColor($r('app.color.text_color'))
  7509. .margin({ left: 22 })
  7510. TextInput({ text: item.LYRICIST })
  7511. .height(40)
  7512. .maxLines(1)
  7513. .fontSize(14)
  7514. .layoutWeight(1)
  7515. .fontColor($r('app.color.text_color'))
  7516. .margin({ right: 20, left: 10 })
  7517. .onChange((val: string) => {
  7518. this.lyricistStr = val
  7519. })
  7520. }
  7521. .width('100%')
  7522. .margin({ top: 10, bottom: 10 })
  7523. .justifyContent(FlexAlign.Start)
  7524. Row() {
  7525. Text('注释:')
  7526. .fontSize(14)
  7527. .fontColor($r('app.color.text_color'))
  7528. .margin({ left: 22 })
  7529. TextInput({ text: item.COMMENT })
  7530. .height(40)
  7531. .maxLines(1)
  7532. .fontSize(14)
  7533. .layoutWeight(1)
  7534. .fontColor($r('app.color.text_color'))
  7535. .margin({ right: 20, left: 10 })
  7536. .onChange((val: string) => {
  7537. this.commentStr = val
  7538. })
  7539. }
  7540. .width('100%')
  7541. .margin({ top: 10, bottom: 10 })
  7542. .justifyContent(FlexAlign.Start)
  7543. Row() {
  7544. Button('保存')
  7545. .fontColor(Color.White)
  7546. .layoutWeight(1)
  7547. .height(50)
  7548. .width(100)
  7549. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7550. .backgroundColor(this.themeColor)
  7551. .stateEffect(true)
  7552. .margin({ right: 20, bottom: 20 })
  7553. .onClick(async () => {
  7554. this.doEdit(item)
  7555. })
  7556. Button('取消')
  7557. .fontColor(Color.White)
  7558. .layoutWeight(1)
  7559. .height(50)
  7560. .width(100)
  7561. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7562. .backgroundColor(this.themeColor)
  7563. .stateEffect(true)
  7564. .margin({ left: 20, bottom: 20 })
  7565. .onClick(async () => {
  7566. if(this.isGridMusic){
  7567. this.longItemFilePath =''
  7568. }else{
  7569. this.isShowEdit = false
  7570. }
  7571. this.setEditStrEmpty()
  7572. if(this.isShowPlay){
  7573. this.isShowEdit = false
  7574. }
  7575. })
  7576. }
  7577. .margin({
  7578. left: 38,
  7579. right: 38,
  7580. top: 10,
  7581. bottom: 10
  7582. })
  7583. .width(250)
  7584. .height(60)
  7585. }
  7586. }
  7587. .margin({ bottom: 20 })
  7588. }
  7589. setEditStrEmpty(){
  7590. this.imagePathStr = ''
  7591. this.lyricConStr = ''
  7592. this.artistStr = ''
  7593. this.titleStr = ''
  7594. this.ablumStr = ''
  7595. this.genreStr = ''
  7596. this.yearStr = ''
  7597. this.trackStr = ''
  7598. this.albumArtistStr = ''
  7599. this.composerStr = ''
  7600. this.lyricistStr = ''
  7601. this.commentStr = ''
  7602. this.discStr = ''
  7603. }
  7604. initEditFields(item?: VideoItem) {
  7605. if (!item) {
  7606. this.setEditStrEmpty()
  7607. return
  7608. }
  7609. this.imagePathStr = ''
  7610. this.titleStr = item.name ?? ''
  7611. this.artistStr = item.artist ?? ''
  7612. this.ablumStr = item.album ?? ''
  7613. this.genreStr = item.genre ?? ''
  7614. this.yearStr = item.year ?? ''
  7615. this.trackStr = item.track ?? ''
  7616. this.albumArtistStr = item.ALBUMARTIST ?? ''
  7617. this.composerStr = item.COMPOSER ?? ''
  7618. this.lyricistStr = item.LYRICIST ?? ''
  7619. this.commentStr = item.COMMENT ?? ''
  7620. this.discStr = item.disc ?? ''
  7621. this.lyricConStr = item.lyricContent ?? ''
  7622. }
  7623. private syncEditedFields(target?: VideoItem) {
  7624. if (!target) {
  7625. return
  7626. }
  7627. target.name = this.titleStr
  7628. target.artist = this.artistStr
  7629. target.album = this.ablumStr
  7630. target.lyricContent = this.lyricConStr
  7631. target.year = this.yearStr
  7632. target.genre = this.genreStr
  7633. target.track = this.trackStr
  7634. target.ALBUMARTIST = this.albumArtistStr
  7635. target.COMPOSER = this.composerStr
  7636. target.LYRICIST = this.lyricistStr
  7637. target.COMMENT = this.commentStr
  7638. target.disc = this.discStr
  7639. }
  7640. private replaceItemInList(list: Array<VideoItem> | undefined, filePath: string,
  7641. apply?: (next: Array<VideoItem>) => void) {
  7642. if (!list || ArrayUtil.isEmpty(list)) {
  7643. return
  7644. }
  7645. const index = list.findIndex((video: VideoItem) => video.filePath === filePath)
  7646. if (index < 0) {
  7647. return
  7648. }
  7649. const nextList = [...list]
  7650. this.syncEditedFields(nextList[index])
  7651. apply?.(nextList)
  7652. }
  7653. private syncListsAfterEdit(filePath: string) {
  7654. this.replaceItemInList(this.videoLocalList, filePath, (next: Array<VideoItem>) => {
  7655. this.videoLocalList = next
  7656. this.dataSource.pushArrayData(next)
  7657. })
  7658. this.replaceItemInList(this.songList, filePath, (next: Array<VideoItem>) => {
  7659. this.songList = next
  7660. this.sonDataSource.pushArrayData(next)
  7661. })
  7662. this.replaceItemInList(this.favList, filePath, (next: Array<VideoItem>) => {
  7663. this.favList = next
  7664. })
  7665. this.replaceItemInList(this.historyList, filePath, (next: Array<VideoItem>) => {
  7666. this.historyList = next
  7667. })
  7668. this.replaceItemInList(this.currentSongList, filePath, (next: Array<VideoItem>) => {
  7669. this.currentSongList = next
  7670. })
  7671. this.replaceItemInList(this.mediaKuList, filePath, (next: Array<VideoItem>) => {
  7672. this.mediaKuList = next
  7673. })
  7674. this.replaceItemInList(this.filteredList, filePath, (next: Array<VideoItem>) => {
  7675. this.filteredList = next
  7676. })
  7677. this.replaceItemInList(this.artistList, filePath, (next: Array<VideoItem>) => {
  7678. this.artistList = next
  7679. })
  7680. this.replaceItemInList(this.albumList, filePath, (next: Array<VideoItem>) => {
  7681. this.albumList = next
  7682. })
  7683. this.listRefreshKey++
  7684. }
  7685. private refreshLazyListViews(mainListUpdated: boolean, playlistUpdated: boolean): void {
  7686. if (!mainListUpdated && !playlistUpdated) {
  7687. return;
  7688. }
  7689. this.listRefreshKey++;
  7690. if (mainListUpdated) {
  7691. this.dataSource.notifyDataReload();
  7692. }
  7693. if (playlistUpdated) {
  7694. this.sonDataSource.notifyDataReload();
  7695. }
  7696. }
  7697. @Builder
  7698. detailSheet(item:VideoItem) {
  7699. Scroll() {
  7700. Column() {
  7701. this.songDetail(item)
  7702. }
  7703. }
  7704. .width('100%')
  7705. .height('100%')
  7706. }
  7707. @Builder
  7708. songDetail(currentItem:VideoItem) {
  7709. Column() {
  7710. if (currentItem) {
  7711. Row() {
  7712. Stack() {
  7713. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.alt') :
  7714. currentItem.pixelMapPath)
  7715. .fillColor(this.themeColor)
  7716. .height(80)
  7717. .width(80)
  7718. .borderRadius(10)
  7719. .opacity(this.opacityItem)// 绑定透明度
  7720. .margin({ left: 22 })
  7721. }
  7722. Column() {
  7723. Column() {
  7724. Text(currentItem.name)
  7725. .fontSize(16)
  7726. .maxLines(1)
  7727. .animation({
  7728. duration: 555,
  7729. curve: 'Linear',
  7730. })
  7731. .fontColor($r('app.color.text_color'))
  7732. .margin({ left: 15 })
  7733. }
  7734. .height('100%')
  7735. .width('100%')
  7736. .justifyContent(FlexAlign.Center)
  7737. .alignItems(HorizontalAlign.Start)
  7738. }
  7739. .height('100%')
  7740. }
  7741. .width('100%')
  7742. .height(90)
  7743. .justifyContent(FlexAlign.SpaceBetween)
  7744. Row() {
  7745. Text('艺术家:')
  7746. .fontSize(14)
  7747. .fontColor($r('app.color.text_color'))
  7748. .margin({ left: 22 })
  7749. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  7750. .fontSize(14)
  7751. .fontColor($r('app.color.text_color'))
  7752. .margin({ left: 10 })
  7753. .layoutWeight(1)
  7754. }
  7755. .width('100%')
  7756. .margin({ top: 10, bottom: 10 })
  7757. .justifyContent(FlexAlign.Start)
  7758. Row() {
  7759. Text('专辑名:')
  7760. .fontSize(14)
  7761. .fontColor($r('app.color.text_color'))
  7762. .margin({ left: 22 })
  7763. Text(currentItem?.album ?currentItem.album : '未知专辑')
  7764. .fontSize(14)
  7765. .margin({ left: 10 })
  7766. .fontColor($r('app.color.text_color'))
  7767. .layoutWeight(1)
  7768. }
  7769. .width('100%')
  7770. .margin({ top: 10, bottom: 10 })
  7771. .justifyContent(FlexAlign.Start)
  7772. Row() {
  7773. Text('时长:')
  7774. .fontSize(14)
  7775. .fontColor($r('app.color.text_color'))
  7776. .margin({ left: 22 })
  7777. Text(StrUtil.isEmpty(currentItem.duration)?
  7778. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  7779. .fontSize(14)
  7780. .margin({ left: 10 })
  7781. .fontColor($r('app.color.text_color'))
  7782. .layoutWeight(1)
  7783. }
  7784. .width('100%')
  7785. .margin({ top: 10, bottom: 10 })
  7786. .justifyContent(FlexAlign.Start)
  7787. Row() {
  7788. Text('采样率:')
  7789. .fontSize(14)
  7790. .fontColor($r('app.color.text_color'))
  7791. .margin({ left: 22 })
  7792. Text(Utility.convertToKHz(currentItem.sampleRate))
  7793. .fontSize(14)
  7794. .margin({ left: 10 })
  7795. .fontColor($r('app.color.text_color'))
  7796. .layoutWeight(1)
  7797. }
  7798. .width('100%')
  7799. .margin({ top: 10, bottom: 10 })
  7800. .justifyContent(FlexAlign.Start)
  7801. Row() {
  7802. Text('比特率:')
  7803. .fontSize(14)
  7804. .fontColor($r('app.color.text_color'))
  7805. .margin({ left: 22 })
  7806. Text(currentItem.bit_rate)
  7807. .fontSize(14)
  7808. .margin({ left: 10 })
  7809. .fontColor($r('app.color.text_color'))
  7810. .layoutWeight(1)
  7811. }
  7812. .width('100%')
  7813. .margin({ top: 10, bottom: 10 })
  7814. .justifyContent(FlexAlign.Start)
  7815. Row() {
  7816. Text('位深:')
  7817. .fontSize(14)
  7818. .fontColor($r('app.color.text_color'))
  7819. .margin({ left: 22 })
  7820. Text(`${currentItem.bits_per_raw_sample} bits`)
  7821. .fontSize(14)
  7822. .margin({ left: 10 })
  7823. .fontColor($r('app.color.text_color'))
  7824. .layoutWeight(1)
  7825. }
  7826. .width('100%')
  7827. .margin({ top: 10, bottom: 10 })
  7828. .justifyContent(FlexAlign.Start)
  7829. Row() {
  7830. Text('声道:')
  7831. .fontSize(14)
  7832. .fontColor($r('app.color.text_color'))
  7833. .margin({ left: 22 })
  7834. Text(`${currentItem.channels}`)
  7835. .fontSize(14)
  7836. .margin({ left: 10 })
  7837. .fontColor($r('app.color.text_color'))
  7838. .layoutWeight(1)
  7839. }
  7840. .width('100%')
  7841. .margin({ top: 10, bottom: 10 })
  7842. .justifyContent(FlexAlign.Start)
  7843. Row() {
  7844. Text('声道布局:')
  7845. .fontSize(14)
  7846. .fontColor($r('app.color.text_color'))
  7847. .margin({ left: 22 })
  7848. Text(`${currentItem.channel_layout}`)
  7849. .fontSize(14)
  7850. .margin({ left: 10 })
  7851. .fontColor($r('app.color.text_color'))
  7852. .layoutWeight(1)
  7853. }
  7854. .width('100%')
  7855. .margin({ top: 10, bottom: 10 })
  7856. .justifyContent(FlexAlign.Start)
  7857. Row() {
  7858. Text('起始播放点:')
  7859. .fontSize(14)
  7860. .fontColor($r('app.color.text_color'))
  7861. .margin({ left: 22 })
  7862. Text(`${currentItem.start_time}`)
  7863. .fontSize(14)
  7864. .margin({ left: 10 })
  7865. .fontColor($r('app.color.text_color'))
  7866. .layoutWeight(1)
  7867. }
  7868. .width('100%')
  7869. .margin({ top: 10, bottom: 10 })
  7870. .justifyContent(FlexAlign.Start)
  7871. Row() {
  7872. Text('风格:')
  7873. .fontSize(14)
  7874. .fontColor($r('app.color.text_color'))
  7875. .margin({ left: 22 })
  7876. Text(currentItem.genre)
  7877. .fontSize(14)
  7878. .margin({ left: 10 })
  7879. .fontColor($r('app.color.text_color'))
  7880. .layoutWeight(1)
  7881. }
  7882. .width('100%')
  7883. .margin({ top: 10, bottom: 10 })
  7884. .justifyContent(FlexAlign.Start)
  7885. Row() {
  7886. Text('发行时间:')
  7887. .fontSize(14)
  7888. .fontColor($r('app.color.text_color'))
  7889. .margin({ left: 22 })
  7890. Text(currentItem.year)
  7891. .fontSize(14)
  7892. .margin({ left: 10 })
  7893. .fontColor($r('app.color.text_color'))
  7894. .layoutWeight(1)
  7895. }
  7896. .width('100%')
  7897. .margin({ top: 10, bottom: 10 })
  7898. .justifyContent(FlexAlign.Start)
  7899. Row() {
  7900. Text('质量评分:')
  7901. .fontSize(14)
  7902. .fontColor($r('app.color.text_color'))
  7903. .margin({ left: 22 })
  7904. Text(currentItem.probe_score+"")
  7905. .fontSize(14)
  7906. .margin({ left: 10 })
  7907. .fontColor($r('app.color.text_color'))
  7908. .layoutWeight(1)
  7909. }
  7910. .width('100%')
  7911. .margin({ top: 10, bottom: 10 })
  7912. .justifyContent(FlexAlign.Start)
  7913. Row() {
  7914. Text('音轨号:')
  7915. .fontSize(14)
  7916. .fontColor($r('app.color.text_color'))
  7917. .margin({ left: 22 })
  7918. Text(currentItem.track)
  7919. .fontSize(14)
  7920. .margin({ left: 10 })
  7921. .fontColor($r('app.color.text_color'))
  7922. .layoutWeight(1)
  7923. }
  7924. .width('100%')
  7925. .margin({ top: 10, bottom: 10 })
  7926. .justifyContent(FlexAlign.Start)
  7927. Row() {
  7928. Text('碟号:')
  7929. .fontSize(14)
  7930. .fontColor($r('app.color.text_color'))
  7931. .margin({ left: 22 })
  7932. Text(currentItem.disc)
  7933. .fontSize(14)
  7934. .margin({ left: 10 })
  7935. .fontColor($r('app.color.text_color'))
  7936. .layoutWeight(1)
  7937. }
  7938. .width('100%')
  7939. .margin({ top: 10, bottom: 10 })
  7940. .justifyContent(FlexAlign.Start)
  7941. Row() {
  7942. Text('专辑艺术家:')
  7943. .fontSize(14)
  7944. .fontColor($r('app.color.text_color'))
  7945. .margin({ left: 22 })
  7946. Text(currentItem.ALBUMARTIST)
  7947. .fontSize(14)
  7948. .margin({ left: 10 })
  7949. .fontColor($r('app.color.text_color'))
  7950. .layoutWeight(1)
  7951. }
  7952. .width('100%')
  7953. .margin({ top: 10, bottom: 10 })
  7954. .justifyContent(FlexAlign.Start)
  7955. Row() {
  7956. Text('作曲家:')
  7957. .fontSize(14)
  7958. .fontColor($r('app.color.text_color'))
  7959. .margin({ left: 22 })
  7960. Text(currentItem.COMPOSER)
  7961. .fontSize(14)
  7962. .margin({ left: 10 })
  7963. .fontColor($r('app.color.text_color'))
  7964. .layoutWeight(1)
  7965. }
  7966. .width('100%')
  7967. .margin({ top: 10, bottom: 10 })
  7968. .justifyContent(FlexAlign.Start)
  7969. Row() {
  7970. Text('作词家:')
  7971. .fontSize(14)
  7972. .fontColor($r('app.color.text_color'))
  7973. .margin({ left: 22 })
  7974. Text(currentItem.LYRICIST)
  7975. .fontSize(14)
  7976. .margin({ left: 10 })
  7977. .fontColor($r('app.color.text_color'))
  7978. .layoutWeight(1)
  7979. }
  7980. .width('100%')
  7981. .margin({ top: 10, bottom: 10 })
  7982. .justifyContent(FlexAlign.Start)
  7983. Row() {
  7984. Text('注释:')
  7985. .fontSize(14)
  7986. .fontColor($r('app.color.text_color'))
  7987. .margin({ left: 22 })
  7988. Text(currentItem.COMMENT)
  7989. .fontSize(14)
  7990. .margin({ left: 10 })
  7991. .fontColor($r('app.color.text_color'))
  7992. .layoutWeight(1)
  7993. }
  7994. .width('100%')
  7995. .margin({ top: 10, bottom: 10 })
  7996. .justifyContent(FlexAlign.Start)
  7997. Row() {
  7998. Text('格式:')
  7999. .fontSize(14)
  8000. .fontColor($r('app.color.text_color'))
  8001. .margin({ left: 22 })
  8002. Text(Utility.formatMimeType(currentItem.mimeType))
  8003. .fontSize(14)
  8004. .margin({ left: 10 })
  8005. .fontColor($r('app.color.text_color'))
  8006. .layoutWeight(1)
  8007. }
  8008. .width('100%')
  8009. .margin({ top: 10, bottom: 10 })
  8010. .justifyContent(FlexAlign.Start)
  8011. Row() {
  8012. Text('播放次数:')
  8013. .fontSize(14)
  8014. .fontColor($r('app.color.text_color'))
  8015. .margin({ left: 22 })
  8016. Text(currentItem.playCount?.toString())
  8017. .fontSize(14)
  8018. .margin({ left: 10 })
  8019. .fontColor($r('app.color.text_color'))
  8020. .layoutWeight(1)
  8021. }
  8022. .width('100%')
  8023. .margin({ top: 10, bottom: 10 })
  8024. .justifyContent(FlexAlign.Start)
  8025. Row() {
  8026. Text('流数量:')
  8027. .fontSize(14)
  8028. .fontColor($r('app.color.text_color'))
  8029. .margin({ left: 22 })
  8030. Text(currentItem.nb_streams?.toString())
  8031. .fontSize(14)
  8032. .margin({ left: 10 })
  8033. .fontColor($r('app.color.text_color'))
  8034. .layoutWeight(1)
  8035. }
  8036. .width('100%')
  8037. .margin({ top: 10, bottom: 10 })
  8038. .justifyContent(FlexAlign.Start)
  8039. Row() {
  8040. Text('文件大小:')
  8041. .fontSize(14)
  8042. .fontColor($r('app.color.text_color'))
  8043. .margin({ left: 22 })
  8044. Text(currentItem.size)
  8045. .fontSize(14)
  8046. .margin({ left: 10 })
  8047. .fontColor($r('app.color.text_color'))
  8048. .layoutWeight(1)
  8049. }
  8050. .width('100%')
  8051. .margin({ top: 10, bottom: 10 })
  8052. .justifyContent(FlexAlign.Start)
  8053. Row() {
  8054. Text('文件名:')
  8055. .fontSize(14)
  8056. .fontColor($r('app.color.text_color'))
  8057. .margin({ left: 22 })
  8058. Text(currentItem.fileName)
  8059. .fontSize(14)
  8060. .margin({ left: 10 })
  8061. .fontColor($r('app.color.text_color'))
  8062. .layoutWeight(1)
  8063. }
  8064. .width('100%')
  8065. .margin({ top: 10, bottom: 10 })
  8066. .justifyContent(FlexAlign.Start)
  8067. Row() {
  8068. Text('修改时间:')
  8069. .fontSize(14)
  8070. .fontColor($r('app.color.text_color'))
  8071. .margin({ left: 22 })
  8072. Text(currentItem.cTime)
  8073. .fontSize(14)
  8074. .margin({ left: 10 })
  8075. .fontColor($r('app.color.text_color'))
  8076. .layoutWeight(1)
  8077. }
  8078. .width('100%')
  8079. .margin({ top: 10, bottom: 10 })
  8080. .justifyContent(FlexAlign.Start)
  8081. Row() {
  8082. Text('存放目录:')
  8083. .fontSize(14)
  8084. .fontColor($r('app.color.text_color'))
  8085. .margin({ left: 22 })
  8086. Text(currentItem.filePath)
  8087. .fontSize(12)
  8088. .margin({ left: 10 })
  8089. .fontColor($r('app.color.text_color'))
  8090. .layoutWeight(1)
  8091. }
  8092. .margin({ top: 10, bottom: 10 })
  8093. .width('100%')
  8094. .justifyContent(FlexAlign.Start)
  8095. Row() {
  8096. Text('内嵌歌词:')
  8097. .fontSize(14)
  8098. .fontColor($r('app.color.text_color'))
  8099. .margin({ left: 22 })
  8100. Text(currentItem.lyricContent)
  8101. .fontSize(12)
  8102. .copyOption(CopyOptions.InApp)
  8103. .margin({ left: 10 })
  8104. .fontColor($r('app.color.text_color'))
  8105. .layoutWeight(1)
  8106. }
  8107. .margin({ top: 10, bottom: 10 })
  8108. .width('100%')
  8109. .justifyContent(FlexAlign.Start)
  8110. }
  8111. }
  8112. .margin({ bottom: 20 })
  8113. }
  8114. //定时关闭布局
  8115. @Builder
  8116. TimeCloseSheet() {
  8117. Scroll() {
  8118. Column() {
  8119. this.TimeClose()
  8120. }
  8121. }
  8122. .width('100%')
  8123. .height('100%')
  8124. }
  8125. //倒计时关闭音乐,退出App功能实现。
  8126. @State selectedMinutes: number = 0 // 0表示未开启
  8127. @State remainingSeconds: number = 0
  8128. // 预设时间选项
  8129. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  8130. private formatTime(seconds: number): string {
  8131. const mins = Math.floor(seconds / 60)
  8132. const secs = seconds % 60
  8133. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  8134. }
  8135. // 开始倒计时
  8136. private handleTimeSelect(minutes: number) {
  8137. if (minutes === this.selectedMinutes) {
  8138. this.stopCountdown();
  8139. this.selectedMinutes = 0;
  8140. return;
  8141. }
  8142. this.selectedMinutes = minutes;
  8143. this.remainingSeconds = minutes * 60;
  8144. this.startCountdown(); // 新增调用
  8145. }
  8146. @Builder
  8147. TimeClose() {
  8148. Column() {
  8149. // 倒计时显示区域
  8150. Text(this.selectedMinutes > 0 ?
  8151. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  8152. "定时关闭未开启")
  8153. .fontSize(17)
  8154. .fontColor($r('app.color.text_color'))
  8155. .margin({ top: 2, bottom: 8 });
  8156. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  8157. ForEach(this.presetTimes, (minutes: number, index: number) => {
  8158. // 单行时间选项容器
  8159. Row() {
  8160. // 文字描述区域
  8161. Text(this.getDisplayText(minutes))
  8162. .fontSize(15)
  8163. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  8164. $r('app.color.text_color'))// 选中态颜色变化
  8165. .textAlign(TextAlign.Start)
  8166. .layoutWeight(1); // 占据剩余空间
  8167. // 复选框样式的选择器
  8168. Row() {
  8169. if (minutes === this.selectedMinutes) {
  8170. // 选中状态 - 带勾号的圆形复选框
  8171. Row() {
  8172. // 使用系统内置的勾号图标
  8173. Image($r('sys.media.ohos_ic_public_ok'))
  8174. .width(14)
  8175. .height(14)
  8176. .fillColor(Color.White)
  8177. }
  8178. .width(24)
  8179. .height(24)
  8180. .borderRadius(12)
  8181. .backgroundColor(this.themeColor)
  8182. .justifyContent(FlexAlign.Center)
  8183. .alignItems(VerticalAlign.Center)
  8184. } else {
  8185. // 未选中状态的圆形边框
  8186. Row()
  8187. .width(24)
  8188. .height(24)
  8189. .borderRadius(12)
  8190. .border({
  8191. width: 2,
  8192. color: $r('app.color.text_color'),
  8193. style: BorderStyle.Solid
  8194. })
  8195. .backgroundColor(Color.Transparent)
  8196. }
  8197. }
  8198. .width(24)
  8199. .height(24)
  8200. .margin({ left: 20 })
  8201. .justifyContent(FlexAlign.Center)
  8202. .alignItems(VerticalAlign.Center)
  8203. }
  8204. .width('100%')
  8205. .padding({
  8206. top: 18,
  8207. bottom: 18,
  8208. left: 18,
  8209. right: 18
  8210. })
  8211. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  8212. $r('app.color.bottom_control_background')) // 选中背景高亮
  8213. .borderRadius(12)
  8214. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8215. .margin({ bottom: 18 })
  8216. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  8217. });
  8218. }
  8219. .width('100%')
  8220. .padding(16)
  8221. }
  8222. }
  8223. // 获取显示文本
  8224. private getDisplayText(minutes: number): string {
  8225. if (minutes === -1) {
  8226. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  8227. }
  8228. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  8229. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  8230. }
  8231. // 处理选择事件
  8232. private handleSelect(minutes: number): void {
  8233. if (minutes === -1) { // 自定义
  8234. // 弹出自定义时间对话框
  8235. DialogHelper.showTextInputDialog({
  8236. title: '自定义时间',
  8237. maskColor: Color.Transparent,
  8238. inputType: InputType.Number,
  8239. text: '',
  8240. onChange: (text) => {
  8241. console.error("onChange: " + text);
  8242. },
  8243. onAction: (action, dialogId, content) => {
  8244. if (action == DialogAction.TWO) {
  8245. const customMinutes = Number(content);
  8246. if (customMinutes > 0) {
  8247. this.handleTimeSelect(customMinutes); // 设置自定义时间
  8248. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  8249. }
  8250. }
  8251. }
  8252. });
  8253. } else {
  8254. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  8255. }
  8256. }
  8257. // 添加定时器引用
  8258. private timerId: number = -1;
  8259. // 启动/重置倒计时
  8260. private startCountdown() {
  8261. // 清除旧定时器
  8262. if (this.timerId !== -1) {
  8263. clearInterval(this.timerId);
  8264. }
  8265. // 创建新定时器
  8266. if (this.selectedMinutes > 0) {
  8267. this.timerId = setInterval(() => {
  8268. if (this.remainingSeconds === 15) {
  8269. this.showConfirmationDialog();
  8270. }
  8271. if (this.remainingSeconds > 0) {
  8272. this.remainingSeconds -= 1;
  8273. } else {
  8274. this.stopCountdown();
  8275. this.handleTimeout();
  8276. }
  8277. }, 1000);
  8278. }
  8279. }
  8280. // 15倒计时后再次提示显示确认是否关闭App对话框
  8281. private showConfirmationDialog() {
  8282. DialogHelper.showAlertDialog({
  8283. backgroundColor: $r('app.color.btn_green'),
  8284. title: '确认关闭',
  8285. maskColor: Color.Transparent,
  8286. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  8287. borderStyle: BorderStyle.Dashed,
  8288. primaryButton: '暂不关闭',
  8289. secondaryButton: '确定',
  8290. onAction: (action) => {
  8291. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  8292. this.stopCountdown();
  8293. this.selectedMinutes = 0
  8294. } else if (action == DialogAction.TWO) {
  8295. }
  8296. }
  8297. })
  8298. }
  8299. // 停止倒计时
  8300. private stopCountdown() {
  8301. if (this.timerId !== -1) {
  8302. clearInterval(this.timerId);
  8303. this.timerId = -1;
  8304. }
  8305. }
  8306. // 超时处理
  8307. private handleTimeout() {
  8308. // 执行播放器关闭逻辑
  8309. this.selectedMinutes = 0;
  8310. ToastUtil.showToast(" 定时关闭已完成");
  8311. this.stop(); // 假设存在的播放器实例
  8312. //退出APP
  8313. const mContext = getContext(this) as common.UIAbilityContext
  8314. mContext.terminateSelf();
  8315. AvSessionController.getInstance(true).unregisterSessionListener()
  8316. }
  8317. //倒计时关闭音乐,退出App功能实现结束。
  8318. //播放列表的拖动List 重新排序
  8319. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  8320. //左滑操作 移动文件 重命名 删除等操作
  8321. @Builder
  8322. sonButton(item: VideoItem, index: number, filePath: string) {
  8323. Row() {
  8324. //加入下一首播放
  8325. Button() {
  8326. Image($r('app.media.next_to_play'))
  8327. .fillColor(Color.White)
  8328. .width(20)
  8329. }
  8330. .width(40)
  8331. .height(40)
  8332. .type(ButtonType.Circle)
  8333. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  8334. .backgroundColor(this.themeColor)
  8335. .margin(5)
  8336. .onClick(() => {
  8337. this.addToNextPlay(item);
  8338. })
  8339. Button() {
  8340. Image($r('app.media.close'))
  8341. .fillColor(Color.White)
  8342. .width(20)
  8343. }
  8344. .width(40)
  8345. .height(40)
  8346. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  8347. .type(ButtonType.Circle)
  8348. .backgroundColor(this.themeColor)
  8349. .margin(5)
  8350. .onClick(() => {
  8351. this.songList.splice(Number(index), 1)
  8352. this.sonDataSource.pushArrayData(this.songList)
  8353. })
  8354. Button() {
  8355. Image($r('app.media.share2'))
  8356. .fillColor(Color.White)
  8357. .width(20)
  8358. }
  8359. .width(40)
  8360. .height(40)
  8361. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  8362. .type(ButtonType.Circle)
  8363. .backgroundColor(this.themeColor)
  8364. .margin(5)
  8365. .onClick(() => {
  8366. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  8367. })
  8368. }
  8369. }
  8370. itemMoveSon(index: number, newIndex: number): void {
  8371. if (newIndex < 0 || newIndex >= this.songList.length) {
  8372. return;
  8373. }
  8374. let tmp = this.songList.splice(index, 1);
  8375. this.songList.splice(newIndex, 0, tmp[0]);
  8376. this.sonDataSource.pushArrayData(this.songList)
  8377. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  8378. if(this.modeType==4&&this.playlistTable){
  8379. updateAllSongsSortOrder(this.playlistTable, this.songList,this.currentSongListID)
  8380. }
  8381. }
  8382. @Builder
  8383. PlayList() {
  8384. List({ scroller: this.playListScroller }) {
  8385. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  8386. ListItem() {
  8387. this.MusicItemSon(item, index)
  8388. }
  8389. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  8390. .animation({
  8391. duration: 666,
  8392. curve: 'ease-in-out' // 可选动画曲线
  8393. })
  8394. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 600 }),
  8395. TransitionEffect.scale({ x: 0, y: 0 })))
  8396. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  8397. //拖动List关键代码开始
  8398. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  8399. .zIndex(this.dragItem === index ? 1 : 0)
  8400. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  8401. .gesture(
  8402. GestureGroup(GestureMode.Sequence,
  8403. LongPressGesture({ repeat: true })
  8404. .onAction((event?: GestureEvent) => {
  8405. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  8406. this.scaleItem = index
  8407. })
  8408. })
  8409. .onActionEnd(() => {
  8410. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  8411. this.scaleItem = -1
  8412. })
  8413. }),
  8414. PanGesture({ fingers: 1, direction: null, distance: 0 })
  8415. .onActionStart(() => {
  8416. this.dragItem = index // 记录当前拖动项索引
  8417. this.dragRefOffset = 0 // 重置偏移基准
  8418. })
  8419. .onActionUpdate((event: GestureEvent) => {
  8420. this.offsetY = event.offsetY - this.dragRefOffset;
  8421. this.neighborItem = -1;
  8422. let indexA = this.songList.indexOf(item);
  8423. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  8424. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  8425. let value: number = 0;
  8426. if (this.offsetY < 0) {
  8427. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  8428. this.neighborItem = indexA - 1;
  8429. this.neighborScale = 1 - value / 20;
  8430. } else if (this.offsetY > 0) {
  8431. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  8432. this.neighborItem = indexA + 1;
  8433. this.neighborScale = 1 - value / 20;
  8434. }
  8435. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  8436. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8437. this.offsetY -= this.ITEM_INTV;
  8438. this.dragRefOffset += this.ITEM_INTV;
  8439. this.itemMoveSon(indexA, indexA + 1);
  8440. });
  8441. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  8442. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8443. this.offsetY += this.ITEM_INTV;
  8444. this.dragRefOffset -= this.ITEM_INTV;
  8445. this.itemMoveSon(indexA, indexA - 1);
  8446. });
  8447. }
  8448. })
  8449. .onActionEnd((event: GestureEvent) => {
  8450. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8451. this.dragItem = -1
  8452. this.neighborItem = -1
  8453. })
  8454. animateTo({
  8455. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  8456. }, () => {
  8457. this.scaleItem = -1
  8458. })
  8459. })
  8460. )
  8461. .onCancel(() => {
  8462. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8463. this.dragItem = -1
  8464. this.neighborItem = -1
  8465. })
  8466. animateTo({
  8467. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  8468. }, () => {
  8469. this.scaleItem = -1
  8470. })
  8471. })
  8472. ) //拖动List关键代码结束
  8473. .onClick(() => {
  8474. this.doPlay(item, index, true)
  8475. })
  8476. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  8477. }
  8478. .width('100%')
  8479. .height('100%')
  8480. .onReachEnd(() => {
  8481. if(this.modeType === 4 )
  8482. return;
  8483. void this.tryLoadNextPageForPlayback();
  8484. })
  8485. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  8486. // .animation({ duration: 500, curve: Curve.Ease }))
  8487. .cachedCount(10)
  8488. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  8489. .gesture(PinchGesture({ fingers: 2 })
  8490. .onActionEnd((event: GestureEvent) => {
  8491. this.setSonListTwoFingers()
  8492. })
  8493. .onActionUpdate(e => {
  8494. this.scaleValue = this.pinchValue * e.scale
  8495. })
  8496. .onActionStart(e => {
  8497. }))
  8498. .padding({
  8499. bottom: 0
  8500. })
  8501. }
  8502. setSonListTwoFingers() {
  8503. this.pinchValue = this.scaleValue;
  8504. Logger.info('this.pinchValue = ' + this.pinchValue);
  8505. if (this.pinchValue >= 1) {
  8506. this.sonTwoFingerType++
  8507. Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
  8508. if (this.sonTwoFingerType > 3) {
  8509. this.sonTwoFingerType = 1
  8510. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  8511. }
  8512. } else {
  8513. this.sonTwoFingerType--
  8514. Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
  8515. if (this.sonTwoFingerType < 1) {
  8516. this.sonTwoFingerType = 1
  8517. }
  8518. }
  8519. PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
  8520. this.pinchValue = 1;
  8521. this.scaleValue = 1;
  8522. }
  8523. @State sonTwoFingerType:number = 3
  8524. @Builder
  8525. private MusicItemSon(item: VideoItem, index?: number) {
  8526. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8527. Row() {
  8528. Stack() {
  8529. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  8530. .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  8531. .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  8532. .alt($r('app.media.alt'))
  8533. .fillColor(this.themeColor)
  8534. .borderRadius(this.isCoverRectangle?11:'100%')
  8535. .clip(true)
  8536. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  8537. .draggable(false)// 禁止长按手势拖动
  8538. .autoResize(true) // 重采样,可减少内存占用
  8539. .margin({ left: 20 })
  8540. }
  8541. .width('15%')
  8542. Column() {
  8543. Column() {
  8544. Text(this.isShowFileName?item.fileName :item.name)
  8545. .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
  8546. .fontColor(this.curIndex === index ? this.themeColor :
  8547. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  8548. .maxLines(1)
  8549. .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
  8550. Row() {
  8551. Column(){
  8552. Text(item.md5Str?.includes('Lossless')?
  8553. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  8554. .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
  8555. .padding({ top: 3,right:6,left:6,bottom:3 })
  8556. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  8557. $r('app.color.text_color'))
  8558. .fontWeight(500)
  8559. .borderRadius(12)
  8560. .visibility(StrUtil.isEmpty(item.md5Str) ? Visibility.None : Visibility.Visible)
  8561. .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
  8562. .backgroundColor('#FFC107')
  8563. }
  8564. .padding({ top: 8 })
  8565. Text(StrUtil.isEmpty(item.artist) ? item.duration :
  8566. item.artist + ' ' + item?.duration)
  8567. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  8568. .padding({ top: 8 })
  8569. .maxLines(1)
  8570. .fontColor(this.curIndex === index ? this.themeColor :
  8571. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  8572. .margin({ left: StrUtil.isEmpty(item.md5Str)? 12 :this.sonTwoFingerType == 3 ? 5 : 3 })
  8573. Blank()
  8574. Text(item.size)
  8575. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  8576. .padding({ top: 8 })
  8577. .maxLines(1)
  8578. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  8579. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  8580. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  8581. .margin({ left: 10 })
  8582. }
  8583. }
  8584. .height('100%')
  8585. .width('100%')
  8586. .justifyContent(FlexAlign.Center)
  8587. .alignItems(HorizontalAlign.Start)
  8588. }
  8589. .height('100%')
  8590. .width('65%')
  8591. Column() {
  8592. ImageAnimator()
  8593. .images(this.imagesF)// 动画数组
  8594. .duration(1000)// 持续
  8595. .state(this.animationState)// 动画状态
  8596. .fillMode(FillMode.Forwards)
  8597. .width(18)
  8598. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  8599. Visibility.None)
  8600. .height(18)
  8601. .iterations(-1) // 播放次数
  8602. }
  8603. .width('20%')
  8604. }
  8605. }
  8606. .backgroundColor(Color.Transparent)
  8607. .width('100%')
  8608. .reuseId('son_item')
  8609. .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
  8610. .shadow(this.scaleItem === index ? {
  8611. radius: 70,
  8612. color: '#15000000',
  8613. offsetX: 0,
  8614. offsetY: 0
  8615. } :
  8616. {
  8617. radius: 0,
  8618. color: '#15000000',
  8619. offsetX: 0,
  8620. offsetY: 0
  8621. })
  8622. .animation({ curve: Curve.Sharp, duration: 300 })
  8623. }
  8624. @Builder
  8625. MusicPlayBuilder() {
  8626. Column() {
  8627. this.IjkMusicPlayerView()
  8628. }
  8629. .transition(TransitionEffect.asymmetric(
  8630. TransitionEffect.opacity(1),
  8631. TransitionEffect.OPACITY
  8632. ))
  8633. .visualEffect(deviceInfo.sdkApiVersion>=20&&this.bgController?
  8634. new hdsEffect.HdsEffectBuilder()
  8635. .shaderEffect({
  8636. effectType: hdsEffect.EffectType.UV_BACKGROUND_FLOW_LIGHT,
  8637. animation: {
  8638. duration: 10000,
  8639. iterations: -1,
  8640. autoPlay: true,
  8641. onFinish: ()=> {
  8642. console.info('Succeeded in finishing');
  8643. }
  8644. },
  8645. controller: this.bgController,
  8646. })
  8647. .buildEffect():null)
  8648. .height('100%')
  8649. .width('100%')
  8650. .onDisAppear(() => {
  8651. this.translateY = 0;
  8652. })
  8653. .translate({ y: this.translateY })
  8654. .gesture(
  8655. PanGesture(this.panOption)
  8656. .onActionUpdate((event?: GestureEvent) => {
  8657. if (event) {
  8658. // 只允许向下滑动,向上滑动时限制为0
  8659. this.translateY = Math.max(0, event.offsetY);
  8660. this.getUIContext().animateTo({
  8661. duration: 500,
  8662. curve: Curve.Sharp
  8663. }, () => {
  8664. this.scaleValueImage = Math.min(1, Math.max(0.38, 1 - event.offsetY / 500));
  8665. console.info('onecold scaleValueImage:', this.scaleValueImage)
  8666. this.scaleValueText =Math.min(1, Math.max(0.6, 1 - event.offsetY / 700));
  8667. })
  8668. }
  8669. })
  8670. .onActionEnd((event?: GestureEvent) => {
  8671. // 使用更低的阈值和滑动速度判断
  8672. const minDistance = 300; // 最小滑动距离 100vp
  8673. const minVelocity = 500; // 最小滑动速度
  8674. // 获取滑动速度(如果可用)
  8675. const velocity = event?.velocityY || 0;
  8676. // 判断是否应该关闭:距离足够 或者 速度足够快
  8677. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  8678. if (shouldClose) {
  8679. // 添加关闭动画
  8680. this.getUIContext().animateTo({
  8681. duration: 600,
  8682. curve: Curve.Friction
  8683. }, () => {
  8684. this.isShowPlay = false;
  8685. this.scaleValueImage = 1
  8686. this.scaleValueText = 1
  8687. this.translateY = 0;
  8688. })
  8689. } else {
  8690. // 回弹动画
  8691. this.getUIContext().animateTo({
  8692. duration: 600,
  8693. curve: Curve.Friction
  8694. }, () => {
  8695. this.scaleValueImage = 1
  8696. this.scaleValueText = 1
  8697. this.translateY = 0;
  8698. })
  8699. }
  8700. })
  8701. )
  8702. }
  8703. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  8704. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  8705. HeightBreakpoint.HEIGHT_LG;
  8706. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  8707. @State topBarHeight: number = 50
  8708. @State barOpacity: number = 1
  8709. @State barBottomOpacity: number = 1
  8710. private hideDone: boolean = false;
  8711. @State currentYOffset: number = 0;
  8712. @State bottomBarHeight: number = 68;
  8713. private isHiding: boolean = false;
  8714. //是否是Pura X外屏,或者小屏幕
  8715. isPuraWP() {
  8716. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  8717. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  8718. }
  8719. //是否是Pura X外屏,或者小屏幕,手机横屏
  8720. /**
  8721. * 是否是Pura X外屏,或者小屏幕,手机横屏
  8722. * @returns
  8723. */
  8724. isCoverOpacity() {
  8725. if (this.isPuraWP()) {
  8726. return true
  8727. }
  8728. if (this.isPhoneLan()) {
  8729. return true
  8730. }
  8731. if (deviceInfo.marketName.includes('Pura X')
  8732. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  8733. return true
  8734. }
  8735. return false
  8736. }
  8737. //是不是手机横屏
  8738. isPhoneLan() {
  8739. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  8740. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  8741. logHiCarWindow(`isPhoneLan width=${this.windowWidth}`);
  8742. logHiCarWindow(`isPhoneLan height=${this.windowHeight}`);
  8743. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarStatus=${this.isHiCarStatus}`);
  8744. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, curDisplayIsHiCar=${this.curDisplayIsHiCar}`);
  8745. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall=${this.isHiCarSmall()}`);
  8746. if (this.isHiCarKuanBianPing()) {
  8747. return true
  8748. }
  8749. if (this.isHiCar()) {
  8750. return false
  8751. }
  8752. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8753. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  8754. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  8755. return true
  8756. }
  8757. return false
  8758. }
  8759. //是不是1920x720的hicar的屏幕分辨率
  8760. isHiCarKuanBianPing(){
  8761. // if(!this.isHiCar()){
  8762. // return false
  8763. // }
  8764. const hiCarAspectRatios: HiCarAspectRatio[] = [
  8765. { ratio: 1920 / 720, name: "1920x720" },
  8766. ];
  8767. const currentRatio: number = this.windowWidth / this.windowHeight;
  8768. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  8769. logHiCarWindow(`HiCarKuanBianPing currentRatio=${currentRatio}`)
  8770. for (const hiCarRatio of hiCarAspectRatios) {
  8771. logHiCarWindow(`HiCarKuanBianPing hiCarRatio=${hiCarRatio.ratio}`)
  8772. logHiCarWindow(`HiCarKuanBianPing diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  8773. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  8774. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  8775. //宽扁平的尺寸设置列表展示
  8776. this.twoFingerType ==3
  8777. this.isGridMusic = false
  8778. return true;
  8779. }
  8780. }
  8781. return false;
  8782. }
  8783. //是不是hicar的屏幕分辨率
  8784. isHiCarSmall() {
  8785. if(!this.isHiCar()){
  8786. return false
  8787. }
  8788. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  8789. {
  8790. this.columns = 6
  8791. return false
  8792. }
  8793. const hiCarAspectRatios: HiCarAspectRatio[] = [
  8794. { ratio: 800 / 480, name: "800x480" },
  8795. { ratio: 1280 / 720, name: "1280x720" },
  8796. { ratio: 1920 / 1080, name: "1920x1080" },
  8797. ];
  8798. const currentRatio: number = this.windowWidth / this.windowHeight;
  8799. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  8800. logHiCarWindow(`HiCarSmall currentRatio=${currentRatio}`)
  8801. for (const hiCarRatio of hiCarAspectRatios) {
  8802. logHiCarWindow(`HiCarSmall hiCarRatio=${hiCarRatio.ratio}`)
  8803. logHiCarWindow(`HiCarSmall diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  8804. logHiCarWindow(`HiCarSmall isHiCarStatus=${this.isHiCarStatus}`);
  8805. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  8806. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  8807. //宽扁平的尺寸设置列表展示
  8808. return true;
  8809. }
  8810. }
  8811. return false;
  8812. }
  8813. isHiCar() {
  8814. return this.curDisplayIsHiCar;
  8815. }
  8816. //是不是正常的手机竖屏
  8817. isPhonePortrait() {
  8818. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  8819. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  8820. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  8821. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8822. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  8823. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  8824. return true
  8825. }
  8826. return false
  8827. }
  8828. @State showSpeedDialog: boolean = false
  8829. @State longPressSpeed: number = 3 //长按默认倍数
  8830. @Builder
  8831. SpeedDialog() {
  8832. Stack() {
  8833. Column() {
  8834. Text('已切换至' + this.longPressSpeed + '倍速播放')
  8835. .fontColor(Color.White)
  8836. .visibility(Visibility.Hidden)
  8837. }
  8838. .backgroundColor(Color.Black)
  8839. .borderRadius(20)
  8840. .padding({
  8841. top: 10,
  8842. right: 20,
  8843. left: 15,
  8844. bottom: 20
  8845. })
  8846. .opacity(0.6)
  8847. Text('已切换至' + this.longPressSpeed + '倍速播放')
  8848. .fontColor(Color.White)
  8849. }
  8850. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  8851. .zIndex(5)
  8852. .margin({ top: 80 })
  8853. }
  8854. @Builder
  8855. IjkMusicPlayerView() {
  8856. Stack() {
  8857. if(canIUse("SystemCapability.UIDesign.HDSComponent.Core")
  8858. &&deviceInfo.sdkApiVersion>=20&&this.sceneBgController){
  8859. HdsVisualComponent()
  8860. .scene(HdsSceneType.DUAL_EDGE_FLOW_LIGHT_WITH_BACKGROUND_MASK, this.sceneBgController, () => {
  8861. console.info('Succeeded in finishing');
  8862. })
  8863. .width('100%')
  8864. .height('100%')
  8865. .visibility(this.isShowBgLiuGUANG?Visibility.Visible:Visibility.None)
  8866. }
  8867. Column() {
  8868. Column() {
  8869. //播放标题
  8870. Column() {
  8871. this.PlayTitle()
  8872. }
  8873. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  8874. .width('100%')
  8875. .margin({ top: 0 })
  8876. .height(PlayConstants.HEIGHT)
  8877. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  8878. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  8879. if (this.showSpeedDialog) {
  8880. this.SpeedDialog()
  8881. }
  8882. Stack() {
  8883. //手势拖动快进
  8884. Column()
  8885. .width(CommonConstants.FULL_PERCENT)
  8886. .height('100%')
  8887. .gesture(
  8888. GestureGroup(GestureMode.Parallel,
  8889. // 长按屏幕倍数播放
  8890. LongPressGesture({ repeat: true })
  8891. .onAction(() => {
  8892. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8893. this.showSpeedDialog = true;
  8894. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  8895. }
  8896. })
  8897. .onActionEnd(() => {
  8898. this.showSpeedDialog = false;
  8899. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  8900. }),
  8901. //双击屏幕暂停或者播放
  8902. TapGesture({ count: 2 })
  8903. .onAction((event: GestureEvent) => {
  8904. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8905. ToastUtil.showToast('已暂停')
  8906. }
  8907. console.info('onecold playOrPause 6693')
  8908. this.playOrPause()
  8909. })
  8910. )
  8911. )
  8912. }
  8913. .height('65%')
  8914. Swiper() {
  8915. this.CoverInfo()
  8916. this.PlayerLyrics()
  8917. }
  8918. .onChange((index: number) => {
  8919. this.currentSwiperIndex = index
  8920. })
  8921. .indicator(false)
  8922. .displayCount(new BreakpointType({
  8923. sm: 1,
  8924. md: 2,
  8925. lg: 2,
  8926. xl: 2,
  8927. xxl: 2
  8928. }).getValue(this.currentBreakpoint))
  8929. .clip(false)
  8930. .loop(false)
  8931. .autoPlay(false)
  8932. // .interval(8000)
  8933. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  8934. .height('100%')
  8935. .hitTestBehavior(HitTestMode.Transparent)
  8936. Image($r('app.media.icon_replay'))
  8937. .objectFit(ImageFit.Auto)
  8938. .width('120px')
  8939. .height('120px')
  8940. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  8941. .border({ width: 0 })
  8942. .visibility(Visibility.None)
  8943. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  8944. .onClick(() => {
  8945. console.info('onecold startPlayOrResumePlay 6744')
  8946. this.startPlayOrResumePlay();
  8947. })
  8948. }
  8949. .width(CommonConstants.FULL_PERCENT)
  8950. .height(CommonConstants.FULL_PERCENT)
  8951. .justifyContent(FlexAlign.End)
  8952. }
  8953. .justifyContent(FlexAlign.End)
  8954. .margin({ bottom: 8 })
  8955. }
  8956. .backgroundImage(!this.isMusicBGCover||StrUtil.isEmpty(this.cover)?null: this.cover)
  8957. .backgroundImageSize(this.isPuraWP()||!this.isMusicBGCover ? { width: '100%' } : { height: '150%', width: '100%' })
  8958. .animation({
  8959. duration: 666,
  8960. curve: 'ease-in-out' // 可选动画曲线
  8961. })
  8962. .backgroundBlurStyle((this.isPuraWP() && this.currentSwiperIndex === 0) ||!this.isMusicBGCover
  8963. ? BlurStyle.NONE :
  8964. BlurStyle.BACKGROUND_ULTRA_THICK)
  8965. .hitTestBehavior(HitTestMode.Transparent)
  8966. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  8967. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  8968. .onClick(() => {
  8969. if(this.isHiCar())
  8970. return
  8971. if(this.is_auto_hide_progress){
  8972. this.is_auto_hide_progress = false
  8973. }
  8974. this.startAutoHide()
  8975. })
  8976. }
  8977. @Consume progressValue: number ;
  8978. @State currentTime: string = "00:00";
  8979. @State totalTime: string = "00:00";
  8980. @State loadingVisible: Visibility = Visibility.None;
  8981. @State replayVisible: Visibility = Visibility.None;
  8982. @State slideEnable: boolean = false;
  8983. @State aspRatio: number = 0.5;
  8984. @State mContext: object | undefined = undefined;
  8985. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  8986. @State mFirst: boolean = true;
  8987. @State mDestroyPage: boolean = false;
  8988. @State playSpeed: number = 1;
  8989. @State oldSeconds: number = 0;
  8990. @State isSeekTo: boolean = false;
  8991. @State isCurrentTime: boolean = false;
  8992. @State videoWidth: string = '100%';
  8993. @State videoHeight: string = '100%';
  8994. @State initAspectRatio: number = 1;
  8995. @State videoAspectRatio: number = this.initAspectRatio;
  8996. @State videoUrl: string = '';
  8997. private last: number = 0;
  8998. @State videoParentAspectRatio: number = this.initAspectRatio;
  8999. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  9000. @Consume CONTROL_PlayStatus: number ;
  9001. @State PROGRESS_MAX_VALUE: number = 100;
  9002. @State updateProgressTimer: number = 0;
  9003. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  9004. @State name: string = '';
  9005. // @State loop: boolean = false;
  9006. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  9007. @State multiple: string = '1.0X';
  9008. xcomponentController: XComponentController = new XComponentController()
  9009. private panOptionBright: PanGestureOptions =
  9010. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  9011. private panOptionVolume: PanGestureOptions =
  9012. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  9013. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  9014. //手势的音量控制和亮度控制
  9015. private positionX: number = PlayConstants.POSITION_X;
  9016. private positionY: number = PlayConstants.POSITION_Y;
  9017. private windowClass: window.Window = globalThis.windowClass
  9018. @State volume: number = 0.5;
  9019. @State volumeSmall: boolean = false
  9020. @State autoParseMusicName: boolean = true
  9021. @State isShowFileName: boolean = false
  9022. @State isLongNameRoLL: boolean = true//长歌名滚动
  9023. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  9024. @State bright: number = PlayConstants.BRIGHT;
  9025. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  9026. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  9027. @State screenWidth: number = 0
  9028. @State screenHeight: number = 0
  9029. @State statusBarHeight: number = 0
  9030. @State isYesFull: boolean = false
  9031. private seekValue: number = 0
  9032. @State isVideoLock: boolean = false; // Whether the video playback is locked
  9033. private preloadNextRandomIndex: number = -1; // 预缓存的随机下一首索引
  9034. eventHub = getContext().eventHub;
  9035. //投播组件
  9036. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  9037. // 新的投播控制器(封装了官方示例的逻辑)
  9038. private castControllerWrapper: CastController | undefined = undefined;
  9039. // 保留原始的 avCastController 引用(用于兼容旧代码)
  9040. private castController: avSession.AVCastController | undefined = undefined;
  9041. @State isCastPlaying: boolean = false;
  9042. @State currentTime2: number = 0;
  9043. @State currentStringTime: string = '00:00';
  9044. @State duration: number = 0;
  9045. @State isReady: boolean = false;
  9046. @State durationTime: number = 0;
  9047. @State durationStringTime: string = '00:00';
  9048. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  9049. // @State isPlaying: boolean = false;
  9050. private castSeek: boolean = false;
  9051. private castItem: avSession.AVQueueItem | undefined = undefined;
  9052. private castFile: fs.File | undefined = undefined; // 保持文件描述符引用,避免被垃圾回收
  9053. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  9054. @State rotateAngle2: number = -9
  9055. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  9056. @Consume cover: string | undefined ;
  9057. @State artist: string | undefined = ''
  9058. // 1.初始化controller
  9059. private lyricController: LyricController = new LyricController()
  9060. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  9061. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  9062. private parser = new LyricParser()
  9063. @State randomShakenX: number = 0
  9064. @State randomShakenY: number = 0
  9065. @State lyricTextSize: number = 24
  9066. @State lyricContent: string = ''
  9067. @State isDebug: boolean = false
  9068. @State isHightLightCenter: boolean = true
  9069. /**
  9070. * 初始化歌词加载与展示逻辑
  9071. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  9072. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  9073. * @param isApi2 是否使用API2获取歌词(可选)
  9074. *
  9075. * 主要流程:
  9076. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  9077. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  9078. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  9079. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  9080. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  9081. * 6. 解析失败或读取失败时,清空歌词显示。
  9082. *
  9083. * 注意事项:
  9084. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  9085. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  9086. * - 歌词内容解析后通过lyricController驱动UI渲染。
  9087. */
  9088. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
  9089. if (StrUtil.isEmpty(lyricPath)) {
  9090. return
  9091. }
  9092. this.initPipLyricSetting()
  9093. this.lyricControllerSingle
  9094. .setTextSize(15)
  9095. .setCacheSize(4)
  9096. .setTextColor("#FFFFFF")
  9097. .setHighlightColor(this.currentHighLightLyricColor)
  9098. .setHighlightScale(1.2)
  9099. .setEmptyHint("")
  9100. .setLineSpace(1)
  9101. .setAlignMode('center')
  9102. .setAnimationDuration(500)
  9103. .setSingleLine(true)
  9104. this.lyricContent = ''
  9105. this.lyricController
  9106. .setTextSize(this.currentLyricSize)
  9107. .setCacheSize(4)
  9108. .setTextColor("#DDDDDD")
  9109. .setHighlightColor("#FFFFFF")
  9110. .setEmptyHint("")
  9111. .setAnimationDuration(1000)
  9112. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  9113. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  9114. this.setBlurDegree(this.blurDegree, false)
  9115. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  9116. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  9117. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  9118. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  9119. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  9120. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  9121. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  9122. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  9123. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  9124. this.lyricController.setTextWeight(this.lyricTextWeight)
  9125. this.showSingleLyric = false
  9126. this.timeOffset = 0
  9127. this.lyricController.setLyric(null)
  9128. this.lyricControllerSingle.setLyric(null)
  9129. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  9130. console.log("onecold lyricPath =" + lyricPath)
  9131. // 1. 检查内嵌歌词
  9132. let neiqianLrc = ''
  9133. let lyContent = this.currentSong?.lyricContent
  9134. if(lyContent && StrUtil.isNotEmpty(lyContent)){
  9135. neiqianLrc = lyContent
  9136. }
  9137. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast && !isLocal) {
  9138. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  9139. // Navidrome JSON歌词转换
  9140. if (this.currentSong && isNavidromeType(this.currentSong.type)) {
  9141. const convertedLyric: string | undefined = LyricUtil.convertNavidromeJsonLyricToLrc(neiqianLrc);
  9142. if (convertedLyric) {
  9143. neiqianLrc = convertedLyric;
  9144. console.log("onecold Navidrome歌词转换成功");
  9145. }
  9146. }
  9147. this.setLyricToControllers(neiqianLrc);
  9148. return
  9149. }
  9150. // 2. 尝试从服务器获取歌词 (Navidrome/Jellyfin/Emby/AudioStation/Plex)
  9151. if (this.currentSong && (isJellyfinType(this.currentSong.type)||isNavidromeType(this.currentSong.type)
  9152. || isEmbyType(this.currentSong.type) || isAudioStationType(this.currentSong.type)
  9153. || isPlexType(this.currentSong.type))) {
  9154. const manager = RemoteDriveManager.getInstance();
  9155. const getAccount = (accountId: string) => manager.getWebDavAccountById(accountId);
  9156. // 将currentSong转换为SongData接口
  9157. const songData: SongData = {
  9158. webdav_account_id: this.currentSong.webdav_account_id,
  9159. artist: this.currentSong.artist,
  9160. name: this.currentSong.name,
  9161. webdav_id: this.currentSong.webdav_id,
  9162. lyricIndex: this.currentSong.lyricIndex,
  9163. type: this.currentSong.type
  9164. };
  9165. let serverLyric = '';
  9166. if (!serverLyric && isNavidromeType(songData.type)) {
  9167. serverLyric = await lyricService.fetchNavidromeLyric(songData, getAccount,this.currentSong.id);
  9168. }
  9169. if (!serverLyric && isJellyfinType(songData.type)) {
  9170. serverLyric = await lyricService.fetchJellyfinLyric(songData, getAccount);
  9171. }
  9172. if (!serverLyric && isEmbyType(songData.type)) {
  9173. serverLyric = await lyricService.fetchEmbyLyric(songData, getAccount);
  9174. }
  9175. if (!serverLyric && isAudioStationType(songData.type)) {
  9176. serverLyric = await lyricService.fetchAudioStationLyric(songData, getAccount);
  9177. }
  9178. if (!serverLyric && isPlexType(songData.type)) {
  9179. serverLyric = await lyricService.fetchPlexLyric(songData, getAccount);
  9180. }
  9181. if (serverLyric) {
  9182. this.setLyricToControllers(serverLyric, lyricPath);
  9183. return;
  9184. }
  9185. }
  9186. // 3. 尝试在线歌词API
  9187. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  9188. && !Utility.isVideoByExtension(this.videoUrl))) {
  9189. this.fetchOnlineLyric(lyricPath, isOnLineAndToast || false, isApi2);
  9190. return;
  9191. }
  9192. // 4. 从本地文件读取歌词
  9193. await this.loadLyricFromFile(lyricPath, jiaMilyricPath, isLocal || false);
  9194. }
  9195. /**
  9196. * 从本地文件加载歌词
  9197. */
  9198. private async loadLyricFromFile(lyricPath: string, jiaMilyricPath: string, isLocal: boolean): Promise<void> {
  9199. try {
  9200. let isJiaMi = false;
  9201. let realLyricPath = lyricPath;
  9202. if (FileUtil.accessSync(jiaMilyricPath)) {
  9203. isJiaMi = true;
  9204. realLyricPath = jiaMilyricPath;
  9205. console.info("onecold 找到加密本地歌词 ");
  9206. } else {
  9207. isJiaMi = false;
  9208. realLyricPath = lyricPath;
  9209. console.info("onecold 找到本地歌词 ");
  9210. }
  9211. // 读取文件内容
  9212. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  9213. const stat = await fileIo.stat(file.fd);
  9214. const arrayBuffer = new ArrayBuffer(stat.size);
  9215. fs.read(file.fd, arrayBuffer)
  9216. .then((readLen: number) => {
  9217. console.info("read file data succeed");
  9218. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  9219. if (buf.length === 0) {
  9220. throw new Error("Buffer is empty after reading the file");
  9221. }
  9222. try {
  9223. // 检测文件编码
  9224. let detectedEncoding = this.detect(arrayBuffer);
  9225. console.info("onecoldT Detected encoding: " + detectedEncoding);
  9226. // 使用检测到的编码解码,解决中文乱码问题
  9227. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  9228. console.info("onecoldT Detected textDecoder: " + textDecoder);
  9229. let fileContent = textDecoder.decode(buf);
  9230. console.info(`onecoldT The content of file1: ${fileContent}`);
  9231. // 解密
  9232. if (isJiaMi) {
  9233. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  9234. }
  9235. console.info(`onecold The content of file2: ${fileContent}`);
  9236. this.lyricContent = fileContent;
  9237. if(isLocal){
  9238. // 编辑标签选择本地歌词需要赋值给this.lyricConStr
  9239. this.lyricConStr = fileContent;
  9240. }
  9241. this.setLyricToControllers(fileContent);
  9242. console.info(`The content of file: ${fileContent}`);
  9243. } catch (chardetError) {
  9244. console.error("chardet.detect failed with error: " + chardetError.message);
  9245. this.clearLyricControllers();
  9246. }
  9247. })
  9248. .catch((err: BusinessError) => {
  9249. this.clearLyricControllers();
  9250. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  9251. })
  9252. .catch((err: Error) => {
  9253. this.clearLyricControllers();
  9254. console.error("read file 2 data failed with error message: " + err.message);
  9255. })
  9256. .finally(() => {
  9257. fs.closeSync(file);
  9258. });
  9259. } catch (error) {
  9260. this.clearLyricControllers();
  9261. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  9262. }
  9263. }
  9264. detect(data: ArrayBuffer): string {
  9265. //创建检测对象
  9266. let detector: UniversalDetector = new UniversalDetector();
  9267. // 传入检测数据并实时判断编码格式
  9268. detector.handleData(data, 0, data.byteLength);
  9269. // 标记检测数据 读取结束
  9270. detector.dataEnd();
  9271. // 获取检测结果
  9272. let detected: string = detector.getDetectedCharset();
  9273. // 释放资源
  9274. detector.reset();
  9275. return detected;
  9276. }
  9277. /**
  9278. * 设置歌词到所有控制器
  9279. * @param lyricText 歌词文本
  9280. * @param savePath 可选,如果提供则保存到本地文件
  9281. */
  9282. private setLyricToControllers(lyricText: string, savePath?: string): void {
  9283. if (StrUtil.isEmpty(lyricText)) {
  9284. this.clearLyricControllers();
  9285. return;
  9286. }
  9287. this.lyricContent = lyricText;
  9288. const lines: string[] = lyricText.split('\n').map((line: string) => line.trim());
  9289. const lyric: Lyric = this.parser.parse(lines);
  9290. this.lyricController.setLyric(lyric);
  9291. this.lyricControllerXF.setLyric(lyric);
  9292. this.lyricControllerSingle.setLyric(lyric);
  9293. this.showSingleLyric = true;
  9294. // 如果提供了保存路径,保存歌词到本地
  9295. if (savePath) {
  9296. this.saveDataToFile(lyricText, savePath, false);
  9297. }
  9298. }
  9299. /**
  9300. * 清空所有歌词控制器
  9301. */
  9302. private clearLyricControllers(): void {
  9303. this.lyricController.setLyric(null);
  9304. this.lyricControllerXF.setLyric(null);
  9305. this.lyricControllerSingle.setLyric(null);
  9306. }
  9307. /**
  9308. * 从在线API获取歌词
  9309. */
  9310. private fetchOnlineLyric(lyricPath: string, isOnLineAndToast: boolean, isApi2?: boolean): void {
  9311. if (!this.currentSong) {
  9312. this.clearLyricControllers();
  9313. if (isOnLineAndToast) {
  9314. ToastUtil.showShort('未获取到歌词!');
  9315. }
  9316. return;
  9317. }
  9318. let artist = this.currentSong.artist || '';
  9319. if (isApi2 === undefined) {
  9320. isApi2 = false;
  9321. }
  9322. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  9323. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  9324. this.setLyricToControllers(res, lyricPath);
  9325. } else {
  9326. this.clearLyricControllers();
  9327. if (isOnLineAndToast) {
  9328. ToastUtil.showShort('未获取到歌词!');
  9329. }
  9330. }
  9331. });
  9332. }
  9333. //初始化悬浮歌词的自定义设置
  9334. initPipLyricSetting() {
  9335. this.lyricControllerXF
  9336. .setTextSize(this.currentLyricSize)
  9337. .setCacheSize(4)
  9338. .setTextColor("#DDDDDD")
  9339. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  9340. .setEmptyHint("")
  9341. .setAnimationDuration(1000)
  9342. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  9343. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  9344. this.setBlurDegree(this.blurDegreePip, true)
  9345. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  9346. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  9347. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  9348. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  9349. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  9350. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  9351. this.lyricControllerXF.setHightLightCenter(true)
  9352. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  9353. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  9354. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  9355. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  9356. if (this.pipBgIndex === 0) {
  9357. if (this.cover) {
  9358. this.pipBg = this.cover
  9359. } else {
  9360. this.pipBg = this.imageColor
  9361. }
  9362. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  9363. }
  9364. }
  9365. //根据item返回歌词内容
  9366. async getLyricContent(item: VideoItem): Promise<string> {
  9367. let neiqianLrc = ''
  9368. let lyContent = item?.lyricContent
  9369. if(lyContent&&StrUtil.isNotEmpty(lyContent)){
  9370. neiqianLrc = lyContent
  9371. return neiqianLrc
  9372. }
  9373. try {
  9374. //取数据库里面的歌词lyContent
  9375. const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
  9376. if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
  9377. console.log("onecold Lyrics:", lyricContent);
  9378. neiqianLrc = lyricContent
  9379. return neiqianLrc
  9380. }
  9381. } catch (error) {
  9382. console.error("Error fetching lyrics:", error);
  9383. }
  9384. try {
  9385. let filePath = item.filePath;
  9386. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  9387. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  9388. let isJiaMi = false;
  9389. let realLyricPath = lyricPath;
  9390. if (FileUtil.accessSync(jiaMilyricPath)) {
  9391. isJiaMi = true;
  9392. realLyricPath = jiaMilyricPath;
  9393. console.info("onecold 找到加密本地歌词");
  9394. } else {
  9395. console.info("onecold 找到本地歌词");
  9396. }
  9397. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  9398. const stat = await fileIo.stat(file.fd);
  9399. const arrayBuffer = new ArrayBuffer(stat.size);
  9400. const readLen = await fs.read(file.fd, arrayBuffer);
  9401. console.info("read file data succeed");
  9402. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  9403. if (buf.length === 0) {
  9404. throw new Error("Buffer is empty after reading the file");
  9405. }
  9406. // let detectedEncoding = chardet.detect(buf);
  9407. let detectedEncoding = this.detect(arrayBuffer)
  9408. console.info("Detected encoding: " + detectedEncoding);
  9409. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  9410. let fileContent = textDecoder.decode(buf);
  9411. console.info(`onecold The content of file1: ${fileContent}`);
  9412. if (isJiaMi) {
  9413. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  9414. }
  9415. console.info(`onecold The content of file2: ${fileContent}`);
  9416. fs.closeSync(file);
  9417. return fileContent;
  9418. } catch (error) {
  9419. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  9420. return '';
  9421. }
  9422. }
  9423. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  9424. if (StrUtil.isEmpty(filePath)) {
  9425. return
  9426. }
  9427. try {
  9428. //将content进行加密
  9429. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  9430. let lyricContent = ''
  9431. if (isJiaMi) {
  9432. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  9433. } else {
  9434. lyricContent = content
  9435. }
  9436. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  9437. // 清空文件内容
  9438. await fileIo.truncate(file.fd, 0);
  9439. await fileIo.write(file.fd, lyricContent);
  9440. await fileIo.close(file);
  9441. console.log('onecold lyric file Data saved successfully.');
  9442. } catch (error) {
  9443. console.error('onecold lyric file Failed to save data:', error);
  9444. }
  9445. }
  9446. // 定义开始旋转的方法
  9447. // 使用动画系统优化旋转性能,避免 setInterval 频繁更新导致卡顿
  9448. @State timer: number = 0
  9449. @State rotateAngle: number = 0
  9450. @State isRotationRunning: boolean = false // 旋转动画是否正在运行
  9451. //封面旋转动画
  9452. animationRoFun() {
  9453. if (this.isPlaying && !this.isCoverRectangle) {
  9454. // 启动旋转动画
  9455. if (!this.isRotationRunning) {
  9456. this.isRotationRunning = true
  9457. this.startContinuousRotation()
  9458. }
  9459. this.startRotation()
  9460. } else {
  9461. // 停止旋转动画
  9462. this.isRotationRunning = false
  9463. clearInterval(this.timer)
  9464. this.stopRotation()
  9465. }
  9466. }
  9467. // 使用持续的动画进行旋转,避免频繁状态更新
  9468. private startContinuousRotation() {
  9469. clearInterval(this.timer)
  9470. // 改为每 1000ms 更新 36 度(10秒一圈),减少更新频率
  9471. // 不使用 % 360 取模,让角度持续累加,避免反转
  9472. this.timer = setInterval(() => {
  9473. if (this.isRotationRunning) {
  9474. this.rotateAngle = this.rotateAngle + 36
  9475. }
  9476. }, 1000)
  9477. }
  9478. // 定义开始旋转的方法
  9479. startRotation() {
  9480. if (this.isPlaying) {
  9481. animateTo({
  9482. duration: 777,
  9483. iterations: 1,
  9484. curve: Curve.Linear
  9485. }, () => {
  9486. this.rotateAngle2 = -9
  9487. })
  9488. }
  9489. }
  9490. // 回调,暂停和播放按钮回调,下一首和上一首
  9491. playChange() {
  9492. // if(this.isCoverRectangle){
  9493. // return
  9494. // }
  9495. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  9496. this.setIsPlaying(true)
  9497. this.animationState = AnimationStatus.Running
  9498. } else {
  9499. this.setIsPlaying(false)
  9500. this.animationState = AnimationStatus.Paused
  9501. }
  9502. AppStorage.setOrCreate('animationState', this.animationState);
  9503. }
  9504. // 定义停止旋转的方法
  9505. stopRotation() {
  9506. if (this.isCoverRectangle) {
  9507. this.rotateAngle = 0
  9508. } else {
  9509. //唱针以左上角为点选择逆时针40度
  9510. animateTo({
  9511. duration: 1000,
  9512. curve: Curve.Linear,
  9513. iterations: 1,
  9514. }, () => {
  9515. this.rotateAngle2 = -45;
  9516. });
  9517. }
  9518. }
  9519. @Builder
  9520. private LyricsTopItem() {
  9521. Row() {
  9522. Stack() {
  9523. Image( StrUtil.isNotEmpty(this.cover)?
  9524. this.cover:$r('app.media.alt'))
  9525. .height(58)
  9526. .width(58)
  9527. .clip(true)
  9528. .sourceSize({width:38, height:38})
  9529. .alt($r('app.media.alt'))
  9530. .borderRadius(8)
  9531. .clickEffect({ level: ClickEffectLevel.HEAVY })
  9532. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  9533. .shadow({
  9534. radius: 22,
  9535. type: ShadowType.BLUR,
  9536. color: 'on_primary'
  9537. })
  9538. }
  9539. .width('18%')
  9540. Column() {
  9541. Column() {
  9542. Text(this.name)
  9543. .fontSize(16)
  9544. .maxLines(1)
  9545. .fontWeight(FontWeight.Bolder)
  9546. .fontColor(Color.White)
  9547. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  9548. Row() {
  9549. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  9550. .fontSize(13)
  9551. .fontWeight(FontWeight.Bolder)
  9552. .padding({ top: 8 })
  9553. .fontColor(Color.White)
  9554. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  9555. Blank()
  9556. }
  9557. }
  9558. .height('100%')
  9559. .width('100%')
  9560. .justifyContent(FlexAlign.Center)
  9561. .alignItems(HorizontalAlign.Start)
  9562. }
  9563. .height('100%')
  9564. .width('65%')
  9565. Column() {
  9566. PointLightDefaultButton({
  9567. isSysBol:false,
  9568. pointColor:Color.White,
  9569. imageResource:$r('app.media.lyric'),
  9570. isPx: false,
  9571. builderHeight: 27,
  9572. builderWidth: 27,
  9573. })
  9574. .onClick(() => {
  9575. this.isLyricSetting = !this.isLyricSetting;
  9576. })
  9577. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  9578. height: '99%',
  9579. dragBar: true,
  9580. preferType: SheetType.CENTER,
  9581. showClose: true,
  9582. blurStyle: BlurStyle.Thin,
  9583. backgroundColor: Color.Transparent,
  9584. title: { title: $r('app.string.lyric_setting') }
  9585. })
  9586. }
  9587. .width('18%')
  9588. }
  9589. .width('82%')
  9590. .height(58)
  9591. .justifyContent(FlexAlign.SpaceBetween)
  9592. }
  9593. //歌词显示
  9594. @Builder
  9595. PlayerLyrics() {
  9596. Column() {
  9597. Column() {
  9598. this.LyricsTopItem()
  9599. }
  9600. .height(this.isPuraWP() ? 15 : 58)
  9601. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  9602. Visibility.None : Visibility.Visible)
  9603. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  9604. .width("100%")
  9605. Column() {
  9606. LyricView2({
  9607. controller: this.lyricController,
  9608. enableSeek: true,
  9609. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  9610. seekLineColor: "#80ffffff", // 滑动定位线颜色
  9611. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  9612. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  9613. if (!this.isPlaying) {
  9614. console.info('onecold startPlayOrResumePlay 7527')
  9615. this.startPlayOrResumePlay()
  9616. }
  9617. else {
  9618. this.isSeekTo = true;
  9619. this.mDestroyPage = false;
  9620. // 只有播放网盘歌曲时才显示转圈圈
  9621. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  9622. this.showLoadIng();
  9623. }
  9624. this.seekTo(position + "");
  9625. }
  9626. return true
  9627. }
  9628. })
  9629. .width("100%")
  9630. .layoutWeight(1)
  9631. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  9632. if (this.isPhoneLan()) {
  9633. Column() {
  9634. this.playProgressView()
  9635. }
  9636. .margin({ bottom: 32, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  9637. }
  9638. }
  9639. .position({
  9640. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  9641. (this.isPuraWP() ? 58 : 99)
  9642. })
  9643. .justifyContent(FlexAlign.Center)
  9644. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  9645. }
  9646. }
  9647. @Builder
  9648. SingleLyricView() {
  9649. Column() {
  9650. Column() {
  9651. LyricView2({
  9652. controller: this.lyricControllerSingle,
  9653. enableSeek: false,
  9654. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  9655. seekLineColor: "#80ffffff", // 滑动定位线颜色
  9656. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  9657. })
  9658. }
  9659. .height(82)
  9660. .margin({ bottom: 20 })
  9661. }
  9662. }
  9663. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  9664. @Builder
  9665. BottomControl() {
  9666. Column() {
  9667. this.TopPlayProgressView()
  9668. //播放 暂停,下一首,上一首
  9669. this.playCenterView()
  9670. if(!this.curDisplayIsHiCar){
  9671. //播放进度条
  9672. this.BottomView()
  9673. }
  9674. }
  9675. .justifyContent(FlexAlign.Center)
  9676. .alignItems(HorizontalAlign.Center)
  9677. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  9678. }
  9679. @Builder
  9680. private EqualizerQuickBar(): void {
  9681. Row() {
  9682. Row() {
  9683. SymbolGlyph($r('sys.symbol.waveform'))
  9684. .fontSize(16)
  9685. .fontColor([this.themeColor])
  9686. Text('均衡器')
  9687. .fontSize(12)
  9688. .fontColor(Color.White)
  9689. .margin({ left: 6 })
  9690. }
  9691. .onClick(() => {
  9692. this.isEqualizerSheet = true;
  9693. })
  9694. Blank()
  9695. Toggle({ type: ToggleType.Switch, isOn: this.eqCurrentEnabled })
  9696. .selectedColor(this.themeColor)
  9697. .switchPointColor(Color.White)
  9698. .width(42)
  9699. .height(22)
  9700. .onChange((isOn: boolean) => {
  9701. const equalizerManager = EqualizerManager.getInstance();
  9702. equalizerManager.enabled = isOn;
  9703. this.syncEqualizerUi();
  9704. if (this.mIjkMediaPlayer) {
  9705. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  9706. this.markEqualizerApplied();
  9707. }
  9708. })
  9709. Text(this.eqCurrentPresetName)
  9710. .fontSize(10)
  9711. .fontColor(Color.White)
  9712. .margin({ left: 8 })
  9713. Text(this.eqAppliedAt > 0 ? '已生效' : '未应用')
  9714. .fontSize(10)
  9715. .fontColor(this.eqAppliedAt > 0 ? this.themeColor : Color.White)
  9716. .margin({ left: 8 })
  9717. Button('应用')
  9718. .fontSize(11)
  9719. .fontColor(Color.White)
  9720. .backgroundColor(this.eqAppliedAt > 0 ? this.themeColor : '#666666')
  9721. .height(24)
  9722. .padding({ left: 10, right: 10 })
  9723. .borderRadius(12)
  9724. .enabled(!this.eqApplying && this.CONTROL_PlayStatus !== PlayStatus.INIT)
  9725. .onClick(() => {
  9726. this.applyEqualizerToCurrentPlayback();
  9727. })
  9728. }
  9729. .width(this.isLandscape ? '88%' : '95%')
  9730. .padding({ left: 12, right: 12, top: 6, bottom: 6 })
  9731. .backgroundColor('rgba(0,0,0,0.32)')
  9732. .borderRadius(12)
  9733. }
  9734. @Builder
  9735. playMenuBuilder(){
  9736. Image($r('app.media.menu'))
  9737. .width(24)
  9738. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9739. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  9740. height: '99%',
  9741. preferType:SheetType.CENTER,
  9742. dragBar: true,
  9743. showClose: true,
  9744. blurStyle: BlurStyle.Thin,
  9745. title: { title: $r('app.string.more') },
  9746. backgroundColor: Color.Transparent,
  9747. })
  9748. }
  9749. //播放控制上一首 下一首 暂停和播放
  9750. @Builder
  9751. playCenterView(){
  9752. Row() {
  9753. PointLightButton({
  9754. builder: () => {
  9755. this.playMenuBuilder()
  9756. },
  9757. isPx: false,
  9758. builderHeight: 32,
  9759. builderWidth: 32,
  9760. })
  9761. .onClick(async () =>{
  9762. this.isShowMoreView = !this.isShowMoreView;
  9763. })
  9764. PointLightButton({
  9765. builder: () => {
  9766. this.playPreviousBuilder()
  9767. },
  9768. isPx: false,
  9769. builderHeight: 32,
  9770. builderWidth: 32,
  9771. })
  9772. .onClick(async () =>{
  9773. await this.playPrevious()
  9774. })
  9775. PointLightButton({
  9776. builder: () => {
  9777. this.PlayOrPauseButton()
  9778. },
  9779. isPx: false,
  9780. builderHeight: this.isPhoneLan()?42:55,
  9781. builderWidth: this.isPhoneLan()?42:55,
  9782. })
  9783. .onClick(() =>{
  9784. this.playOrPause()
  9785. })
  9786. PointLightButton({
  9787. builder: () => {
  9788. this.playNextBuilder()
  9789. },
  9790. isPx: false,
  9791. builderHeight: 32,
  9792. builderWidth: 32,
  9793. })
  9794. .onClick(async () =>{
  9795. await this.playNext()
  9796. })
  9797. this.playModeButton()
  9798. }
  9799. .width('95%')
  9800. .margin({ bottom:this.isCoverOpacity()?0:15 })
  9801. .justifyContent(FlexAlign.SpaceEvenly)
  9802. }
  9803. @Builder
  9804. playPreviousBuilder(){
  9805. Image($r('app.media.ic_previous'))
  9806. .width(32)
  9807. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9808. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9809. }
  9810. @Builder
  9811. playNextBuilder(){
  9812. Image($r('app.media.ic_next'))
  9813. .width(32)
  9814. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9815. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9816. }
  9817. @Builder
  9818. PlayOrPauseButton(){
  9819. Stack() {
  9820. Column() {
  9821. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  9822. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  9823. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  9824. .width(this.isPhoneLan()?43:53)
  9825. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9826. .fillColor(Color.White)
  9827. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9828. }
  9829. // 加载进度圈
  9830. if (this.isPlayerLoading) {
  9831. Progress({value:0,total:100,type:ProgressType.Ring })
  9832. .width(this.isPhoneLan()?46:55)
  9833. .height(this.isPhoneLan()?46:55)
  9834. .color(Color.White)
  9835. .style({ strokeWidth: 5, status: ProgressStatus.LOADING })
  9836. }
  9837. }
  9838. .width(this.isPhoneLan()?43:53)
  9839. .height(this.isPhoneLan()?43:53)
  9840. }
  9841. @Builder
  9842. TopPlayProgressView(){
  9843. Column() {
  9844. Row(){
  9845. Stack(){
  9846. SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
  9847. .fontColor([Color.White])
  9848. .fontSize(21)
  9849. .effectStrategy(1)
  9850. Text(this.fastForwardSeconds)
  9851. .fontColor(Color.White)
  9852. .fontSize(10)
  9853. .fontWeight(FontWeight.Bold)
  9854. }
  9855. .padding({left:12,bottom:6})
  9856. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  9857. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9858. .onClick(()=>{
  9859. this.backForward()
  9860. })
  9861. Slider({
  9862. value: this.progressValue,
  9863. min: 0,
  9864. max: this.PROGRESS_MAX_VALUE,
  9865. step: 1,
  9866. style: SliderStyle.InSet
  9867. })
  9868. .height(20)
  9869. .blockColor('rgba(255,255,255,1)')
  9870. .trackColor('rgba(255,255,255,0.3)')
  9871. .selectedColor(Color.White)
  9872. .trackThickness(4)
  9873. .showSteps(false)
  9874. .showTips(true)
  9875. .layoutWeight(1)
  9876. .enabled(this.slideEnable)
  9877. .onChange((value: number, mode: SliderChangeMode) => {
  9878. if(this.isSeekTo)
  9879. return
  9880. this.isSeekTo = true;
  9881. this.mDestroyPage = false;
  9882. // 只有播放网盘歌曲时才显示转圈圈
  9883. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  9884. this.showLoadIng();
  9885. }
  9886. let seekValue = value * (this.getActiveDuration() / 100);
  9887. console.info("onecold this.currentSong.type:"+this.currentSong?.type)
  9888. this.seekTo(seekValue + "");
  9889. })
  9890. Stack(){
  9891. SymbolGlyph($r('sys.symbol.arrow_clockwise'))
  9892. .fontColor([Color.White])
  9893. .fontSize(21)
  9894. .effectStrategy(1)
  9895. Text(this.fastForwardSeconds)
  9896. .fontColor(Color.White)
  9897. .fontSize(10)
  9898. .fontWeight(FontWeight.Bold)
  9899. }
  9900. .padding({right:10,bottom:6})
  9901. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  9902. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9903. .onClick(()=>{
  9904. this.fastForward()
  9905. })
  9906. }
  9907. .justifyContent(FlexAlign.Center)
  9908. .padding({left:20,right:20})
  9909. .width(this.isLandscape?'88%':'95%')
  9910. Row() {
  9911. Text(this.currentTime)
  9912. .fontSize(10)
  9913. .fontColor(Color.White)
  9914. .margin({left:25})
  9915. Blank()
  9916. Text(this.totalTime)
  9917. .fontSize(10)
  9918. .fontColor(Color.White)
  9919. .margin({right:25})
  9920. }
  9921. .width(this.isLandscape?'85%':'90%')
  9922. .height(10)
  9923. }
  9924. .width('100%')
  9925. .alignItems(HorizontalAlign.Center)
  9926. }
  9927. @Builder
  9928. playModeButton(){
  9929. PointLightButton({
  9930. builder: () => {
  9931. this.playModeBuilder()
  9932. },
  9933. isPx: false,
  9934. builderHeight: 32,
  9935. builderWidth: 32,
  9936. })
  9937. .onClick(async () =>{
  9938. this.setLoopMode()
  9939. })
  9940. }
  9941. @Builder
  9942. playModeBuilder(){
  9943. Column() {
  9944. if (this.playType === 0) {
  9945. Image($r('app.media.loop'))
  9946. .width(26)
  9947. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9948. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9949. } else if (this.playType === 1) {
  9950. Image($r('app.media.single'))
  9951. .width(26)
  9952. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9953. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9954. } else if (this.playType === 2) {
  9955. Image($r('app.media.normal_play'))
  9956. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9957. .width(26)
  9958. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9959. } else if (this.playType === 3) {
  9960. Image($r('app.media.random'))
  9961. .width(26)
  9962. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9963. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9964. }
  9965. }
  9966. }
  9967. //播放进度条
  9968. @Builder
  9969. BottomView(){
  9970. Row() {
  9971. PointLightDefaultButton({
  9972. isSysBol:true,
  9973. pointColor:Color.White,
  9974. imageResource:$r('sys.symbol.rectangle_portrait_rotate'),
  9975. isPx: false,
  9976. builderHeight: 26,
  9977. builderWidth: 26,
  9978. })
  9979. .onClick(async () =>{
  9980. if (this.isLandscape) {
  9981. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  9982. } else {
  9983. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  9984. }
  9985. })
  9986. if(this.currentSong){
  9987. PointLightDefaultButton({
  9988. isSysBol:true,
  9989. pointColor:Color.White,
  9990. imageResource:$r('sys.symbol.rename'),
  9991. isPx: false,
  9992. builderHeight: 26,
  9993. builderWidth: 26,
  9994. })
  9995. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  9996. height: '99%',
  9997. dragBar: true,
  9998. showClose: true,
  9999. preferType: SheetType.BOTTOM,
  10000. title: { title: '编辑标签' }
  10001. })
  10002. .onClick(async () => {
  10003. this.initEditFields(this.currentSong)
  10004. this.tempLyricContent = this.lyricContent
  10005. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  10006. this.lyricConStr = this.tempLyricContent
  10007. }
  10008. this.isShowEdit = !this.isShowEdit;
  10009. })
  10010. }
  10011. PointLightDefaultButton({
  10012. isSysBol:false,
  10013. pointColor:Color.White,
  10014. imageResource:$r('app.media.lyric'),
  10015. isPx: false,
  10016. builderHeight: 26,
  10017. builderWidth: 26,
  10018. })
  10019. .onClick(async () => {
  10020. this.isLyricSetting = !this.isLyricSetting;
  10021. })
  10022. this.playListBuilder()
  10023. }
  10024. .width(this.isLandscape?'88%':'95%')
  10025. .justifyContent(FlexAlign.SpaceAround)
  10026. .visibility(this.showSimple?Visibility.None:Visibility.Visible)
  10027. .height(30)
  10028. .animation({
  10029. duration: 666,
  10030. curve: 'ease-in-out' // 可选动画曲线
  10031. })
  10032. }
  10033. @Builder
  10034. fullButton(){
  10035. Column() {
  10036. Image($r('app.media.full_4'))
  10037. .width(25)
  10038. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  10039. .aspectRatio(CommonConstants.ASPECT_RATIO)
  10040. }
  10041. }
  10042. @Builder
  10043. playListBuilder(){
  10044. PointLightDefaultButton({
  10045. isSysBol:true,
  10046. pointColor:Color.White,
  10047. imageResource:$r('sys.symbol.music_note_list'),
  10048. isPx: false,
  10049. builderHeight: 26,
  10050. builderWidth: 26,
  10051. })
  10052. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  10053. height: '95%',
  10054. dragBar: true,
  10055. showClose: true,
  10056. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  10057. blurStyle: BlurStyle.Thin,
  10058. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  10059. title: {
  10060. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  10061. + `(${this.getPlayListDisplayCount()}首)`
  10062. }
  10063. })
  10064. .onClick(() => {
  10065. this.isShowSheetView = !this.isShowSheetView;
  10066. if(this.isPlayListBgGrass){
  10067. this.isFrontWhite = true
  10068. }else{
  10069. this.isFrontWhite = false
  10070. }
  10071. this.scrollIndex()
  10072. // 只有在播放本地音乐时才自动加载完整列表
  10073. if (this.currentSong && this.currentSong.type === CommonConstants.TYPE_LOCAL) {
  10074. void this.hydrateFullMediaPlayListIfNeeded();
  10075. }
  10076. })
  10077. }
  10078. //旧版本播放进度条(现在是手机横屏的播放条)
  10079. @Builder
  10080. playProgressView() {
  10081. Row() {
  10082. Column(){
  10083. PointLightDefaultButton({
  10084. isSysBol:true,
  10085. pointColor:Color.White,
  10086. imageResource:$r('sys.symbol.rectangle_portrait_rotate'),
  10087. isPx: false,
  10088. builderHeight: 26,
  10089. builderWidth: 26,
  10090. })
  10091. .onClick(async () =>{
  10092. if (this.isLandscape) {
  10093. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  10094. } else {
  10095. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  10096. }
  10097. })
  10098. }
  10099. .margin({ right: 10,bottom:6})
  10100. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  10101. .animation({
  10102. duration: 666,
  10103. curve: 'ease-in-out' // 可选动画曲线
  10104. })
  10105. Text(this.currentTime)
  10106. .fontSize($r('app.float.slider_font_size'))
  10107. .fontColor(Color.White)
  10108. .margin(3)
  10109. Slider({
  10110. value: this.progressValue,
  10111. min: 0,
  10112. max: this.PROGRESS_MAX_VALUE,
  10113. step: 1,
  10114. style: SliderStyle.InSet
  10115. })
  10116. .width('600px')
  10117. .blockColor('rgba(255,255,255,1)')
  10118. .trackColor('rgba(255,255,255,0.3)')
  10119. .selectedColor(Color.White)
  10120. .trackThickness(5)
  10121. .layoutWeight(1)
  10122. .margin({top:4, left: PlayConstants.PROGRESS_MARGIN_LEFT })
  10123. .showSteps(false)
  10124. .showTips(true)
  10125. .enabled(this.slideEnable)
  10126. .onChange((value: number, mode: SliderChangeMode) => {
  10127. // if (mode == 2) {
  10128. this.isSeekTo = true;
  10129. this.mDestroyPage = false;
  10130. // 只有播放网盘歌曲时才显示转圈圈
  10131. console.info("onecold this.currentSong.type:"+this.currentSong?.type)
  10132. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  10133. console.info("onecold 开始转圈圈")
  10134. this.showLoadIng();
  10135. }
  10136. let seekValue = value * (this.getActiveDuration() / 100);
  10137. this.seekTo(seekValue + "");
  10138. })
  10139. Text(this.totalTime)
  10140. .fontSize($r('app.float.slider_font_size'))
  10141. .fontColor(Color.White)
  10142. .margin(3)
  10143. //播放列表
  10144. Column(){
  10145. this.playListBuilder()
  10146. }
  10147. .margin({ left: 10,bottom:6})
  10148. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  10149. .animation({
  10150. duration: 666,
  10151. curve: 'ease-in-out' // 可选动画曲线
  10152. })
  10153. }
  10154. //x5的竖屏模式需要99%
  10155. .width(this.isPhonePortrait() ? '93.4%'
  10156. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  10157. .height(this.isPhoneLan() ? 25 : 33)
  10158. .alignItems(VerticalAlign.Bottom)
  10159. .animation({
  10160. duration: 666,
  10161. curve: 'ease-in-out' // 可选动画曲线
  10162. })
  10163. }
  10164. isBigScreen() {
  10165. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  10166. return true
  10167. }
  10168. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  10169. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  10170. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  10171. return false
  10172. } else {
  10173. return true
  10174. }
  10175. return false
  10176. }
  10177. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  10178. // 添加控制缩放的状态变量
  10179. @State scaleValueImage: number = 1
  10180. @State scaleValueText: number = 1
  10181. @Builder
  10182. CoverInfo() {
  10183. Column() {
  10184. Stack() {
  10185. Column() {
  10186. //方形封面布局
  10187. if (this.isCoverRectangle) {
  10188. this.RectangleCoverView()
  10189. } else {
  10190. //圆形封面布局
  10191. this.CicleCoverView()
  10192. }
  10193. this.musicNameInfo(false)
  10194. if (this.isPhoneLan()) {
  10195. Text(this.name)
  10196. .fontSize(18)
  10197. .fontWeight(FontWeight.Bold)
  10198. .margin({ top: 13 })
  10199. .textOverflow({ overflow: TextOverflow.Ellipsis })
  10200. .maxLines(1)
  10201. .width('99%')
  10202. .textAlign(TextAlign.Center)
  10203. .fontColor(Color.White)
  10204. }
  10205. }
  10206. .width('100%')
  10207. Column({ space: 8 }) {
  10208. Text(this.name)
  10209. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  10210. .fontWeight(FontWeight.Bold)
  10211. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  10212. .maxLines(1)
  10213. .width('85%')
  10214. .textAlign(TextAlign.Center)
  10215. .fontColor(Color.White)
  10216. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  10217. Text(this.artist)
  10218. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  10219. .fontColor(Color.White)
  10220. .fontWeight(FontWeight.Bold)
  10221. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  10222. }
  10223. .justifyContent(FlexAlign.Start)
  10224. .zIndex(1)
  10225. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  10226. }
  10227. .margin({
  10228. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  10229. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  10230. top: this.isCoverOpacity() ? 0 : 20
  10231. })
  10232. if (this.isPhonePortrait() && this.isShowSingleLineLyric) {
  10233. this.SingleLyricView()
  10234. }
  10235. if (this.isPhoneLan()) {
  10236. Column() {
  10237. this.playCenterView()
  10238. }
  10239. .position({ left: 28, bottom: 38 })
  10240. } else {
  10241. this.BottomControl()
  10242. }
  10243. }
  10244. .width(CommonConstants.FULL_PERCENT)
  10245. .clip(true)
  10246. }
  10247. //方形封面布局
  10248. @Builder
  10249. RectangleCoverView(){
  10250. Stack({alignContent:Alignment.Center}){
  10251. Image( StrUtil.isNotEmpty(this.cover)?
  10252. this.cover:$r('app.media.alt'))
  10253. .height(this.isHiCar()?(px2vp(this.windowHeight)*0.43):
  10254. this.isCoverOpacity()?(px2vp(this.windowHeight)*0.54):'auto')
  10255. .width(this.isHiCar()||this.isCoverOpacity()?'auto':this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '88%')
  10256. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  10257. .alt($r('app.media.alt'))
  10258. .margin({ right: 8, left: 8, top: 8 })
  10259. .aspectRatio(1)
  10260. .geometryTransition('cover') // 绑定标识符
  10261. .opacity(this.opacityValueImage)
  10262. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  10263. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  10264. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  10265. .clip(true)
  10266. .rotate({
  10267. x: 0,
  10268. y: 0,
  10269. z: 1,
  10270. angle: this.rotateAngle
  10271. })
  10272. .animation({
  10273. duration: 1000, // 与 setInterval 同步
  10274. curve: Curve.Linear,
  10275. iterations: 1
  10276. })
  10277. .shadow({
  10278. radius: 22,
  10279. type: ShadowType.BLUR,
  10280. color: 'on_primary'
  10281. })
  10282. .onClick(() => {
  10283. this.isMusicBGCover = !this.isMusicBGCover
  10284. })
  10285. }
  10286. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  10287. // 设置左下角为缩放中心点
  10288. centerX: '0%',
  10289. centerY: '100%' })
  10290. }
  10291. @Builder
  10292. CicleCoverView() {
  10293. //圆形封面布局
  10294. Stack({alignContent:Alignment.Center}) {
  10295. Image($r('app.media.ic_music_disc'))
  10296. .width(245)
  10297. .height(245)
  10298. .margin({ right: 20, left: 20 ,top:this.isCoverRectangle||this.isLandscape?0:50 })
  10299. .aspectRatio(1)
  10300. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  10301. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  10302. .borderRadius('100%')
  10303. .align(Alignment.Center)
  10304. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  10305. .rotate({
  10306. angle: this.rotateAngle,
  10307. centerX: "50%",
  10308. centerY: "50%",
  10309. })
  10310. .animation({
  10311. duration: 1000, // 改为 1000ms 与 setInterval 同步
  10312. curve: Curve.Linear,
  10313. iterations: 1 // 只执行一次,下一次更新会触发新的动画
  10314. })
  10315. .shadow({
  10316. radius: 22,
  10317. type: ShadowType.BLUR,
  10318. color: 'on_primary'
  10319. })
  10320. Image( StrUtil.isNotEmpty(this.cover)?
  10321. this.cover:$r('app.media.alt'))
  10322. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
  10323. (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 168))
  10324. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  10325. .alt($r('app.media.alt'))
  10326. .margin({ right: 20, left: 20,
  10327. top:this.isCoverRectangle||this.isLandscape?0:50})
  10328. .aspectRatio(1)
  10329. .opacity(this.opacityValueImage)
  10330. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  10331. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  10332. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  10333. .align(Alignment.Center)//
  10334. .clip(true)
  10335. .shadow({
  10336. radius: 22,
  10337. type: ShadowType.BLUR,
  10338. color: 'on_primary'
  10339. })
  10340. .rotate({
  10341. x: 0,
  10342. y: 0,
  10343. z: 1,
  10344. angle: this.rotateAngle
  10345. })
  10346. .animation({
  10347. duration: 1000, // 与 setInterval 同步
  10348. curve: Curve.Linear,
  10349. iterations: 1
  10350. })
  10351. .onClick(() => {
  10352. this.isMusicBGCover = !this.isMusicBGCover
  10353. })
  10354. // 唱针以左上角为点选择逆时针40度
  10355. Image($r('app.media.ic_music_cover_hand'))
  10356. .height(130)
  10357. .margin({ bottom: 200, top: 0 })
  10358. // .position({ x: this.windowWidth/2, y: 0 })
  10359. .align(Alignment.Top)
  10360. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  10361. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  10362. .visibility(this.isHiCar()||this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  10363. }
  10364. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  10365. // 设置左下角为缩放中心点
  10366. centerX: '0%',
  10367. centerY: '100%' })
  10368. }
  10369. @Builder
  10370. private musicNameInfo(isHidden: boolean) {
  10371. Row(){
  10372. Column({ space: 8 }) {
  10373. Text(this.name)
  10374. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 20)
  10375. .fontWeight(FontWeight.Bold)
  10376. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  10377. .maxLines(1)
  10378. .width('99%')
  10379. .textAlign(TextAlign.Start)
  10380. .fontColor(Color.White)
  10381. Text(this.artist + ' ' + this.currentSong?.album)
  10382. .fontSize(this.isCoverOpacity() ? 12 : 15)
  10383. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  10384. .fontColor(Color.White)
  10385. .textAlign(TextAlign.Start)
  10386. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  10387. .width('99%')
  10388. .maxLines(1)
  10389. }
  10390. .zIndex(1)
  10391. .layoutWeight(1)
  10392. .margin({ left: 15 })
  10393. Blank()
  10394. Row(){
  10395. Button({type:ButtonType.Circle,stateEffect:true}){
  10396. //添加或取消收藏
  10397. SymbolGlyph(Utility.getIsFav(this.favList,this.currentSong)?
  10398. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'))
  10399. .fontSize(22)
  10400. .fontColor([Color.White])
  10401. .alignSelf(ItemAlign.Center)
  10402. .clickEffect({level:ClickEffectLevel.MIDDLE})
  10403. .aspectRatio(CommonConstants.ASPECT_RATIO)
  10404. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  10405. .onClick(async () => {
  10406. if(this.currentSong){
  10407. this.doFav(this.currentSong)
  10408. }
  10409. })
  10410. }
  10411. .margin({ left: 8,right:8 })
  10412. .backgroundColor(Color.Transparent)
  10413. .width(45)
  10414. .height(45)
  10415. }
  10416. }
  10417. .width(this.isLandscape?'83%':'90%')
  10418. .scale({ x: this.scaleValueText, y: this.scaleValueText }) // 添加缩放效果
  10419. .margin({ top:this.isCoverRectangle?10: 0 })
  10420. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  10421. }
  10422. @Builder
  10423. private PlayTitle() {
  10424. Row() {
  10425. Row() {
  10426. Image($r('app.media.ic_back_down'))
  10427. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  10428. .hitTestBehavior(HitTestMode.Transparent)
  10429. }
  10430. .layoutWeight(1)
  10431. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10432. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  10433. .onClick(() => {
  10434. this.setShowPlayFalse()
  10435. })
  10436. Column() {
  10437. AVCastPicker({
  10438. normalColor: Color.White,
  10439. onStateChange: this.onStateVastChange
  10440. })
  10441. .width(24)
  10442. .height(24)
  10443. }
  10444. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  10445. }
  10446. .width(PlayConstants.ROW_WIDTH)
  10447. }
  10448. @Builder
  10449. lyricSettingSheet(isPip: boolean) {
  10450. Scroll() {
  10451. this.lyricSetting(isPip)
  10452. }
  10453. .width('100%')
  10454. .height('100%')
  10455. }
  10456. @Builder
  10457. lyricSetting(isPip: boolean) {
  10458. Column() {
  10459. // 时间调节模块
  10460. if (!isPip) {
  10461. this.BuildTimeControls()
  10462. }
  10463. // 字号控制模块
  10464. this.BuildFontControls(isPip)
  10465. }
  10466. }
  10467. // 歌词时间偏移状态
  10468. @State timeOffset: number = 0.0
  10469. @State currentLyricColor: string = '#FFFFFF'
  10470. @State currentLyricColorPip: string = '#FFFFFF'
  10471. @State currentHighLightLyricColor: string = '#FF4081'
  10472. @State currentHighLightLyricColorPip: string = '#FF4081'
  10473. // 歌词字号状态
  10474. @State currentLyricSize: number = 20
  10475. @State currentLyricSizePip: number = 20
  10476. // 高亮歌词放大倍数
  10477. @State currentHightLyricSize: number = 1.2
  10478. @State currentHightLyricSizePip: number = 1.2
  10479. @State currentLyricLineSpace: number = 10
  10480. @State currentLyricLineSpacePip: number = 10
  10481. @State currentLyricAlignMode: number = 1
  10482. @State currentLyricAlignModePip: number = 1
  10483. @State blurDegree: number = 2
  10484. @State blurDegreePip: number = 2
  10485. @State isShowSelectColor: boolean = false
  10486. @State isShowHLSelectColor: boolean = false
  10487. @State isShowPipBgSelectColor: boolean = false
  10488. @State pipLyWidth: number = 330
  10489. @State pipLyHeight: number = 120
  10490. // 构建颜色选择器
  10491. @Builder
  10492. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  10493. Row({ space: 10 }) {
  10494. HSBColorPicker({
  10495. color: '#FFFFFF',
  10496. radius: 8,
  10497. layout: HSBColorPickerLayout.COLUMN,
  10498. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  10499. '#fa7105'],
  10500. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  10501. this.changeLyricColor(value, isPip, isBGPip)
  10502. })
  10503. .height(250)
  10504. .layoutWeight(1)
  10505. .padding(25)
  10506. }
  10507. .width('66%')
  10508. }
  10509. @State isOpenPip: boolean = false
  10510. @State pipBgIndex: number = 0
  10511. // 构建字号控制器
  10512. @Builder
  10513. BuildFontControls(isPip: boolean) {
  10514. Column() {
  10515. if (isPip) {
  10516. Column() {
  10517. Row() {
  10518. Text('悬浮歌词')
  10519. .margin({ left: 18 })
  10520. .fontSize(15)
  10521. .fontColor(Color.White)
  10522. .fontWeight(480)
  10523. .layoutWeight(1)
  10524. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  10525. .selectedColor(this.themeColor)
  10526. .switchPointColor(Color.White)
  10527. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10528. .margin({ right: 18 })
  10529. .onChange((checked: boolean) => {
  10530. this.isOpenPip = checked;
  10531. if (this.isOpenPip) {
  10532. this.startPip()
  10533. } else {
  10534. this.stopPip()
  10535. }
  10536. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  10537. })
  10538. .width(50)
  10539. .height(30);
  10540. }
  10541. .height(55)
  10542. }
  10543. .backgroundColor(Color.Transparent)
  10544. .borderRadius(15)
  10545. .margin({
  10546. left: 30,
  10547. right: 30,
  10548. top: 0,
  10549. bottom: 20
  10550. })
  10551. .padding(0)
  10552. .border({
  10553. color: Color.White,
  10554. width: 1.8
  10555. })
  10556. }else{
  10557. Column() {
  10558. Row() {
  10559. Text('显示迷你歌词')
  10560. .margin({ left: 18 })
  10561. .fontSize(15)
  10562. .fontColor(Color.White)
  10563. .fontWeight(480)
  10564. .layoutWeight(1)
  10565. Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
  10566. .selectedColor(this.themeColor)
  10567. .switchPointColor(Color.White)
  10568. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10569. .margin({ right: 18 })
  10570. .onChange((checked: boolean) => {
  10571. this.isShowSingleLineLyric = checked;
  10572. PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
  10573. })
  10574. .width(50)
  10575. .height(30);
  10576. }
  10577. .height(55)
  10578. }
  10579. .backgroundColor(Color.Transparent)
  10580. .borderRadius(15)
  10581. .margin({
  10582. left: 30,
  10583. right: 30,
  10584. top: 10,
  10585. bottom: 10
  10586. })
  10587. .padding(0)
  10588. .border({
  10589. color: Color.White,
  10590. width: 1.8
  10591. })
  10592. }
  10593. Row() {
  10594. Text(`歌词居中:`)
  10595. .fontSize(14)
  10596. .fontColor(Color.White)
  10597. .margin({ left: 2 })
  10598. Row() {
  10599. ForEach(['居中', '居左'], (size: string, index: number) => {
  10600. Button(size)
  10601. .width(60)
  10602. .height(28)
  10603. .fontSize(12)
  10604. .fontColor('#FFFFFF')
  10605. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  10606. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  10607. .border({
  10608. color: (!isPip && this.currentLyricAlignMode === index) ||
  10609. (isPip && this.currentLyricAlignModePip === index) ?
  10610. '#007DFF' : '#DDDDDD',
  10611. width: 1.8
  10612. })
  10613. .onClick(() => {
  10614. this.setLyricAlignMode(index, isPip)
  10615. })
  10616. .margin({ left: 10, right: 8 })
  10617. })
  10618. }
  10619. .width('76%')
  10620. Blank()
  10621. }
  10622. .margin({
  10623. top: 10,
  10624. bottom: 10,
  10625. right: 20,
  10626. left: 20
  10627. })
  10628. if (isPip) {
  10629. Row() {
  10630. Text(`悬浮背景:`)
  10631. .fontSize(14)
  10632. .fontColor(Color.White)
  10633. Select([
  10634. { value: CommonConstants.PIP_LYRIC_BG[0] },
  10635. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  10636. .font({ size: 13, weight: FontWeight.Medium })
  10637. .fontColor(Color.White)
  10638. .margin({ left: 10 })
  10639. .selected(this.pipBgIndex)
  10640. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  10641. .onSelect(async (_index: number, text?: string | undefined) => {
  10642. this.pipBgIndex = _index
  10643. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  10644. if (this.pipBgIndex === 0) {
  10645. if (this.cover) {
  10646. this.pipBg = this.cover
  10647. } else {
  10648. this.pipBg = this.imageColor
  10649. }
  10650. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  10651. } else {
  10652. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  10653. }
  10654. })
  10655. Column() {
  10656. }
  10657. .backgroundColor(this.pipBg)
  10658. .margin({ left: 10, right: 10 })
  10659. .borderRadius(20)
  10660. .height(28)
  10661. .width(28)
  10662. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10663. Row() {
  10664. SymbolGlyph($r('sys.symbol.paintbrush'))
  10665. .fontColor([Color.White])
  10666. .effectStrategy(1)
  10667. Text(`选择颜色`)
  10668. .fontSize(13)
  10669. .margin({ left: 10 })
  10670. .fontColor(Color.White)
  10671. }
  10672. }
  10673. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  10674. .backgroundColor(Color.Transparent)
  10675. .border({
  10676. color: '#FFFFFF',
  10677. radius: 20,
  10678. width: 1.8
  10679. })
  10680. .height(36)
  10681. .width(110)
  10682. .onClick(() => {
  10683. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  10684. })
  10685. .bindPopup(this.isShowPipBgSelectColor, {
  10686. builder: this.SelectColor(false, isPip, true),
  10687. placement: Placement.Top,
  10688. mask: { color: '#33000000' },
  10689. enableArrow: false, //是否显示箭头
  10690. showInSubWindow: false,
  10691. onStateChange: (e) => {
  10692. if (!e.isVisible) {
  10693. this.isShowPipBgSelectColor = false
  10694. }
  10695. }
  10696. })
  10697. }
  10698. .width('76%')
  10699. .margin({ bottom: 5, right: 45, left: 20 })
  10700. }
  10701. if (!isPip) {
  10702. Row() {
  10703. Text(`高亮居中:`)
  10704. .fontSize(14)
  10705. .fontColor(Color.White)
  10706. Column() {
  10707. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  10708. .selectedColor(this.themeColor)
  10709. .switchPointColor(Color.White)
  10710. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10711. .onChange((checked: boolean) => {
  10712. this.isHightLightCenter = checked;
  10713. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  10714. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  10715. })
  10716. .width(50)
  10717. .height(30)
  10718. .alignSelf(ItemAlign.Start)
  10719. .margin({ left: 12 })
  10720. Blank()
  10721. }
  10722. .width('76%')
  10723. }
  10724. .margin({
  10725. left: 20,
  10726. right: 15,
  10727. top: 10,
  10728. bottom: 10
  10729. })
  10730. }
  10731. Row() {
  10732. Text(`歌词颜色:`)
  10733. .fontSize(14)
  10734. .fontColor(Color.White)
  10735. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  10736. .fontSize(15)
  10737. .fontColor(Color.White)
  10738. .margin({ left: 12, right: 12 })
  10739. Column() {
  10740. }
  10741. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  10742. .margin({ right: 12 })
  10743. .borderRadius(20)
  10744. .height(28)
  10745. .width(28)
  10746. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10747. Row() {
  10748. SymbolGlyph($r('sys.symbol.paintbrush'))
  10749. .fontColor([Color.White])
  10750. .effectStrategy(1)
  10751. Text(`选择颜色`)
  10752. .fontSize(13)
  10753. .margin({ left: 10 })
  10754. .fontColor(Color.White)
  10755. }
  10756. }
  10757. .backgroundColor(Color.Transparent)
  10758. .border({
  10759. color: '#FFFFFF',
  10760. radius: 20,
  10761. width: 1.8
  10762. })
  10763. .height(36)
  10764. .width(110)
  10765. .onClick(() => {
  10766. this.isShowSelectColor = !this.isShowSelectColor
  10767. })
  10768. .bindPopup(this.isShowSelectColor, {
  10769. builder: this.SelectColor(false, isPip),
  10770. placement: Placement.Top,
  10771. mask: { color: '#33000000' },
  10772. enableArrow: false, //是否显示箭头
  10773. showInSubWindow: false,
  10774. onStateChange: (e) => {
  10775. if (!e.isVisible) {
  10776. this.isShowSelectColor = false
  10777. }
  10778. }
  10779. })
  10780. }
  10781. .width('76%')
  10782. .margin({
  10783. top: 10,
  10784. bottom: 10,
  10785. right: 45,
  10786. left: 20
  10787. })
  10788. Row() {
  10789. Text(`高亮颜色:`)
  10790. .fontSize(14)
  10791. .fontColor(Color.White)
  10792. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  10793. .fontSize(15)
  10794. .fontColor(Color.White)
  10795. .margin({ left: 12, right: 12 })
  10796. Column() {
  10797. }
  10798. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  10799. .margin({ right: 12 })
  10800. .borderRadius(20)
  10801. .height(28)
  10802. .width(28)
  10803. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10804. Row() {
  10805. SymbolGlyph($r('sys.symbol.paintbrush'))
  10806. .fontColor([Color.White])
  10807. .effectStrategy(1)
  10808. Text(`选择颜色`)
  10809. .fontSize(13)
  10810. .margin({ left: 10 })
  10811. .fontColor(Color.White)
  10812. }
  10813. }
  10814. .backgroundColor(Color.Transparent)
  10815. .border({
  10816. color: '#FFFFFF',
  10817. radius: 20,
  10818. width: 1.8
  10819. })
  10820. .height(36)
  10821. .width(110)
  10822. .onClick(() => {
  10823. this.isShowHLSelectColor = !this.isShowHLSelectColor
  10824. })
  10825. .bindPopup(this.isShowHLSelectColor, {
  10826. builder: this.SelectColor(true, isPip),
  10827. placement: Placement.Top,
  10828. mask: { color: '#33000000' },
  10829. enableArrow: false, //是否显示箭头
  10830. showInSubWindow: false,
  10831. onStateChange: (e) => {
  10832. if (!e.isVisible) {
  10833. this.isShowHLSelectColor = false
  10834. }
  10835. }
  10836. })
  10837. }
  10838. .width('76%')
  10839. .margin({
  10840. top: 10,
  10841. bottom: 10,
  10842. right: 45,
  10843. left: 20
  10844. })
  10845. if (isPip) {
  10846. Row() {
  10847. Text(`显示宽度:`)
  10848. .fontSize(14)
  10849. .fontColor(Color.White)
  10850. Slider({
  10851. value: this.pipLyWidth,
  10852. min: 10,
  10853. max: 800,
  10854. step: 1,
  10855. style: SliderStyle.OutSet
  10856. })
  10857. .blockColor(this.themeColor)
  10858. .trackColor($r('app.color.speed_text_color'))
  10859. .selectedColor(Color.White)
  10860. .trackThickness(6)
  10861. .onChange((value: number) => {
  10862. this.pipLyWidth = value
  10863. if (this.pipController) {
  10864. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  10865. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  10866. }
  10867. })
  10868. .width('76%')
  10869. }
  10870. .margin({
  10871. left: 20,
  10872. right: 15,
  10873. top: 5,
  10874. bottom: 5
  10875. })
  10876. Row() {
  10877. Text(`显示高度:`)
  10878. .fontSize(14)
  10879. .fontColor(Color.White)
  10880. Slider({
  10881. value: this.pipLyHeight,
  10882. min: 10,
  10883. max: 1000,
  10884. step: 1,
  10885. style: SliderStyle.OutSet
  10886. })
  10887. .blockColor(this.themeColor)
  10888. .trackColor($r('app.color.speed_text_color'))
  10889. .selectedColor(Color.White)
  10890. .trackThickness(6)
  10891. .onChange((value: number) => {
  10892. this.pipLyHeight = value
  10893. if (this.pipController) {
  10894. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  10895. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  10896. }
  10897. })
  10898. .width('76%')
  10899. }
  10900. .margin({
  10901. left: 20,
  10902. right: 15,
  10903. top: 5,
  10904. bottom: 5
  10905. })
  10906. }
  10907. Row() {
  10908. Text(`歌词字号:`)
  10909. .fontSize(14)
  10910. .fontColor(Color.White)
  10911. Slider({
  10912. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  10913. min: 12,
  10914. max: 30,
  10915. step: 0.1,
  10916. style: SliderStyle.OutSet
  10917. })
  10918. .blockColor(this.themeColor)
  10919. .trackColor($r('app.color.speed_text_color'))
  10920. .selectedColor(Color.White)
  10921. .trackThickness(6)
  10922. .onChange((value: number) => {
  10923. this.setLyricTextSize(value, isPip)
  10924. })
  10925. .width('76%')
  10926. }
  10927. .margin({
  10928. left: 20,
  10929. right: 15,
  10930. top: 5,
  10931. bottom: 5
  10932. })
  10933. Row() {
  10934. Text(`高亮倍数:`)
  10935. .fontSize(14)
  10936. .fontColor(Color.White)
  10937. Slider({
  10938. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  10939. min: 1,
  10940. max: 2,
  10941. step: 0.1,
  10942. style: SliderStyle.OutSet
  10943. })
  10944. .blockColor(this.themeColor)
  10945. .trackColor($r('app.color.speed_text_color'))
  10946. .selectedColor(Color.White)
  10947. .trackThickness(6)
  10948. .onChange((value: number) => {
  10949. this.setHighLyricTextSize(value, isPip)
  10950. })
  10951. .width('76%')
  10952. }
  10953. .margin({
  10954. left: 20,
  10955. right: 15,
  10956. top: 5,
  10957. bottom: 5
  10958. })
  10959. Row() {
  10960. Text(`歌词间隙:`)
  10961. .fontSize(14)
  10962. .fontColor(Color.White)
  10963. Slider({
  10964. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  10965. min: 0,
  10966. max: 100,
  10967. step: 1,
  10968. style: SliderStyle.OutSet
  10969. })
  10970. .blockColor(this.themeColor)
  10971. .trackColor($r('app.color.speed_text_color'))
  10972. .selectedColor(Color.White)
  10973. .trackThickness(6)
  10974. .onChange((value: number) => {
  10975. this.setLyricLineSpace(value, isPip)
  10976. })
  10977. .width('76%')
  10978. }
  10979. .margin({
  10980. left: 20,
  10981. right: 15,
  10982. top: 5,
  10983. bottom: 5
  10984. })
  10985. //取值间隔为100,默认为400,取值越大,字体越粗
  10986. Row() {
  10987. Text(`歌词字重:`)
  10988. .fontSize(14)
  10989. .fontColor(Color.White)
  10990. Slider({
  10991. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  10992. min: 100,
  10993. max: 900,
  10994. step: 100,
  10995. style: SliderStyle.OutSet
  10996. })
  10997. .blockColor(this.themeColor)
  10998. .trackColor($r('app.color.speed_text_color'))
  10999. .selectedColor(Color.White)
  11000. .trackThickness(6)
  11001. .onChange((value: number) => {
  11002. if (isPip) {
  11003. this.lyricTextWeightPip = value
  11004. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  11005. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  11006. } else {
  11007. this.lyricTextWeight = value
  11008. this.lyricController.setTextWeight(this.lyricTextWeight)
  11009. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  11010. }
  11011. })
  11012. .width('76%')
  11013. }
  11014. .margin({
  11015. left: 20,
  11016. right: 15,
  11017. top: 5,
  11018. bottom: 5
  11019. })
  11020. Row() {
  11021. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  11022. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  11023. // this.pushLyricButton($r('app.media.white_search'), 1, '繁体转简体')
  11024. }
  11025. .justifyContent(FlexAlign.Center)
  11026. .margin({ top: 3, bottom: 10 })
  11027. }
  11028. }
  11029. private setBlurDegree(index: number, isPip: boolean) {
  11030. if (isPip) {
  11031. this.blurDegreePip = index
  11032. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  11033. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  11034. } else {
  11035. this.blurDegree = index
  11036. this.lyricController.setBlurDegree(this.blurDegree)
  11037. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  11038. }
  11039. }
  11040. private setLyricAlignMode(index: number, isPip: boolean) {
  11041. if (isPip) {
  11042. this.currentLyricAlignModePip = index
  11043. if (this.currentLyricAlignModePip === 1) {
  11044. this.lyricControllerXF.setAlignMode("left")
  11045. } else {
  11046. this.lyricControllerXF.setAlignMode("center")
  11047. }
  11048. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  11049. } else {
  11050. this.currentLyricAlignMode = index
  11051. if (this.currentLyricAlignMode === 1) {
  11052. this.lyricController.setAlignMode("left")
  11053. } else {
  11054. this.lyricController.setAlignMode("center")
  11055. }
  11056. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  11057. }
  11058. }
  11059. private setLyricTextSize(index: number, isPip: boolean) {
  11060. if (isPip) {
  11061. this.currentLyricSizePip = index
  11062. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  11063. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  11064. } else {
  11065. this.currentLyricSize = index
  11066. this.lyricController.setTextSize(this.currentLyricSize)
  11067. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  11068. }
  11069. }
  11070. private setHighLyricTextSize(scale: number, isPip: boolean) {
  11071. if (isPip) {
  11072. this.currentHightLyricSizePip = scale
  11073. this.lyricControllerXF
  11074. .setHighlightScale(this.currentHightLyricSizePip)
  11075. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  11076. } else {
  11077. this.currentHightLyricSize = scale
  11078. this.lyricController
  11079. .setHighlightScale(this.currentHightLyricSize)
  11080. PreferencesUtil.putSync('HighLyricTextSize', scale)
  11081. }
  11082. }
  11083. private setLyricLineSpace(index: number, isPip: boolean) {
  11084. if (isPip) {
  11085. this.currentLyricLineSpacePip = index
  11086. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  11087. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  11088. } else {
  11089. this.currentLyricLineSpace = index
  11090. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  11091. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  11092. }
  11093. }
  11094. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  11095. LogUtil.info('onecold isBG = ' + isBG)
  11096. if (isBG) { //如果是设置悬浮背景
  11097. this.pipBg = color
  11098. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  11099. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  11100. return
  11101. }
  11102. if (isPip) {
  11103. this.currentLyricColorPip = color
  11104. this.lyricControllerXF
  11105. .setTextColor(this.currentLyricColorPip)
  11106. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  11107. } else {
  11108. this.currentLyricColor = color
  11109. this.lyricController
  11110. .setTextColor(this.currentLyricColor)
  11111. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  11112. }
  11113. }
  11114. private changeLyricHightLightColor(color: string, isPip: boolean) {
  11115. if (isPip) {
  11116. this.currentHighLightLyricColorPip = color
  11117. this.lyricControllerXF
  11118. .setHighlightColor(this.currentHighLightLyricColorPip)
  11119. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  11120. } else {
  11121. this.currentHighLightLyricColor = color
  11122. this.lyricController
  11123. .setHighlightColor(this.currentHighLightLyricColor)
  11124. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  11125. }
  11126. }
  11127. // 构建时间控制器
  11128. @Builder
  11129. BuildTimeControls() {
  11130. Column() {
  11131. // 时间显示
  11132. Text(this.getTimeText())
  11133. .fontSize(18)
  11134. .fontColor(Color.White)
  11135. .margin({ bottom: 10 })
  11136. Row() {
  11137. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  11138. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  11139. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  11140. }
  11141. .justifyContent(FlexAlign.Center)
  11142. }
  11143. .margin({ top: 12, bottom: 8 })
  11144. }
  11145. // 精度按钮组件
  11146. @Builder
  11147. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  11148. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  11149. Column() {
  11150. Image(icon)
  11151. .width(28)
  11152. .margin({ bottom: 5 })
  11153. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  11154. Text(label)
  11155. .fontSize(12)
  11156. .fontColor('#FFFFFF')
  11157. }
  11158. }
  11159. .backgroundColor(Color.Transparent)
  11160. .enabled(!this.isButtonDisabled(step))
  11161. .onClick(() => this.handlePrecisionAdjust(step))
  11162. .padding(5)
  11163. .width(66)
  11164. .height(66)
  11165. .margin({ left: 18, right: 18 })
  11166. .border({
  11167. color: '#FFFFFF',
  11168. width: 1.8
  11169. })
  11170. }
  11171. private handlePrecisionAdjust(step: number) {
  11172. if (step === 0) {
  11173. this.timeOffset = 0
  11174. return
  11175. }
  11176. // 精度处理:保留1位小数
  11177. const newOffset = Number((this.timeOffset + step).toFixed(5))
  11178. // 边界保护(±15.0秒)
  11179. if (newOffset < -30.0 || newOffset > 30.0) {
  11180. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  11181. return
  11182. }
  11183. // 状态更新
  11184. this.timeOffset = newOffset
  11185. }
  11186. // 按钮禁用逻辑
  11187. private isButtonDisabled(step: number): boolean {
  11188. const futureOffset = this.timeOffset + step
  11189. return (futureOffset < -30.0) || (futureOffset > 30.0)
  11190. }
  11191. // 时间显示文本升级
  11192. private getTimeText(): string {
  11193. const absValue = Math.abs(this.timeOffset)
  11194. return this.timeOffset === 0
  11195. ? '歌词时间已重置'
  11196. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  11197. }
  11198. // 导入 本地歌词 搜索歌词
  11199. @Builder
  11200. pushLyricButton(icon: Resource, step: number, label: string) {
  11201. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  11202. Row() {
  11203. Image(icon)
  11204. .width(14)
  11205. .margin({ left: 13 })
  11206. Text(label)
  11207. .fontSize(12)
  11208. .margin({ left: 6 })
  11209. .fontColor('#FFFFFF')
  11210. }
  11211. }
  11212. .onClick(() => {
  11213. switch (step) {
  11214. case 0:
  11215. this.callFilePickerSelectFileForLyric()
  11216. break;
  11217. case 1:
  11218. //判断有没有设置api
  11219. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  11220. this.isLyricSetting = false
  11221. this.showTipsDialog()
  11222. return
  11223. }
  11224. if (StrUtil.isNotEmpty(this.videoUrl)) {
  11225. ToastUtil.showToast('正在获取')
  11226. this.isLyricSetting = false
  11227. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  11228. this.initLyric(lyricPath, true);
  11229. }
  11230. break;
  11231. }
  11232. })
  11233. .padding(5)
  11234. .width(110)
  11235. .backgroundColor(Color.Transparent)
  11236. .height(40)
  11237. .margin({ left: 6, right: 6 })
  11238. .border({
  11239. color: '#FFFFFF',
  11240. radius: 20,
  11241. width: 1.8
  11242. })
  11243. }
  11244. showVipDialog() {
  11245. DialogHelper.showCustomContentDialog({
  11246. dialogId: 'vip',
  11247. title: "友情提示",
  11248. autoCancel: false, //点击遮障层时,不关闭弹窗
  11249. backCancel: true, //点击返回键,不关闭弹窗
  11250. contentBuilder: () => {
  11251. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  11252. },
  11253. buttons: [],
  11254. })
  11255. }
  11256. //去赞助的自定义内容
  11257. @Builder
  11258. customVipBuilder(content: string) {
  11259. Column() {
  11260. Text(content)
  11261. .fontColor(Color.Gray)
  11262. .fontSize(16)
  11263. .alignSelf(ItemAlign.Start)
  11264. .margin({ bottom: 15 })
  11265. .fontSize(16)
  11266. Row() {
  11267. Button('取消')
  11268. .fontColor(Color.White)
  11269. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  11270. .height(50)
  11271. .layoutWeight(1)
  11272. .stateEffect(true)
  11273. .margin({ right: 6 })
  11274. .onClick(() => {
  11275. DialogHelper.closeDialog('vip'); //关闭弹框
  11276. })
  11277. Button('开通')
  11278. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  11279. .layoutWeight(1)
  11280. .height(50)
  11281. .backgroundColor(this.themeColor)
  11282. .stateEffect(true)
  11283. .margin({ left: 6 })
  11284. .onClick(() => {
  11285. DialogHelper.closeDialog('vip'); //关闭弹框
  11286. this.isShowPlay = false
  11287. this.mType = 1 //跳转到用户中心
  11288. // router.pushUrl({
  11289. // url: 'pages/VipPage'
  11290. // }, router.RouterMode.Single);
  11291. })
  11292. }
  11293. }
  11294. .width("100%")
  11295. .padding(10)
  11296. }
  11297. showTipsDialog() {
  11298. DialogHelper.showCustomContentDialog({
  11299. dialogId: 'tips',
  11300. title: "友情提示",
  11301. autoCancel: false, //点击遮障层时,不关闭弹窗
  11302. backCancel: true, //点击返回键,不关闭弹窗
  11303. contentBuilder: () => {
  11304. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  11305. },
  11306. buttons: [],
  11307. })
  11308. }
  11309. @Builder
  11310. customTipsBuilder(content: string) {
  11311. Column() {
  11312. Text(content)
  11313. .fontColor(Color.Gray)
  11314. .fontSize(16)
  11315. .alignSelf(ItemAlign.Start)
  11316. .margin({ bottom: 15 })
  11317. .fontSize(16)
  11318. Row() {
  11319. Button('取消')
  11320. .fontColor(Color.White)
  11321. .backgroundColor(this.themeColor)
  11322. .height(50)
  11323. .layoutWeight(1)
  11324. .stateEffect(true)
  11325. .margin({ right: 6 })
  11326. .onClick(() => {
  11327. DialogHelper.closeDialog('tips'); //关闭弹框
  11328. })
  11329. Button('跳转')
  11330. .fontColor(Color.White)//
  11331. .layoutWeight(1)
  11332. .height(50)
  11333. .backgroundColor(this.themeColor)
  11334. .stateEffect(true)
  11335. .margin({ left: 6 })
  11336. .onClick(() => {
  11337. DialogHelper.closeDialog('tips'); //关闭弹框
  11338. this.isShowEdit = false
  11339. this.longItemFilePath = ''
  11340. // if(this.isGridMusic&&!this.isShowPlay){
  11341. // this.longItemFilePath== ''
  11342. // }else{
  11343. // this.isShowEdit = false
  11344. // }
  11345. this.isShowMoreView = false;
  11346. this.isShowPlay = false
  11347. this.mType = 4
  11348. // router.pushUrl({
  11349. // url: 'pages/SettingPage'
  11350. // }, router.RouterMode.Single);
  11351. })
  11352. }
  11353. }
  11354. .width("100%")
  11355. .padding(10)
  11356. }
  11357. @Builder
  11358. PlayMoreSheet() {
  11359. Column() {
  11360. this.MoreList()
  11361. }
  11362. .width('100%')
  11363. .height('100%')
  11364. }
  11365. @Builder
  11366. MoreList() {
  11367. Scroll() {
  11368. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  11369. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  11370. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  11371. Row() {
  11372. if (more.id === 3&&this.currentSong) {
  11373. Image(more.image)
  11374. .width(24)
  11375. .height(24)
  11376. .margin({ left: 10, right: 10 })
  11377. Text(more.title)
  11378. .fontSize(16)
  11379. .fontColor(Color.White)
  11380. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  11381. height: '99%',
  11382. dragBar: true,
  11383. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11384. showClose: true,
  11385. blurStyle: BlurStyle.Thin,
  11386. backgroundColor: Color.Transparent,
  11387. title: { title: '歌曲信息' }
  11388. })
  11389. } else if (more.id === 15 && this.currentSong) { //编辑标签
  11390. Image(more.image)
  11391. .width(24)
  11392. .height(24)
  11393. .margin({ left: 10, right: 10 })
  11394. Text(more.title)
  11395. .fontSize(16)
  11396. .fontColor(Color.White)
  11397. } else if (more.id === 5) { //定时关闭
  11398. Image(more.image)
  11399. .width(24)
  11400. .height(24)
  11401. .margin({ left: 10, right: 10 })
  11402. Text(more.title)
  11403. .fontSize(16)
  11404. .fontColor(Color.White)
  11405. .onClick(() => {
  11406. this.doMore(more.id)
  11407. })
  11408. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  11409. height: this.isCoverOpacity() ? '95%' : '95%',
  11410. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11411. dragBar: true,
  11412. showClose: true,
  11413. title: { title: $r('app.string.time_close') }
  11414. })
  11415. } else if (more.id === 2) { //歌词设置
  11416. Image(more.image)
  11417. .width(24)
  11418. .height(24)
  11419. .margin({ left: 10, right: 10 })
  11420. Text(more.title)
  11421. .fontSize(16)
  11422. .fontColor(Color.White)
  11423. } else if (more.id === 16) { //悬浮歌词设置
  11424. Image(more.image)
  11425. .width(24)
  11426. .height(24)
  11427. .margin({ left: 10, right: 10 })
  11428. Text(more.title)
  11429. .fontSize(16)
  11430. .fontColor(Color.White)
  11431. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  11432. height: '99%',
  11433. dragBar: true,
  11434. preferType: SheetType.CENTER,
  11435. showClose: true,
  11436. blurStyle: BlurStyle.Thin,
  11437. backgroundColor: Color.Transparent,
  11438. title: { title: '悬浮歌词' }
  11439. })
  11440. } else if (more.id === 11) {
  11441. Image(more.image)
  11442. .width(24)
  11443. .height(24)
  11444. .margin({ left: 10, right: 10 })
  11445. Text(more.title)
  11446. .fontSize(16)
  11447. .fontColor(Color.White)
  11448. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  11449. height: this.isCoverOpacity() ? '95%' : '60%',
  11450. dragBar: true,
  11451. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11452. showClose: true,
  11453. blurStyle: BlurStyle.Thin,
  11454. backgroundColor: Color.Transparent,
  11455. title: { title: '跳过头尾' }
  11456. })
  11457. } else if (more.id === 12) { //投播
  11458. AVCastPicker({
  11459. customPicker: (): void => this.TPImageBuilder(more),
  11460. onStateChange: (state) => {
  11461. if (state == AVCastPickerState.STATE_APPEARING) {
  11462. console.log(' The picker starts showing.');
  11463. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  11464. console.log(' The picker finishes presenting.');
  11465. }
  11466. },
  11467. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  11468. sessionType: 'video'
  11469. })
  11470. .id('AVCastPicker')
  11471. } else {
  11472. Image(more.image)
  11473. .width(24)
  11474. .height(24)
  11475. .fillColor(Color.White)
  11476. .margin({ left: 10, right: 10 })
  11477. .onClick(() => {
  11478. this.doMore(more.id)
  11479. })
  11480. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  11481. .fontSize(16)
  11482. .fontColor(Color.White)
  11483. .onClick(() => {
  11484. this.doMore(more.id)
  11485. })
  11486. Select([//倍速
  11487. { value: '0.25x' },
  11488. { value: '0.5x' },
  11489. { value: '0.75x' },
  11490. { value: '1x' },
  11491. { value: '1.25x' },
  11492. { value: '1.5x' },
  11493. { value: '1.75x' },
  11494. { value: '2x' },
  11495. { value: '3x' }])
  11496. .font({ size: 16, weight: FontWeight.Medium })
  11497. .fontColor($r('sys.color.white'))
  11498. .margin({ left: 25 })
  11499. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  11500. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  11501. .value(Utility.optimizedFormat(this.playSpeed))
  11502. .onSelect(async (_index: number, text?: string | undefined) => {
  11503. let speed = parseFloat(text?.replace('x', '') || '1');
  11504. if (!CommonConstants.video_speed_list.includes(speed)) {
  11505. speed = 1;
  11506. }
  11507. this.playSpeed = speed
  11508. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  11509. })
  11510. Slider({
  11511. value: this.volume,
  11512. min: 0,
  11513. max: 1,
  11514. step: 0.1,
  11515. style: SliderStyle.OutSet
  11516. })
  11517. .margin({ left: 18, right: 8 })
  11518. .blockColor(this.themeColor)
  11519. .trackColor($r('app.color.speed_text_color'))
  11520. .selectedColor(Color.White)
  11521. .trackThickness(9)
  11522. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  11523. .onChange((value: number) => {
  11524. this.volume = value;
  11525. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  11526. PreferencesUtil.putSync('DefalutVolume',this.volume)
  11527. })
  11528. .layoutWeight(1)
  11529. Blank()
  11530. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  11531. .selectedColor(this.themeColor)
  11532. .switchPointColor(Color.White)
  11533. .margin({ right: 15 })
  11534. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11535. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  11536. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11537. if (more.id == 6) {
  11538. this.isMusicMemoryPlay = checked;
  11539. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  11540. if (this.isMusicMemoryPlay) {
  11541. ToastUtil.showToast('记忆播放已开启')
  11542. } else {
  11543. ToastUtil.showToast('记忆播放已关闭')
  11544. }
  11545. }
  11546. })
  11547. .width(48)
  11548. .height(24);
  11549. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  11550. .selectedColor(this.themeColor)
  11551. .switchPointColor(Color.White)
  11552. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11553. .margin({ right: 15 })
  11554. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  11555. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11556. if (more.id == 7) {
  11557. this.isMusicBGCover = checked;
  11558. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  11559. if (this.isMusicBGCover) {
  11560. ToastUtil.showToast('播放背景随音乐封面已开启')
  11561. } else {
  11562. ToastUtil.showToast('播放背景随音乐封面已关闭')
  11563. }
  11564. }
  11565. })
  11566. .width(48)
  11567. .height(24);
  11568. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  11569. .selectedColor(this.themeColor)
  11570. .switchPointColor(Color.White)
  11571. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11572. .margin({ right: 15 })
  11573. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  11574. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11575. if (more.id == 8) {
  11576. this.isSavePlayMode = checked;
  11577. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  11578. if (this.isSavePlayMode) {
  11579. ToastUtil.showToast('保存播放模式已开启')
  11580. } else {
  11581. ToastUtil.showToast('保存播放模式已关闭')
  11582. }
  11583. }
  11584. })
  11585. .width(48)
  11586. .height(24);
  11587. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  11588. .selectedColor(this.themeColor)
  11589. .switchPointColor(Color.White)
  11590. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11591. .margin({ right: 15 })
  11592. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  11593. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11594. if (more.id == 13) {
  11595. this.isCoverRectangle = checked;
  11596. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  11597. if (this.isCoverRectangle) {
  11598. ToastUtil.showToast('封面方形已开启')
  11599. this.animationRoFun()
  11600. } else {
  11601. ToastUtil.showToast('封面圆形已开启')
  11602. this.animationRoFun()
  11603. }
  11604. }
  11605. })
  11606. .width(48)
  11607. .height(24);
  11608. Toggle({ type: ToggleType.Switch, isOn: this.showSimple })
  11609. .selectedColor(this.themeColor)
  11610. .switchPointColor(Color.White)
  11611. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11612. .margin({ right: 15 })
  11613. .visibility(more.id == 22 ? Visibility.Visible : Visibility.None)
  11614. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11615. if (more.id == 22) {
  11616. this.showSimple = checked;
  11617. PreferencesUtil.put('showSimple', this.showSimple)
  11618. }
  11619. })
  11620. .width(48)
  11621. .height(24);
  11622. Toggle({ type: ToggleType.Switch, isOn: this.enablePointLight })
  11623. .selectedColor(this.themeColor)
  11624. .switchPointColor(Color.White)
  11625. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11626. .margin({ right: 15 })
  11627. .visibility(more.id == 23 ? Visibility.Visible : Visibility.None)
  11628. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11629. if (more.id == 23) {
  11630. this.enablePointLight = checked;
  11631. PreferencesUtil.put('enablePointLight', this.enablePointLight)
  11632. AppStorage.setOrCreate('EnablePointLight', this.enablePointLight);
  11633. }
  11634. })
  11635. .width(48)
  11636. .height(24);
  11637. Toggle({ type: ToggleType.Switch, isOn: this.isShowBgLiuGUANG })
  11638. .selectedColor(this.themeColor)
  11639. .switchPointColor(Color.White)
  11640. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11641. .margin({ right: 15 })
  11642. .visibility(more.id == 21 ? Visibility.Visible : Visibility.None)
  11643. .onChange((checked: boolean) => { // 是否开启背景流光效果
  11644. if (more.id == 21) {
  11645. this.isShowBgLiuGUANG = checked;
  11646. PreferencesUtil.putSync('isShowBgLiuGUANG',this.isShowBgLiuGUANG)
  11647. }
  11648. })
  11649. .width(48)
  11650. .height(24);
  11651. }
  11652. }
  11653. .width('100%')
  11654. .height(45)
  11655. .padding(15)
  11656. .backgroundColor(Color.Transparent)
  11657. .borderRadius(12)
  11658. .margin({ bottom: 6 })
  11659. }
  11660. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  11661. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  11662. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  11663. .backgroundColor(Color.Transparent)
  11664. .onClick(() => {
  11665. this.doMore(more.id)
  11666. })
  11667. });
  11668. }
  11669. .width('100%')
  11670. .padding(16)
  11671. }.margin({ bottom: 18 })
  11672. }
  11673. @Builder
  11674. TPImageBuilder(more: MoreItem): void {
  11675. Row() {
  11676. Image($r('app.media.tuoping'))
  11677. .width(22)
  11678. .height(22)
  11679. .margin({ left: 10, right: 10 })
  11680. Text(more.title)
  11681. .fontSize(16)
  11682. .fontColor(Color.White)
  11683. }
  11684. .width('100%')
  11685. .layoutWeight(1)
  11686. .alignItems(VerticalAlign.Center)
  11687. .justifyContent(FlexAlign.Start)
  11688. }
  11689. private moreItems: MoreItem[] = [
  11690. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  11691. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  11692. { id: 24, image: $r('app.media.equalizer'), title: '均衡器' },
  11693. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  11694. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  11695. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  11696. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  11697. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  11698. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  11699. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  11700. { id:20,image: $r("app.media.a_b"), title: 'AB循环' },
  11701. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  11702. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  11703. { id: 4, image: $r('app.media.share2'), title: '分享' },
  11704. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  11705. // { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  11706. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  11707. { id : 22, image: $r('app.media.skip'), title: '沉浸式' },
  11708. { id : 23, image: $r('app.media.more_do'), title: '点光源效果' },
  11709. { id : 21, image: $r('app.media.kp_music'), title: '背景双边流光' },
  11710. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  11711. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  11712. ];
  11713. @State isShowBgLiuGUANG: boolean = false;
  11714. @State isShowMoreView: boolean = false;
  11715. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  11716. @State isShowTimeCloseMore: boolean = false
  11717. @State isShowDetailMore: boolean = false
  11718. @State isMusicBGCover: boolean = true
  11719. @State isSavePlayMode: boolean = true
  11720. @State isLyricSetting: boolean = false
  11721. @State isJumpSetting: boolean = false
  11722. @State isShowEdit: boolean = false
  11723. @State showPipLyric: boolean = false
  11724. async setRingTone() {
  11725. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  11726. return
  11727. }
  11728. // 确定后的逻辑
  11729. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  11730. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  11731. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  11732. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  11733. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  11734. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  11735. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  11736. , this.videoUrl, this.name).then(res => {
  11737. LogUtil.info('onecold setFlag :' + res);
  11738. });
  11739. }
  11740. doMore(moreId: number) {
  11741. switch (moreId) {
  11742. case 2: //歌词
  11743. this.isLyricSetting = !this.isLyricSetting;
  11744. this.isShowMoreView = false
  11745. break;
  11746. case 3: //详情
  11747. this.isShowDetailMore = !this.isShowDetailMore;
  11748. break;
  11749. case 4: //分享
  11750. if (this.currentSong !== undefined) {
  11751. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  11752. }
  11753. this.isShowMoreView = false
  11754. break;
  11755. case 5: //定时关闭
  11756. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  11757. break;
  11758. case 10: //设为铃声
  11759. this.setRingTone()
  11760. this.isShowMoreView = false
  11761. break;
  11762. case 11: //跳过头尾
  11763. this.isJumpSetting = !this.isJumpSetting;
  11764. break;
  11765. case 13: //倍速
  11766. break;
  11767. case 14: //搜索封面
  11768. if (this.currentSong !== undefined) {
  11769. this.doSearchCover(this.currentSong)
  11770. }
  11771. this.isShowMoreView = false
  11772. break;
  11773. case 15: //编辑标签
  11774. this.initEditFields(this.currentSong)
  11775. this.tempLyricContent = this.lyricContent
  11776. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  11777. this.lyricConStr = this.tempLyricContent
  11778. }
  11779. this.isShowEdit = !this.isShowEdit;
  11780. break;
  11781. case 16: //悬浮歌词
  11782. this.showPipLyric = !this.showPipLyric;
  11783. break;
  11784. case 17: //横屏模式
  11785. if (this.isLandscape) {
  11786. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  11787. } else {
  11788. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  11789. }
  11790. this.isShowMoreView = false
  11791. break;
  11792. case 20://AB循环
  11793. this.isABSheet = !this.isABSheet
  11794. break;
  11795. case 24://均衡器
  11796. this.isEqualizerSheet = !this.isEqualizerSheet
  11797. break;
  11798. }
  11799. }
  11800. //AB循环
  11801. @State isOpenAB:boolean = false
  11802. @State jumpATime:number = 0
  11803. @State jumpBTime:number = 0
  11804. @State isABSheet:boolean = false
  11805. @State isEqualizerSheet: boolean = false
  11806. @State eqApplying: boolean = false
  11807. @State eqAppliedAt: number = 0
  11808. @State eqCurrentPresetName: string = '正常'
  11809. @State eqCurrentEnabled: boolean = false
  11810. @Builder
  11811. ABLoopSheet() {
  11812. ABLoopComptent({
  11813. jumpATime:this.jumpATime,
  11814. jumpBTime:this.jumpBTime,
  11815. onClickAItem: async ()=>{
  11816. if(this.mIjkMediaPlayer){
  11817. this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
  11818. }
  11819. },
  11820. onClickBItem: async ()=>{
  11821. if(this.mIjkMediaPlayer){
  11822. this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
  11823. if(this.jumpBTime<=this.jumpATime){
  11824. ToastUtil.showToast('设置B点时间不能小于A点时间')
  11825. this.jumpBTime = 0
  11826. }
  11827. }
  11828. },
  11829. onCancleButtonClick: async ()=>{
  11830. this.isOpenAB = false
  11831. this.isABSheet = false
  11832. },
  11833. onStartButtonClick: async ()=>{
  11834. if(this.jumpBTime<=this.jumpATime||this.stringForTime(this.jumpATime)==this.stringForTime(this.jumpBTime)){
  11835. ToastUtil.showToast('设置B点时间不能小于或等于A点时间')
  11836. return
  11837. }
  11838. this.isABSheet = false
  11839. this.startABLoop()
  11840. },
  11841. })
  11842. }
  11843. private syncEqualizerUi(): void {
  11844. const equalizerManager = EqualizerManager.getInstance();
  11845. this.eqCurrentEnabled = equalizerManager.enabled;
  11846. this.eqCurrentPresetName = equalizerManager.getPresetDisplayName(equalizerManager.currentPresetId);
  11847. if (this.CONTROL_PlayStatus === PlayStatus.INIT) {
  11848. this.eqAppliedAt = 0;
  11849. }
  11850. }
  11851. private markEqualizerApplied(): void {
  11852. const equalizerManager = EqualizerManager.getInstance();
  11853. this.eqCurrentEnabled = equalizerManager.enabled;
  11854. this.eqCurrentPresetName = equalizerManager.getPresetDisplayName(equalizerManager.currentPresetId);
  11855. this.eqAppliedAt = Date.now();
  11856. this.eqApplying = false;
  11857. }
  11858. private applyEqualizerToCurrentPlayback(): void {
  11859. if (this.eqApplying) {
  11860. return;
  11861. }
  11862. if (this.castControllerWrapper && this.isCastPlaying) {
  11863. ToastUtil.showToast('投播模式暂不支持实时均衡器');
  11864. return;
  11865. }
  11866. if (!this.currentSong || !this.mIjkMediaPlayer) {
  11867. ToastUtil.showToast('暂无可应用的播放');
  11868. return;
  11869. }
  11870. this.eqApplying = true;
  11871. try {
  11872. const equalizerManager = EqualizerManager.getInstance();
  11873. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  11874. this.markEqualizerApplied();
  11875. ToastUtil.showToast('均衡器已实时生效');
  11876. } catch (error) {
  11877. this.eqApplying = false;
  11878. Logger.warn(TAG, `heanup 应用均衡器失败: ${(error as Error).message}`);
  11879. }
  11880. }
  11881. @Builder
  11882. private EqualizerApplyStatusBar(): void {
  11883. Row() {
  11884. Column() {
  11885. Text(`均衡器:${this.eqCurrentEnabled ? '开' : '关'} · ${this.eqCurrentPresetName}`)
  11886. .fontSize(12)
  11887. .fontColor($r('app.color.text_color'))
  11888. Text(this.eqAppliedAt > 0 ? '当前播放:已生效' : '当前播放:未应用')
  11889. .fontSize(10)
  11890. .fontColor(this.eqAppliedAt > 0 ? this.themeColor : Color.Gray)
  11891. }
  11892. .alignItems(HorizontalAlign.Start)
  11893. Blank()
  11894. Button('重新应用')
  11895. .fontSize(12)
  11896. .fontColor(Color.White)
  11897. .backgroundColor('#666666')
  11898. .height(28)
  11899. .padding({ left: 14, right: 14 })
  11900. .borderRadius(14)
  11901. .enabled(!this.eqApplying && this.CONTROL_PlayStatus !== PlayStatus.INIT)
  11902. .onClick(() => {
  11903. this.applyEqualizerToCurrentPlayback();
  11904. })
  11905. }
  11906. .width('100%')
  11907. .padding({ left: 12, right: 12, top: 8, bottom: 8 })
  11908. .backgroundColor($r('app.color.settings_background_main'))
  11909. .borderRadius(12)
  11910. }
  11911. @Builder
  11912. EqualizerSheet() {
  11913. Column() {
  11914. Column() {
  11915. EqualizerViewWithCallback({
  11916. onEqualizerChanged: () => {
  11917. this.syncEqualizerUi();
  11918. if (this.mIjkMediaPlayer) {
  11919. const equalizerManager = EqualizerManager.getInstance();
  11920. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  11921. this.markEqualizerApplied();
  11922. }
  11923. }
  11924. })
  11925. }
  11926. .margin({ top: 8 })
  11927. Column() {
  11928. this.EqualizerApplyStatusBar()
  11929. }
  11930. .margin({ top: 8 })
  11931. }
  11932. .padding({ left: 12, right: 12, bottom: 20 })
  11933. .width('100%')
  11934. }
  11935. //开始AB循环
  11936. startABLoop(){
  11937. if(this.mIjkMediaPlayer){
  11938. this.seekTo(this.jumpATime+'')
  11939. this.isOpenAB = true
  11940. }
  11941. }
  11942. /**
  11943. * 切换横竖屏
  11944. *
  11945. */
  11946. setOrientation(orientation: number) {
  11947. this.windowClass.setPreferredOrientation(orientation).then(() => {
  11948. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  11949. }).catch((err: BusinessError) => {
  11950. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  11951. });
  11952. }
  11953. /**
  11954. * 画中画功能(悬浮歌词功能)
  11955. *
  11956. */
  11957. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  11958. pipController?: PiPWindow.PiPController;
  11959. navigationId: string = '';
  11960. @State curState: string = '';
  11961. @State curError: ResourceStr = '';
  11962. @State pipBg: string = '#E8E8E8'
  11963. @State buttonAction: string = '';
  11964. //开启画中画功能
  11965. async startPip() {
  11966. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  11967. if (!this.pipController) {
  11968. await this.createPipController();
  11969. }
  11970. if (!this.pipController) {
  11971. Logger.info(`[${TAG}] pipController create error`);
  11972. return;
  11973. }
  11974. await this.pipController.startPiP();
  11975. }
  11976. async stopPip() {
  11977. if (!this.pipController) {
  11978. Logger.info(`[${TAG}] pipController is not exist`);
  11979. return;
  11980. }
  11981. this.isOpenPip = false
  11982. await this.pipController.stopPiP();
  11983. }
  11984. async createPipController() {
  11985. this.pipController = await PiPWindow.create({
  11986. context: getContext(this),
  11987. componentController: this.xcomponentController,
  11988. navigationId: this.navigationId,
  11989. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  11990. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  11991. customUIController: this.nodeController,
  11992. });
  11993. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  11994. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  11995. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  11996. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  11997. this.onStateChange(state, reason);
  11998. });
  11999. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  12000. this.onActionEvent(event, status);
  12001. });
  12002. }
  12003. destroyPipController() {
  12004. if (!this.pipController) {
  12005. return;
  12006. }
  12007. this.pipController.off('stateChange');
  12008. this.pipController.off('controlPanelActionEvent');
  12009. this.pipController = undefined;
  12010. }
  12011. onStateChange(state: PiPWindow.PiPState, reason: string) {
  12012. switch (state) {
  12013. case PiPWindow.PiPState.ABOUT_TO_START:
  12014. this.curState = 'ABOUT_TO_START';
  12015. this.curError = $r('app.string.current_error_hint');
  12016. break;
  12017. case PiPWindow.PiPState.STARTED:
  12018. this.curState = 'STARTED';
  12019. this.curError = $r('app.string.current_error_hint');
  12020. break;
  12021. case PiPWindow.PiPState.ABOUT_TO_STOP:
  12022. this.curState = 'ABOUT_TO_STOP';
  12023. this.curError = $r('app.string.current_error_hint');
  12024. break;
  12025. case PiPWindow.PiPState.STOPPED:
  12026. this.curState = 'STOPPED';
  12027. this.curError = $r('app.string.current_error_hint');
  12028. this.stopPip()
  12029. this.destroyPipController()
  12030. break;
  12031. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  12032. this.curState = 'ABOUT_TO_RESTORE';
  12033. this.curError = $r('app.string.current_error_hint');
  12034. break;
  12035. case PiPWindow.PiPState.ERROR:
  12036. this.curState = 'ERROR';
  12037. this.curError = reason;
  12038. break;
  12039. default:
  12040. break;
  12041. }
  12042. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  12043. }
  12044. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  12045. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  12046. switch (event) {
  12047. case 'playbackStateChanged':
  12048. if (status === 0) {
  12049. this.pause();
  12050. } else {
  12051. console.info('onecold startPlayOrResumePlay 9869')
  12052. this.startPlayOrResumePlay();
  12053. }
  12054. break;
  12055. case 'nextVideo':
  12056. // 切换到下一个视频
  12057. this.playNext().catch(() => {
  12058. Logger.error('heanup onActionEvent playNext', `播放下一首失败`);
  12059. });
  12060. break;
  12061. case 'previousVideo':
  12062. // 切换到上一个视频
  12063. this.playPrevious().catch(() => {
  12064. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败`);
  12065. });
  12066. break;
  12067. case 'previousVideo':
  12068. // 切换到上一个视频
  12069. this.playPrevious().catch(() => {
  12070. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败:`);
  12071. });
  12072. break;
  12073. default:
  12074. }
  12075. this.buttonAction = event + `-status:${status}`;
  12076. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  12077. }
  12078. /**
  12079. * 画中画功能(悬浮歌词功能)结束
  12080. *
  12081. */
  12082. async doSearchCover(item: VideoItem,title?:string,artist?:string): Promise<string> {
  12083. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  12084. this.isShowMoreView = false;
  12085. this.showTipsDialog();
  12086. return ''; // Return empty string when no API is configured
  12087. }
  12088. if (!item) {
  12089. return ''; // Return empty string if item is undefined
  12090. }
  12091. const titleS = title||item?.name || '';
  12092. const artistS = artist||item?.artist || ''; // Use empty string if artist is missing
  12093. return this.searchCover(item, titleS, artistS); // Await is not needed here as we return the promise directly
  12094. }
  12095. /**
  12096. *api搜索封面
  12097. *item,根据title和artist
  12098. */
  12099. searchCover(item: VideoItem, title: string, artist: string): Promise<string> {
  12100. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  12101. LogUtil.debug("onecold res =" + res);
  12102. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  12103. if (item.filePath == this.currentSong?.filePath) {
  12104. this.cover = res;
  12105. if (this.currentSong) {
  12106. this.currentSong.pixelMapPath = res;
  12107. }
  12108. }
  12109. // Update pixel map path but always return res regardless of success
  12110. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  12111. if (success) {
  12112. this.doUpdateData();
  12113. console.log("onecold 更新音乐封面成功,数据库已同步");
  12114. } else {
  12115. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  12116. }
  12117. // Note: We don't resolve/reject here because we already returned res
  12118. });
  12119. LogUtil.debug("onecold this.cover =" + this.cover);
  12120. }
  12121. return res; // Always return res regardless of updatePixelMapPath result
  12122. });
  12123. }
  12124. @State jumpTopTime: number = 0
  12125. @State jumpEndTime: number = 0
  12126. @State isOpenJump: boolean = false
  12127. @Builder
  12128. JumpTopEndSheet() {
  12129. Scroll() {
  12130. Column() {
  12131. Column() {
  12132. Text('仅对本播放列表有效')
  12133. .fontSize(16)
  12134. .fontColor($r('app.color.text_color'))
  12135. // 跳过头尾
  12136. Column() {
  12137. Row() {
  12138. Text('跳过片头:')
  12139. .fontSize(16)
  12140. .fontColor($r('app.color.text_color'))
  12141. Text(this.jumpTopTime + 's')
  12142. .fontSize(16)
  12143. .fontColor($r('app.color.text_color'))
  12144. }
  12145. .margin({ bottom: 5 })
  12146. Row() {
  12147. Slider({
  12148. value: this.jumpTopTime,
  12149. min: 0,
  12150. max: 120,
  12151. step: 1,
  12152. style: SliderStyle.OutSet
  12153. })
  12154. .blockColor(this.themeColor)
  12155. .trackColor($r('app.color.speed_text_color'))
  12156. .selectedColor(Color.White)
  12157. .trackThickness(8)
  12158. .onChange((value: number) => {
  12159. this.jumpTopTime = value;
  12160. })
  12161. .width('85%')
  12162. }
  12163. .alignItems(VerticalAlign.Top)
  12164. }
  12165. .margin({ top: 10, bottom: 10 })
  12166. // 跳过头尾
  12167. Column() {
  12168. Row() {
  12169. Text('跳过片尾:')
  12170. .fontSize(16)
  12171. .fontColor($r('app.color.text_color'))
  12172. Text(this.jumpEndTime + 's')
  12173. .fontSize(16)
  12174. .fontColor($r('app.color.text_color'))
  12175. }
  12176. .margin({ bottom: 5 })
  12177. Row() {
  12178. Slider({
  12179. value: this.jumpEndTime,
  12180. min: 0,
  12181. max: 120,
  12182. step: 1,
  12183. style: SliderStyle.OutSet
  12184. })
  12185. .blockColor(this.themeColor)
  12186. .trackColor($r('app.color.speed_text_color'))
  12187. .selectedColor(Color.White)
  12188. .trackThickness(8)
  12189. .onChange((value: number) => {
  12190. this.jumpEndTime = value;
  12191. })
  12192. .width('85%')
  12193. }
  12194. .alignItems(VerticalAlign.Top)
  12195. }
  12196. .margin({ top: 10, bottom: 10 })
  12197. Row() {
  12198. Button('保存设置')
  12199. .fontColor(Color.White)
  12200. .layoutWeight(1)
  12201. .height(40)
  12202. .width(80)
  12203. .backgroundColor(this.themeColor)
  12204. .stateEffect(true)
  12205. .margin({ left: 0, bottom: 20 })
  12206. .onClick(async () => {
  12207. if (!Utility.isNoble()) {
  12208. this.isJumpSetting = false
  12209. this.isShowMoreView = false
  12210. this.showVipDialog()
  12211. return
  12212. }
  12213. if (this.currentSong === undefined) {
  12214. return
  12215. }
  12216. if (this.modeType === 0) {
  12217. let parentPath = FileUtil.getParentPath(this.videoUrl)
  12218. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  12219. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  12220. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  12221. } else if (this.modeType === 1) { //媒体库
  12222. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  12223. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  12224. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  12225. } else if (this.modeType === 2) { //艺术家
  12226. if (this.currentSong?.artist) {
  12227. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  12228. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  12229. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  12230. }
  12231. } else if (this.modeType === 3) { //专辑
  12232. if (this.currentSong?.album) {
  12233. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  12234. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  12235. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  12236. }
  12237. }
  12238. ToastUtil.showShort("保存成功")
  12239. this.isJumpSetting = false
  12240. })
  12241. }
  12242. .margin({
  12243. left: 38,
  12244. right: 38,
  12245. top: 10,
  12246. bottom: 10
  12247. })
  12248. .width(120)
  12249. .height(50)
  12250. }
  12251. }
  12252. }
  12253. .width('100%')
  12254. .height('100%')
  12255. }
  12256. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  12257. private onStateVastChange(state: AVCastPickerState) {
  12258. if (state == AVCastPickerState.STATE_APPEARING) {
  12259. console.log('The picker starts showing.');
  12260. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  12261. console.log('The picker finishes presenting.');
  12262. }
  12263. }
  12264. private showSelectLyric() {
  12265. DialogHelper.showActionSheetDialog({
  12266. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  12267. // sheets: ["本地歌词", "搜索歌词"],
  12268. sheets: [
  12269. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  12270. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  12271. ],
  12272. maskColor: Color.Transparent,
  12273. backgroundColor: $r('app.color.bg_card'),
  12274. transition: AnimationHelper.transitionInDown(666),
  12275. onAction: (index) => {
  12276. switch (index) {
  12277. case 0:
  12278. this.callFilePickerSelectFileForLyric()
  12279. break;
  12280. case 1:
  12281. if (StrUtil.isNotEmpty(this.videoUrl)) {
  12282. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  12283. this.initLyric(lyricPath);
  12284. }
  12285. break;
  12286. }
  12287. }
  12288. })
  12289. }
  12290. // 拉起picker选择文件管理器
  12291. async callFilePickerSelectFileForLyric(): Promise<void> {
  12292. try {
  12293. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  12294. DocumentSelectOptions.maxSelectNumber = 1
  12295. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  12296. let documentPicker = new picker.DocumentViewPicker();
  12297. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  12298. Logger.info(TAG,
  12299. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  12300. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  12301. this.saveVideoDatasLyric(DocumentSelectResult)
  12302. }
  12303. }).catch((err: BusinessError) => {
  12304. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  12305. });
  12306. } catch (err) {
  12307. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  12308. }
  12309. }
  12310. async saveVideoDatasLyric(uris: string[]) {
  12311. if (ArrayUtil.isEmpty(uris)) {
  12312. return
  12313. }
  12314. let newUris: string[] = [];
  12315. for (let i = 0; i < uris.length; i++) {
  12316. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  12317. Logger.info(TAG, 'filePath uri: ' + filePath);
  12318. newUris.push(filePath)
  12319. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  12320. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  12321. fileIo.copyFileSync(file.fd, file2.fd)
  12322. fileIo.closeSync(file);
  12323. fileIo.closeSync(file2);
  12324. this.initLyric(filePath,false,false,true)
  12325. }
  12326. }
  12327. private initDelayPlay(context: object) {
  12328. this.mContext = context;
  12329. }
  12330. startPipLyric() {
  12331. if (this.pipController) {
  12332. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  12333. PiPWindow.PiPControlStatus.PLAY);
  12334. }
  12335. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  12336. if (this.isOpenPip) {
  12337. this.startPip()
  12338. } else {
  12339. this.stopPip()
  12340. }
  12341. }
  12342. //startOffset 从cue分轨时间开始播
  12343. private startPlayOrResumePlay(startOffset?:number) {
  12344. //新版本ijkplayer可以直接播放dsf歌,不需要转格式了。所以注释掉代码
  12345. //针对dsf文件高采样率,统一转wav播放
  12346. // const sampleRate = this.currentSong?.sampleRate||0
  12347. // if(this.videoUrl.toLowerCase().endsWith('.dsf')&&sampleRate>=441000){
  12348. // console.info('onecold 采样率 ='+sampleRate)
  12349. // let newDsfPath = this.context.filesDir + '/'+FileUtil.getFileName(this.videoUrl)+'.wav'
  12350. // console.info('onecold newDsfPath ='+newDsfPath)
  12351. // if(!FileUtil.accessSync(newDsfPath)){
  12352. // const task = new taskpool.Task(convertDsfToWav,this.videoUrl,newDsfPath);
  12353. // taskpool.execute(task, taskpool.Priority.HIGH).then((data)=>{
  12354. // this.videoUrl = newDsfPath
  12355. // this.startPlay(startOffset)
  12356. // }).catch((e:object)=>{
  12357. // console.info("task1 catch e: " + e);
  12358. // })
  12359. // }else{
  12360. // this.videoUrl = newDsfPath
  12361. // this.startPlay(startOffset)
  12362. // }
  12363. //
  12364. // }else{
  12365. // this.startPlay(startOffset)
  12366. // }
  12367. this.startPlay(startOffset)
  12368. // 仅当前播放的是网盘歌曲时,才提前缓存下一首
  12369. // 排除用户拖动进度条的情况
  12370. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !this.isSeekTo) {
  12371. void this.preloadNextSongInternal();
  12372. }
  12373. }
  12374. startPlay(startOffset?:number) {
  12375. this.startPipLyric()
  12376. this.mDestroyPage = false;
  12377. this.animationState = AnimationStatus.Running
  12378. LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  12379. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  12380. this.stopProgressTask();
  12381. this.startProgressTask();
  12382. // 判断是否是HTTP或在线网盘视频,显示加载进度
  12383. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  12384. this.isPlayerLoading = true;
  12385. }
  12386. this.play(this.videoUrl.toString(),startOffset);
  12387. }
  12388. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  12389. this.mIjkMediaPlayer.start();
  12390. this.setProgress()
  12391. this.CONTROL_PlayStatus = PlayStatus.PLAY
  12392. }
  12393. this.setIsPlaying(true)
  12394. this.updateSessionPlayState(true)
  12395. this.watchStatus();
  12396. this.updateLastPlayTimeStr(this.videoUrl)
  12397. }
  12398. updateLastPlayTimeStr(filePath: string) {
  12399. // 检查是否为网络音频(WebDAV),如果是则不更新本地数据库
  12400. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  12401. Logger.info(`heanup 检测到网络音频播放,跳过数据库更新: ${filePath}`)
  12402. return;
  12403. }
  12404. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  12405. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  12406. if (success) {
  12407. this.getHistoryList(false)
  12408. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  12409. } else {
  12410. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  12411. }
  12412. });
  12413. }
  12414. private completionNum(num: number): string | number {
  12415. if (num < 10) {
  12416. return '0' + num;
  12417. } else {
  12418. return num;
  12419. }
  12420. }
  12421. private parseDurationToMs(duration?: string): number {
  12422. if (!duration) {
  12423. return 0;
  12424. }
  12425. const parts = duration.split(':').map((item) => Number(item));
  12426. if (parts.some((item) => Number.isNaN(item))) {
  12427. return 0;
  12428. }
  12429. if (parts.length === 2) {
  12430. return Math.floor((parts[0] * 60 + parts[1]) * 1000);
  12431. }
  12432. if (parts.length === 3) {
  12433. return Math.floor((parts[0] * 3600 + parts[1] * 60 + parts[2]) * 1000);
  12434. }
  12435. return 0;
  12436. }
  12437. private stringForTime(timeMs: number): string {
  12438. let totalSeconds: number | string = (timeMs / 1000);
  12439. let newSeconds: number | string = totalSeconds % 60;
  12440. let minutes: number | string = (totalSeconds / 60) % 60;
  12441. let hours: number | string = totalSeconds / 3600;
  12442. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  12443. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  12444. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  12445. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  12446. if (this.isCurrentTime) {
  12447. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  12448. this.oldSeconds = newSeconds
  12449. } else {
  12450. newSeconds = this.oldSeconds
  12451. }
  12452. }
  12453. newSeconds = this.completionNum(newSeconds);
  12454. if (hours > 0) {
  12455. return hours + ":" + minutes + ":" + newSeconds;
  12456. } else {
  12457. return minutes + ":" + newSeconds;
  12458. }
  12459. }
  12460. private setProgress() {
  12461. if (this.castControllerWrapper && this.isCastPlaying) {
  12462. return;
  12463. }
  12464. let position = this.mIjkMediaPlayer.getCurrentPosition();
  12465. let duration = this.mIjkMediaPlayer.getDuration();
  12466. if (duration <= 0 && this.duration > 0) {
  12467. duration = this.duration;
  12468. }
  12469. let pos = 0;
  12470. if (duration > 0) {
  12471. this.slideEnable = true;
  12472. let curPercent = position / duration;
  12473. pos = curPercent * 100;
  12474. if (pos > this.PROGRESS_MAX_VALUE) {
  12475. this.progressValue = this.PROGRESS_MAX_VALUE
  12476. } else {
  12477. this.progressValue = pos;
  12478. }
  12479. }
  12480. // LogUtils.getInstance()
  12481. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  12482. this.totalTime = this.stringForTime(duration);
  12483. if (position > duration) {
  12484. position = duration;
  12485. }
  12486. this.isCurrentTime = true;
  12487. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  12488. if(this.showPipLyric){
  12489. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000);
  12490. }
  12491. if(this.isShowSingleLineLyric){
  12492. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000);
  12493. }
  12494. this.currentTime = this.stringForTime(position);
  12495. this.isCurrentTime = false
  12496. if (this.mIjkMediaPlayer.isPlaying()) {
  12497. //如果是开启AB循环
  12498. if(this.isOpenAB){
  12499. if(position >=this.jumpBTime){
  12500. this.seekTo(this.jumpATime+'')
  12501. return
  12502. }
  12503. }
  12504. // 判断是否播放到结束时间
  12505. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  12506. if (position >= duration - this.jumpEndTime * 1000) {
  12507. if(this.playType == 1){//跳过尾部如果是单曲循环就选择单曲循环
  12508. this.CONTROL_PlayStatus = PlayStatus.INIT
  12509. this.startPlayOrResumePlay();
  12510. }else if (this.playType == 2) { //2:正常播放,单曲播完
  12511. this.showRePlay();
  12512. this.currentTime = this.stringForTime(this.mIjkMediaPlayer.getDuration());
  12513. this.progressValue = this.PROGRESS_MAX_VALUE;
  12514. this.slideEnable = false;
  12515. this.stop();
  12516. // ToastUtil.showToast('开始重新播放')
  12517. }else{
  12518. this.playNext().catch(() => {
  12519. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  12520. });
  12521. }
  12522. }
  12523. }
  12524. }
  12525. }
  12526. private startProgressTask() {
  12527. let that = this;
  12528. this.updateProgressTimer = setInterval(() => {
  12529. //LogUtils.getInstance().LOGI("startProgressTask");
  12530. if (!that.mDestroyPage) {
  12531. that.setProgress();
  12532. }
  12533. }, 300);
  12534. }
  12535. private stopProgressTask() {
  12536. LogUtils.getInstance().LOGI("stopProgressTask");
  12537. clearInterval(this.updateProgressTimer);
  12538. }
  12539. private showLoadIng() {
  12540. this.loadingVisible = Visibility.Visible;
  12541. this.replayVisible = Visibility.None;
  12542. }
  12543. private hideLoadIng() {
  12544. this.loadingVisible = Visibility.None;
  12545. this.replayVisible = Visibility.None;
  12546. }
  12547. private showRePlay() {
  12548. this.loadingVisible = Visibility.None;
  12549. this.replayVisible = Visibility.Visible;
  12550. }
  12551. private async play(url: string,startOffset?:number) {
  12552. this.isShowBgLiuGUANG = PreferencesUtil.getBooleanSync('isShowBgLiuGUANG', false)
  12553. console.info('onecold this.url 1= '+url)
  12554. if(!url.toLowerCase().startsWith('http')){
  12555. let hasPermission = await PermissionUtil.activatePermission(url)
  12556. console.info('onecold this.hasPermission 1= '+hasPermission)
  12557. if(!url.includes(this.packName)){
  12558. const file = fs.openSync(url)
  12559. this.videoUrl = file.path
  12560. url= this.videoUrl
  12561. }
  12562. console.info('onecold this.hasPermission 1= '+hasPermission)
  12563. console.info('onecold this.videoUrl 1= '+this.videoUrl)
  12564. }
  12565. let that = this;
  12566. that.showLoadIng();
  12567. this.isOpenAB = false
  12568. //设置XComponent回调的context
  12569. if (!!this.mContext) {
  12570. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  12571. }
  12572. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  12573. this.mIjkMediaPlayer.reset();
  12574. }
  12575. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  12576. //设置debug模式(用于EQ日志采集)
  12577. this.mIjkMediaPlayer.setDebug(true);
  12578. //初始化配置
  12579. this.mIjkMediaPlayer.native_setup();
  12580. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  12581. if(this.volumeSmall){
  12582. if(this.videoUrl.toLowerCase().endsWith('.dsf')){
  12583. this.mIjkMediaPlayer.setVolume('1', '1');
  12584. }else{
  12585. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  12586. }
  12587. }else{
  12588. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  12589. }
  12590. // 构建规范的HTTP请求头(统一一次性设置,避免未带认证提前发起连接)
  12591. const headers = new Map<string, string>();
  12592. headers.set("User-Agent", "TTMusic-WebDAV/1.0");
  12593. headers.set("Accept", "*/*");
  12594. if (this.currentSong&&StrUtil.isEmpty(this.currentSong.pixelMapPath)
  12595. &&PreferencesUtil.getStringSync('COVER_API', '') != '') {
  12596. //如果封面为空,则搜索封面
  12597. this.searchCover(this.currentSong, this.currentSong.name, this.currentSong.artist||'')
  12598. }
  12599. // 如果是WebDAV网络音频,使用webdav_account_id获取认证信息(等待完成后再设置一次性头部)
  12600. // SMB类型通过本地HTTP代理播放,不需要认证头,排除SMB和百度类型
  12601. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !isBaiduType(this.currentSong.type) && !isSmbType(this.currentSong.type)) {
  12602. Logger.info(`heanup WebDAV歌曲认证 - 歌曲名: ${this.currentSong.name}, webdav_account_id: ${this.currentSong.webdav_account_id || '未设置'}`);
  12603. if (this.currentSong.webdav_account_id) {
  12604. try {
  12605. const webdavManager = RemoteDriveManager.getInstance();
  12606. const webDavHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  12607. if (webDavHeaders && webDavHeaders.size > 0) {
  12608. webDavHeaders.forEach((value, key) => headers.set(key, value));
  12609. Logger.info(`heanup 成功通过webdav_account_id获取并合并WebDAV认证头`);
  12610. } else {
  12611. Logger.warn(`heanup 通过webdav_account_id获取认证头失败,播放可能无法继续`);
  12612. }
  12613. } catch (error) {
  12614. const err = error as Error;
  12615. Logger.error(`heanup 获取WebDAV认证头时出错: ${err.message}`);
  12616. }
  12617. } else {
  12618. Logger.error(`heanup WebDAV歌曲 "${this.currentSong.name}" 缺少webdav_account_id,无法进行认证`);
  12619. }
  12620. } else if (this.currentSong && isSmbType(this.currentSong.type)) {
  12621. Logger.info(`heanup SMB歌曲通过HTTP代理播放,无需认证头`);
  12622. }
  12623. // 统一设置带认证的请求头
  12624. // 百度类型也需要特殊请求头
  12625. if (this.currentSong && isBaiduType(this.currentSong.type)) {
  12626. try {
  12627. const webdavManager = RemoteDriveManager.getInstance();
  12628. const baiduHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  12629. baiduHeaders.forEach((value, key) => headers.set(key, value));
  12630. const headerSnapshot: Record<string, string> = {};
  12631. headers.forEach((value, key) => headerSnapshot[key] = value);
  12632. Logger.info(TAG, `Baidu播放请求头: ${JSON.stringify(headerSnapshot)}`);
  12633. } catch (error) {
  12634. Logger.error(`heanup 构建百度请求头失败: ${(error as Error).message}`);
  12635. }
  12636. }
  12637. //设置视频源(先准备好认证头,再设置数据源)
  12638. Logger.info(TAG, `IjkPlayer setDataSource url=${url}`);
  12639. this.mIjkMediaPlayer.setDataSource(url);
  12640. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  12641. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !isBaiduType(this.currentSong.type)) {
  12642. console.log(`heanup 为WebDAV播放设置IjkPlayer选项`);
  12643. // 网络超时设置(单位:微秒,文档显示应该是字符串格式)
  12644. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "30000000"); // 30秒
  12645. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "30000000"); // 连接超时30秒
  12646. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "listen_timeout", "30000000"); // 监听超时30秒
  12647. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "30000000"); // DNS缓存超时30秒
  12648. // 缓冲和播放优化设置
  12649. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "1024000"); // 增大缓冲区
  12650. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "50"); // 减少最小帧数
  12651. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1"); // 预加载启动
  12652. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0"); // 无缓冲播放
  12653. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "30000"); // 最大缓存30秒
  12654. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1"); // 无限制收流
  12655. // 网络相关设置
  12656. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1"); // 启用HTTP重定向
  12657. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", "TTMusic-WebDAV/1.0"); // 用户代理
  12658. // 重连设置
  12659. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "reconnect", "3"); // 重连3次
  12660. console.log(`heanup WebDAV IjkPlayer选项设置完成`);
  12661. } else if (this.currentSong && isBaiduType(this.currentSong.type)) {
  12662. console.log(`heanup 为百度网盘播放设置IjkPlayer选项`);
  12663. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "15000000");
  12664. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "15000000");
  12665. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1");
  12666. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "1");
  12667. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "2097152");
  12668. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "25");
  12669. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", BaiduConstants.USER_AGENT);
  12670. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", "3");
  12671. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http-detect-range-support", "1");
  12672. console.log(`heanup 百度网盘 IjkPlayer 选项设置完成`);
  12673. }
  12674. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  12675. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  12676. // }
  12677. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  12678. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  12679. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  12680. let bufferSize = 50 * 1024 ; // 默认缓冲区大小为1MB
  12681. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  12682. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  12683. //停止预读的最小帧数
  12684. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  12685. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  12686. // 设置其他缓冲相关选项
  12687. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  12688. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  12689. //启动预加载
  12690. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
  12691. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  12692. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  12693. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  12694. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  12695. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  12696. // 因此需要播放器丢包,才不会累积延时
  12697. // 这个和第三个参数packet-buffering无关。
  12698. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  12699. // 无限制收流
  12700. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  12701. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  12702. // 屏幕常亮
  12703. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  12704. // 开启hls起播优化 默认是关闭的
  12705. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "fetch_first", "on");
  12706. // 设置超时
  12707. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  12708. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  12709. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  12710. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  12711. // 变速播放
  12712. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  12713. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  12714. let Speed = this.mIjkMediaPlayer.getSpeed()
  12715. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  12716. //是否开启循环播放
  12717. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  12718. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = new ImplOnVideoSizeChangedListener(
  12719. (width: number, height: number, sar_num: number, sar_den: number) => {
  12720. if (height === 0) {
  12721. return;
  12722. }
  12723. const va = width / height;
  12724. const vpa = that.videoParentAspectRatio;
  12725. if (vpa > va) {
  12726. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  12727. } else {
  12728. that.videoWidth = '100%';
  12729. }
  12730. if (width && height) {
  12731. that.videoAspectRatio = width / height;
  12732. }
  12733. LogUtils.getInstance()
  12734. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  12735. that.hideLoadIng();
  12736. }
  12737. );
  12738. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  12739. let mOnPreparedListener: OnPreparedListener = new ImplOnPreparedListener(
  12740. async () => {
  12741. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  12742. // 隐藏加载进度
  12743. this.isPlayerLoading = false;
  12744. try {
  12745. //保存碰一碰分享的当前的歌曲
  12746. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  12747. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  12748. await this.initLyric(lyricPath);
  12749. const applyDuration = (durationMs: number): void => {
  12750. if (durationMs <= 0) {
  12751. return;
  12752. }
  12753. this.duration = durationMs;
  12754. this.durationTime = Math.floor(durationMs / 1000);
  12755. this.durationStringTime = secondToTime(this.durationTime);
  12756. this.totalTime = this.stringForTime(durationMs);
  12757. if (this.currentSong) {
  12758. this.currentSong.duration = this.totalTime;
  12759. try {
  12760. this.avSessionController.setAVMetadataMusic(this.currentSong, durationMs, this.lyricContent);
  12761. } catch (metaError) {
  12762. Logger.warn(TAG, `heanup 首次播放写入AVSession失败: ${(metaError as Error).message}`);
  12763. }
  12764. }
  12765. };
  12766. const fetchBaiduM3u8Duration = async (url: string): Promise<number> => {
  12767. if (!url || !isBaiduType(this.currentSong?.type ?? -1)) {
  12768. return 0;
  12769. }
  12770. const httpRequest = http.createHttp();
  12771. try {
  12772. const response = await httpRequest.request(url, {
  12773. method: http.RequestMethod.GET,
  12774. connectTimeout: 8000,
  12775. readTimeout: 8000,
  12776. expectDataType: http.HttpDataType.STRING,
  12777. header: {
  12778. 'User-Agent': BaiduConstants.STREAMING_USER_AGENT,
  12779. 'Host': 'pan.baidu.com',
  12780. 'Referer': 'https://pan.baidu.com/disk/home',
  12781. 'Accept-Encoding': 'identity'
  12782. }
  12783. });
  12784. if (response.responseCode !== 200 || typeof response.result !== 'string') {
  12785. return 0;
  12786. }
  12787. const text = response.result;
  12788. if (text.indexOf('#EXTM3U') < 0) {
  12789. return 0;
  12790. }
  12791. const lines = text.split('\n');
  12792. let totalSeconds = 0;
  12793. for (let i = 0; i < lines.length; i++) {
  12794. const line = lines[i].trim();
  12795. if (line.startsWith('#EXTINF:')) {
  12796. const colonIndex = line.indexOf(':');
  12797. if (colonIndex < 0) {
  12798. continue;
  12799. }
  12800. const content = line.substring(colonIndex + 1);
  12801. const commaIndex = content.indexOf(',');
  12802. const numberPart = commaIndex >= 0 ? content.substring(0, commaIndex) : content;
  12803. const seconds = Number(numberPart);
  12804. if (!Number.isNaN(seconds) && seconds > 0) {
  12805. totalSeconds += seconds;
  12806. }
  12807. }
  12808. }
  12809. if (totalSeconds > 0) {
  12810. return Math.floor(totalSeconds * 1000);
  12811. }
  12812. return 0;
  12813. } catch (fetchError) {
  12814. Logger.warn(TAG, `heanup 解析百度M3U8时长失败: ${(fetchError as Error).message}`);
  12815. return 0;
  12816. } finally {
  12817. httpRequest.destroy();
  12818. }
  12819. };
  12820. const fetchDurationFallback = async (): Promise<void> => {
  12821. const durationMs = await fetchBaiduM3u8Duration(this.videoUrl);
  12822. if (durationMs > 0) {
  12823. Logger.info(TAG, `heanup 通过M3U8推导出时长: ${durationMs}ms`);
  12824. applyDuration(durationMs);
  12825. return;
  12826. }
  12827. Logger.warn(TAG, 'heanup 首次播放未拿到时长,保持未知');
  12828. };
  12829. const preparedDuration = this.mIjkMediaPlayer.getDuration();
  12830. console.info("onecold preparedDuration--" + preparedDuration)
  12831. if (preparedDuration > 0) {
  12832. applyDuration(preparedDuration);
  12833. if (this.videoUrl.includes('method=streaming') && isBaiduType(this.currentSong?.type ?? -1)) {
  12834. const durationMs = await fetchBaiduM3u8Duration(this.videoUrl);
  12835. if (durationMs > 0 && Math.abs(durationMs - preparedDuration) > 1000) {
  12836. Logger.info(TAG, `heanup 使用M3U8时长覆盖播放器时长: ${preparedDuration}ms -> ${durationMs}ms`);
  12837. applyDuration(durationMs);
  12838. }
  12839. }
  12840. } else {
  12841. const metaDurationMs = this.parseDurationToMs(this.currentSong?.duration);
  12842. if (metaDurationMs > 0) {
  12843. Logger.info(TAG, `heanup 使用元数据时长: ${metaDurationMs}ms`);
  12844. applyDuration(metaDurationMs);
  12845. } else {
  12846. fetchDurationFallback();
  12847. }
  12848. }
  12849. setTimeout(() => {
  12850. this.avSessionController.initAvSession(false);
  12851. if (this.duration > 0) {
  12852. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  12853. }
  12854. this.setAvSessionListener();
  12855. this.updateSessionPlayState(true)
  12856. this.setCurrentPlayMode()
  12857. if(startOffset&&startOffset>0){//cue分轨播放
  12858. this.seekTo(startOffset + "");
  12859. this.saveLastPlayList()
  12860. return
  12861. }
  12862. }, 500)
  12863. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12864. let timeoutPlay = 0
  12865. if (StrUtil.isNotEmpty(this.videoUrl) &&
  12866. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  12867. timeoutPlay = 1000
  12868. }
  12869. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  12870. if (this.modeType === 0) { //文件夹
  12871. let parentPath = FileUtil.getParentPath(this.videoUrl)
  12872. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  12873. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  12874. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  12875. } else if (this.modeType === 1) { //媒体库
  12876. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  12877. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  12878. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  12879. } else if (this.modeType === 2) { //艺术家
  12880. if (this.currentSong?.artist) {
  12881. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  12882. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  12883. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  12884. }
  12885. } else if (this.modeType === 3) { //专辑
  12886. if (this.currentSong?.album) {
  12887. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  12888. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  12889. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  12890. }
  12891. }
  12892. this.duration = this.mIjkMediaPlayer.getDuration()
  12893. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  12894. if (this.mIjkMediaPlayer != null) {
  12895. let jumpTopTimeMs = this.jumpTopTime*1000;
  12896. if (jumpTopTimeMs <= this.duration) {
  12897. // 调用 seekTo 方法,跳到指定时间
  12898. if(PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY,true)){
  12899. console.log('onecold jumpTopTime = '+jumpTopTimeMs);
  12900. const position:number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  12901. console.log('onecold position = '+position);
  12902. if (position > jumpTopTimeMs) {
  12903. jumpTopTimeMs = position
  12904. }
  12905. }
  12906. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12907. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  12908. this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
  12909. }
  12910. }, timeoutPlay)
  12911. } else {
  12912. // 提示用户无法跳过
  12913. ToastUtil.showToast('跳过时间超过视频时长');
  12914. }
  12915. }
  12916. } else {
  12917. this.jumpTopTime = 0
  12918. this.jumpEndTime = 0
  12919. // console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  12920. // console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  12921. // console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  12922. // PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  12923. //记忆播放(每一首都会记忆播放)
  12924. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  12925. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12926. if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  12927. this.restorePlaybackPosition() //读取播放记忆功能
  12928. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  12929. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  12930. this.restorePlaybackPosition() //读取播放记忆功能
  12931. }
  12932. this.isFirstStartPlay = false
  12933. }, timeoutPlay)
  12934. } else {
  12935. this.isFirstStartPlay = false
  12936. }
  12937. }
  12938. this.saveLastPlayList()
  12939. } catch (error) {
  12940. let err: BusinessError = error as BusinessError;
  12941. console.error('onecold failed with err: ' + JSON.stringify(err));
  12942. }
  12943. }
  12944. );
  12945. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  12946. let mOnTimedTextListener: OnTimedTextListener = new ImplOnTimedTextListener(
  12947. (text: string) => {
  12948. }
  12949. );
  12950. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  12951. let mOnCompletionListener: OnCompletionListener = new ImplOnCompletionListener(
  12952. () => {
  12953. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  12954. if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
  12955. // 异步调用playNext
  12956. this.playNext().catch(() => {
  12957. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  12958. });
  12959. } else if (this.playType == 1) { //1:单片重复播放
  12960. this.CONTROL_PlayStatus = PlayStatus.INIT
  12961. that.startPlayOrResumePlay();
  12962. } else if (this.playType == 2) { //2:正常播放,单曲播完
  12963. that.showRePlay();
  12964. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  12965. that.progressValue = this.PROGRESS_MAX_VALUE;
  12966. that.slideEnable = false;
  12967. that.stop();
  12968. // ToastUtil.showToast('开始重新播放')
  12969. } else if (this.playType == 3) { //3:随机播放
  12970. // 异步调用randomPlay
  12971. this.randomPlay().catch(() => {
  12972. Logger.error('heanup OnCompletionListener randomPlay', `随机播放失败`);
  12973. });
  12974. }
  12975. }
  12976. );
  12977. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  12978. let mOnBufferingUpdateListener: OnBufferingUpdateListener = new ImplOnBufferingUpdateListener(
  12979. (percent: number) => {
  12980. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  12981. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  12982. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  12983. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  12984. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  12985. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  12986. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  12987. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  12988. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  12989. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  12990. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  12991. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  12992. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  12993. let Looping = this.mIjkMediaPlayer.isLooping()
  12994. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  12995. }
  12996. );
  12997. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  12998. let mOnSeekCompleteListener: OnSeekCompleteListener = new ImplOnSeekCompleteListener(
  12999. () => {
  13000. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  13001. console.info('onecold startPlayOrResumePlay 10643')
  13002. // seek 完成,延迟恢复播放,确保 ijkplayer 内部状态完全稳定
  13003. setTimeout(() => {
  13004. // seek 完成,隐藏转圈圈并重置标志
  13005. that.hideLoadIng();
  13006. that.isSeekTo = false;
  13007. that.startPlayOrResumePlay();
  13008. }, 200); // 延迟200ms,确保ijkplayer内部状态稳定
  13009. }
  13010. );
  13011. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  13012. let mOnInfoListener: OnInfoListener = new ImplOnInfoListener(
  13013. (what: number, extra: number) => {
  13014. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  13015. that.hideLoadIng();
  13016. }
  13017. );
  13018. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  13019. let mOnErrorListener: OnErrorListener = new ImplOnErrorListener(
  13020. (what: number, extra: number) => {
  13021. // 隐藏加载进度
  13022. this.isPlayerLoading = false;
  13023. this.stopProgressTask();
  13024. console.info("heanup OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  13025. console.info('heanup 播放错误,歌曲详情:' + JSON.stringify(this.currentSong))
  13026. // 检查是否为WebDAV播放错误
  13027. let isWebDavError = false;
  13028. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.currentSong.filePath) {
  13029. try {
  13030. const globalContext = GlobalContext.getContext();
  13031. const webDavAuthInfo = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
  13032. if (webDavAuthInfo) {
  13033. isWebDavError = true;
  13034. }
  13035. } catch (error) {
  13036. console.error('OnErrorListener-->go: 获取WebDAV认证信息失败');
  13037. }
  13038. }
  13039. if (isWebDavError) {
  13040. console.info(`heanup WebDAV播放错误 - what: ${what}, extra: ${extra}, URL: ${this.videoUrl}`);
  13041. // 播放失败时清空实例变量中的WebDAV认证信息,防止错误账户持续使用
  13042. // this.currentWebDavAuthInfo = null;
  13043. console.info('heanup WebDAV播放失败,保留认证信息用于后续歌曲切换');
  13044. // 根据错误代码提供更具体的错误信息
  13045. let errorMessage = "WebDAV播放失败";
  13046. if (what === -1) { // 网络错误
  13047. errorMessage = "网络连接失败,请检查WebDAV服务器连接";
  13048. } else if (what === -1004) { // HTTP 404
  13049. errorMessage = "文件未找到,请检查WebDAV服务器上的文件";
  13050. } else if (what === -1001) { // 超时
  13051. errorMessage = "连接超时,请检查网络或WebDAV服务器状态";
  13052. } else if (what === -1003) { // 无法解析主机
  13053. errorMessage = "无法连接到WebDAV服务器";
  13054. }
  13055. ToastUtil.showToast(errorMessage);
  13056. } else {
  13057. if (StrUtil.isNotEmpty(this.videoUrl) &&
  13058. !this.videoUrl.startsWith('http') &&
  13059. this.currentSong &&this.currentSong.type==CommonConstants.TYPE_LOCAL&&
  13060. !FileUtil.accessSync(this.videoUrl)) {
  13061. console.info('heanup 播放.文件不存在');
  13062. ToastUtil.showToast(Utility.resourceToString(this.context, $r('app.string.file_not_exist')))
  13063. }
  13064. }
  13065. that.hideLoadIng();
  13066. }
  13067. );
  13068. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  13069. this.mIjkMediaPlayer.setMessageListener();
  13070. // 应用均衡器设置
  13071. try {
  13072. const equalizerManager = EqualizerManager.getInstance();
  13073. equalizerManager.applyToPlayer(this.mIjkMediaPlayer);
  13074. Logger.info(TAG, 'heanup 均衡器设置已应用');
  13075. this.markEqualizerApplied();
  13076. } catch (eqError) {
  13077. Logger.warn(TAG, `heanup 应用均衡器失败: ${(eqError as Error).message}`);
  13078. this.eqApplying = false;
  13079. }
  13080. this.mIjkMediaPlayer.prepareAsync();
  13081. this.mIjkMediaPlayer.start();
  13082. }
  13083. //保存最后播放的那首歌和已经对应的播放列表
  13084. saveLastPlayList() {
  13085. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  13086. PreferencesUtil.putSync('LastMusicList', this.songList)
  13087. PreferencesUtil.putSync('LastPlayQueueScope', this.playQueueScope)
  13088. PreferencesUtil.putSync('LastPlayModeType', this.modeType)
  13089. PreferencesUtil.putSync('LastPlayTotalCount', this.totalCount)
  13090. }
  13091. // 清空播放记录
  13092. clearVideoHistory() {
  13093. this.table.clearPlayHistory((success: boolean, error?: string) => {
  13094. if (success) {
  13095. this.historyList = [];
  13096. this.updateListData(this.historyList)
  13097. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  13098. ToastUtil.showToast('清空播放记录成功')
  13099. } else {
  13100. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  13101. }
  13102. });
  13103. }
  13104. public async setAvSessionListener() {
  13105. if (!this.avSessionController) {
  13106. return;
  13107. }
  13108. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  13109. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  13110. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  13111. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  13112. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  13113. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  13114. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  13115. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  13116. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  13117. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  13118. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  13119. }
  13120. setLoopMode() {
  13121. let itype = this.playType + 1
  13122. if (itype >= 4) {
  13123. this.playType = 0
  13124. ToastUtil.showToast('连续播放')
  13125. } else if (itype === 1) {
  13126. this.playType = 1
  13127. ToastUtil.showToast('单曲循环')
  13128. } else if (itype === 2) {
  13129. this.playType = 2
  13130. ToastUtil.showToast('单曲播完')
  13131. } else if (itype === 3) {
  13132. this.playType = 3
  13133. ToastUtil.showToast('随机播放')
  13134. } else if (itype === 0) {
  13135. this.playType = 0
  13136. ToastUtil.showToast('连续播放')
  13137. }
  13138. PreferencesUtil.putSync('musicPlayType', this.playType)
  13139. this.setCurrentPlayMode()
  13140. }
  13141. private sessionSetLoopModeCallback = (mode: number) => {
  13142. if (this.mIjkMediaPlayer != null) {
  13143. ToastUtil.showToast('当前播放模式:' + mode)
  13144. Logger.info('onecold 当前播放模式= ' + mode)
  13145. let hmPlayMode = mode + 1
  13146. if (hmPlayMode >= 4) {
  13147. hmPlayMode = 0
  13148. }
  13149. if (hmPlayMode === 1) {
  13150. this.playType = 1
  13151. ToastUtil.showToast('单曲循环')
  13152. } else if (hmPlayMode === 0) {
  13153. this.playType = 2
  13154. ToastUtil.showToast('单曲播完')
  13155. } else if (hmPlayMode === 3) {
  13156. this.playType = 3
  13157. ToastUtil.showToast('随机播放')
  13158. } else if (hmPlayMode === 2) {
  13159. this.playType = 0
  13160. ToastUtil.showToast('连续播放')
  13161. }
  13162. PreferencesUtil.putSync('musicPlayType', this.playType)
  13163. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  13164. let playBackState: avSession.AVPlaybackState = {
  13165. loopMode: hmPlayMode,
  13166. };
  13167. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  13168. console.info(`set setLoopMode AVPlaybackState successfully`);
  13169. }).catch((err: BusinessError) => {
  13170. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  13171. });
  13172. }
  13173. }
  13174. setCurrentPlayMode() {
  13175. if (!this.avSessionController) {
  13176. return;
  13177. }
  13178. let mLoopMode = 0
  13179. switch (this.playType) {
  13180. case 0:
  13181. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  13182. break;
  13183. case 1:
  13184. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  13185. break;
  13186. case 2:
  13187. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  13188. break;
  13189. case 3:
  13190. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  13191. break;
  13192. }
  13193. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  13194. let playBState: avSession.AVPlaybackState = {
  13195. loopMode: mLoopMode,
  13196. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  13197. };
  13198. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  13199. console.info(`set setLoopMode AVPlaybackState successfully`);
  13200. }).catch((err: BusinessError) => {
  13201. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  13202. });
  13203. }
  13204. private sessionToggleFavoriteCallback = (assetId: string) => {
  13205. if (this.mIjkMediaPlayer != null && this.currentSong) {
  13206. console.info(`on toggleFavorite `);
  13207. // 应用收到收藏命令,进行收藏处理。
  13208. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  13209. this.doFav(this.currentSong)
  13210. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  13211. let playbackState: avSession.AVPlaybackState = {
  13212. isFavorite: !this.isFac,
  13213. };
  13214. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  13215. console.info(`SetAVPlaybackState successfully`);
  13216. }).catch((err: BusinessError) => {
  13217. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  13218. });
  13219. }
  13220. }
  13221. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  13222. device: avSession.OutputDeviceInfo) => {
  13223. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  13224. // 将 connectState 转换为可读的字符串
  13225. let stateName = 'UNKNOWN';
  13226. switch (connectState) {
  13227. case avSession.ConnectionState.STATE_CONNECTED:
  13228. stateName = 'CONNECTED(1)';
  13229. break;
  13230. case avSession.ConnectionState.STATE_DISCONNECTED:
  13231. stateName = 'DISCONNECTED(2)';
  13232. break;
  13233. case avSession.ConnectionState.STATE_CONNECTING:
  13234. stateName = 'CONNECTING(3)';
  13235. break;
  13236. default:
  13237. stateName = `OTHER(${connectState})`;
  13238. }
  13239. Logger.info('heanup sessionOutputDeviceChange', `设备状态变化: connectState=${stateName}, castCategory=${currentDevice?.castCategory}, isCastPlaying=${this.isCastPlaying}`);
  13240. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  13241. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  13242. await this.startCasting();
  13243. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  13244. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  13245. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  13246. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  13247. if (device) {
  13248. Logger.info('heanup sessionOutputDeviceChange', '设备断开连接');
  13249. Logger.info('heanup sessionOutputDeviceChange', '用户主动断开连接或已停止播放,调用endCasting');
  13250. this.endCasting();
  13251. }
  13252. }
  13253. };
  13254. private async startCasting() {
  13255. try {
  13256. Logger.info('heanup startCasting', '========== 开始投播初始化 ==========');
  13257. // 获取原始的 AVCastController
  13258. let avCastCtrl = await this.avSessionController.getAvSession()?.getAVCastController();
  13259. if (!avCastCtrl) {
  13260. Logger.error('heanup startCasting', '获取 AVCastController 失败');
  13261. return;
  13262. }
  13263. this.castController = avCastCtrl;
  13264. Logger.info('heanup startCasting', '✅ 获取 AVCastController 成功');
  13265. // 创建新的 CastController 封装器
  13266. this.castControllerWrapper = new CastController(avCastCtrl);
  13267. Logger.info('heanup startCasting', '✅ 创建 CastController 成功');
  13268. // 设置回调函数
  13269. let callbacks: CastControllerCallbacks = {
  13270. onPlayNext: () => {
  13271. Logger.info('heanup CastController', '收到 playNext 回调');
  13272. this.playNext();
  13273. },
  13274. onPlayPrevious: () => {
  13275. Logger.info('heanup CastController', '收到 playPrevious 回调');
  13276. this.playPrevious();
  13277. },
  13278. onPositionChanged: (position: number) => {
  13279. this.positionChange(position);
  13280. },
  13281. onDurationChanged: (duration: number) => {
  13282. this.playDurationChange(duration);
  13283. }
  13284. };
  13285. this.castControllerWrapper.setCallbacks(callbacks);
  13286. Logger.info('heanup startCasting', '✅ 设置回调成功');
  13287. // 暂停本地播放
  13288. this.pause();
  13289. Logger.info('heanup startCasting', '✅ 暂停本地播放成功');
  13290. // 初始化投播会话
  13291. Logger.info('heanup startCasting', `准备调用 initAVCast: songList.length=${this.songList.length}, curIndex=${this.curIndex}, videoUrl=${this.videoUrl}`);
  13292. await this.castControllerWrapper.initAVCast(
  13293. this.songList,
  13294. this.curIndex,
  13295. this.mIjkMediaPlayer.getCurrentPosition(),
  13296. this.videoUrl,
  13297. this.getActiveDuration()
  13298. );
  13299. Logger.info('heanup startCasting', '✅ initAVCast 调用完成');
  13300. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  13301. refToIsCasting?.set(true);
  13302. this.castSeek = true;
  13303. // 从 CastController 获取投播状态
  13304. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  13305. if (this.isCastPlaying) {
  13306. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  13307. this.setIsPlaying(true);
  13308. this.updateSessionPlayState(true);
  13309. }
  13310. Logger.info('heanup startCasting', `✅ 投播初始化完成, isCastPlaying=${this.isCastPlaying}`);
  13311. } catch (error) {
  13312. Logger.error('heanup startCasting', `❌ 投播初始化失败: ${error}`);
  13313. }
  13314. }
  13315. async changeCasting() {
  13316. Logger.info('heanup changeCasting', '切换投播');
  13317. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  13318. this.initQueueItem();
  13319. await this.prepare();
  13320. this.setPlaybackStateChangeListener();
  13321. // isCastPlaying 会在 playbackStateChangeListener 中根据实际状态更新
  13322. this.castSeek = true;
  13323. }
  13324. public endCasting() {
  13325. Logger.info('heanup endCasting', 'endCasting被调用');
  13326. this.avSessionController.getAvSession()?.stopCasting();
  13327. this.stopCast();
  13328. // 关闭文件描述符
  13329. if (this.castFile) {
  13330. try {
  13331. fs.closeSync(this.castFile);
  13332. this.castFile = undefined;
  13333. Logger.info('heanup endCasting', '关闭投播文件描述符');
  13334. } catch (error) {
  13335. Logger.warn('heanup endCasting', `关闭文件描述符失败: ${error}`);
  13336. }
  13337. }
  13338. this.isCastPlaying = false;
  13339. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  13340. refToIsCasting?.set(false);
  13341. this.pause();
  13342. this.setIsPlaying(false);
  13343. // if (this.curIndex === this.curSource.index) {
  13344. // this.play
  13345. // this.seek(this.currentTime * 1000);
  13346. // this.setIsPlaying(true);
  13347. // } else {
  13348. // this.pauseVideo();
  13349. // this.setIsPlaying(false);
  13350. // }
  13351. }
  13352. public setIsPlaying(isPlayer: boolean) {
  13353. this.isPlaying = isPlayer;
  13354. // 发送播放状态变化事件给歌单详情页面
  13355. try {
  13356. const eventPlaybackStatus: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYBACK_STATUS }
  13357. const currentFilePath = this.currentSong?.filePath || ''
  13358. const eventData: emitter.EventData = {
  13359. data: {
  13360. isPlaying: this.isPlaying,
  13361. curIndex: this.curIndex,
  13362. currentFilePath: currentFilePath
  13363. }
  13364. };
  13365. emitter.emit(eventPlaybackStatus, eventData)
  13366. Logger.info(`heanup 发送播放状态变化事件: isPlaying=${this.isPlaying}, curIndex=${this.curIndex}, currentFilePath=${currentFilePath}`)
  13367. } catch (error) {
  13368. Logger.error('heanup 发送播放状态变化事件失败: ' + error)
  13369. }
  13370. }
  13371. private setPlaybackStateChangeListener(): void {
  13372. // 注意: HarmonyOS 的投播控制器可能不返回 state 字段
  13373. // 我们需要通过其他方式来判断播放状态
  13374. // 1. 监听位置变化
  13375. this.castController?.on('playbackStateChange', ['position'], (playbackState: avSession.AVPlaybackState) => {
  13376. if (playbackState.position && typeof playbackState.position.elapsedTime !== 'undefined') {
  13377. Logger.info('heanup playbackStateChange[position]', `elapsedTime=${playbackState.position.elapsedTime}`);
  13378. this.positionChange(playbackState.position.elapsedTime);
  13379. }
  13380. });
  13381. // 2. 监听时长变化
  13382. this.castController?.on('playbackStateChange', ['extras'], (playbackState: avSession.AVPlaybackState) => {
  13383. const duration = playbackState?.extras?.duration;
  13384. if (typeof duration === 'number') {
  13385. this.playDurationChange(duration);
  13386. }
  13387. });
  13388. // 3. 监听所有状态变化(用于调试和状态判断)
  13389. this.castController?.on('playbackStateChange', 'all', (playbackState: avSession.AVPlaybackState) => {
  13390. Logger.info('heanup playbackStateChange[all]', `完整状态=${JSON.stringify(playbackState)}`);
  13391. // 检查是否有 state 字段(某些设备可能返回)
  13392. if (playbackState.state !== undefined) {
  13393. Logger.info('heanup playbackStateChange', `state字段存在: ${playbackState.state}`);
  13394. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  13395. this.isCastPlaying = true;
  13396. }
  13397. }
  13398. });
  13399. // 4. 监听播放完成事件
  13400. this.castController?.on('endOfStream', this.playNextCallback);
  13401. this.castController?.on('playNext', this.playNextCallback);
  13402. this.castController?.on('playPrevious', this.playPreviousCallback);
  13403. // 5. 监听错误事件
  13404. this.castController?.on('error', (error: BusinessError) => {
  13405. Logger.error('heanup playbackStateChange', `投播错误: code=${error.code}, message=${error.message}`);
  13406. this.isCastPlaying = false;
  13407. });
  13408. }
  13409. private updateSessionPlayState(isPlay: boolean): void {
  13410. // if(!this.isBgPlayOpen)
  13411. // return
  13412. const elapsedTime = (this.castControllerWrapper && this.isCastPlaying) ? this.currentTime2 * 1000
  13413. : this.mIjkMediaPlayer.getCurrentPosition();
  13414. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  13415. this.setAVSessionPlayState({
  13416. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  13417. position: {
  13418. elapsedTime: elapsedTime,
  13419. updateTime: new Date().getTime()
  13420. }
  13421. });
  13422. }
  13423. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  13424. this.avSessionController.setAvSessionPlayState(playbackState)
  13425. }
  13426. private positionChange(position: number) {
  13427. this.currentTime2 = position / 1000;
  13428. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  13429. if (this.castControllerWrapper && this.isCastPlaying) {
  13430. this.updateCastProgress(position);
  13431. if (this.isSeekTo) {
  13432. this.isSeekTo = false;
  13433. }
  13434. }
  13435. }
  13436. private playDurationChange(duration: number) {
  13437. this.duration = duration;
  13438. this.durationTime = Math.floor(this.duration / 1000);
  13439. this.durationStringTime = secondToTime((this.durationTime));
  13440. if (this.castControllerWrapper && this.isCastPlaying) {
  13441. this.totalTime = this.stringForTime(this.duration);
  13442. }
  13443. }
  13444. // playbackStateChangeListener 方法已被删除,改用 setPlaybackStateChangeListener 中的内联函数
  13445. private reloadCasting = async () => {
  13446. Logger.info('heanup reloadCasting', '重新加载投播');
  13447. // 使用 initQueueItem() 方法来准备投播项目,保持逻辑一致
  13448. this.initQueueItem();
  13449. await this.prepare();
  13450. };
  13451. public playNextCallback = (): void => {
  13452. this.playNext().catch(() => {
  13453. Logger.error('heanup playNextCallback', `播放下一首失败`);
  13454. });
  13455. };
  13456. public playPreviousCallback = (): void => {
  13457. this.playPrevious().catch(() => {
  13458. Logger.error('heanup playNextCallback', `播放上一首失败`);
  13459. });
  13460. };
  13461. async prepare() {
  13462. try {
  13463. Logger.info('heanup prepare', `开始准备投播: ${this.castItem?.description?.title}`);
  13464. await this.castController?.prepare(this.castItem);
  13465. Logger.info('heanup prepare', '投播prepare成功');
  13466. await this.castController?.start(this.castItem);
  13467. Logger.info('heanup prepare', '投播start成功');
  13468. // 投播启动成功,设置为投播状态
  13469. this.isCastPlaying = true;
  13470. Logger.info('heanup prepare', '投播启动成功,设置isCastPlaying=true');
  13471. } catch (error) {
  13472. Logger.error('heanup prepare', `投播准备失败: ${error}`);
  13473. this.isCastPlaying = false;
  13474. }
  13475. }
  13476. public initQueueItem() {
  13477. let item = this.songList[this.curIndex];
  13478. // 判断是否是流媒体地址 - 使用 videoUrl 判断而不是 filePath
  13479. // 因为 filePath 可能是 navidrome:// 等自定义协议,而 videoUrl 才是真实的流地址
  13480. let isStreaming = this.isUrl(this.videoUrl);
  13481. Logger.info('heanup initQueueItem', `准备投播歌曲: ${item.name}, 是否流媒体: ${isStreaming}, videoUrl: ${this.videoUrl}`);
  13482. // 关闭之前的文件描述符
  13483. if (this.castFile) {
  13484. try {
  13485. fs.closeSync(this.castFile);
  13486. Logger.info('heanup initQueueItem', '关闭之前的文件描述符');
  13487. } catch (error) {
  13488. Logger.warn('heanup initQueueItem', `关闭文件描述符失败: ${error}`);
  13489. }
  13490. }
  13491. let description: avSession.AVMediaDescription = {
  13492. assetId: 'AUDIO-' + item.filePath,
  13493. title: item.name,
  13494. artist: item.artist || '',
  13495. // 该字段大写,音频'AUDIO',视频'VIDEO'
  13496. mediaType: 'AUDIO',
  13497. mediaSize: item.videoSize,
  13498. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  13499. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  13500. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  13501. duration: this.duration,
  13502. albumCoverUri: item.pixelMapPath, // 本地路径电视可能无法访问,暂时注释
  13503. appName: this.appName,
  13504. lyricContent: item.lyricContent,
  13505. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  13506. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  13507. };
  13508. console.log('heanup initQueueItem this.lyricContent', item.lyricContent);
  13509. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  13510. if (isStreaming) {
  13511. // 流媒体地址使用 mediaUri
  13512. description.mediaUri = this.videoUrl;
  13513. Logger.info('heanup initQueueItem', `使用流媒体地址投播: ${this.videoUrl}`);
  13514. } else {
  13515. // 本地文件使用 fdSrc
  13516. const localPath = this.videoUrl || item.filePath;
  13517. let uri = fileUri.getUriFromPath(localPath);
  13518. this.castFile = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  13519. let fdSrc: media.AVFileDescriptor = {
  13520. fd: this.castFile.fd
  13521. };
  13522. description.fdSrc = fdSrc;
  13523. Logger.info('heanup initQueueItem', `使用本地文件投播: ${localPath}, fd: ${this.castFile.fd}`);
  13524. }
  13525. this.castItem = {
  13526. itemId: this.curIndex,
  13527. description: description
  13528. };
  13529. Logger.info('heanup initQueueItem', `投播项目创建完成: ${JSON.stringify({
  13530. title: description.title,
  13531. mediaType: description.mediaType,
  13532. hasMediaUri: !!description.mediaUri,
  13533. hasFdSrc: !!description.fdSrc,
  13534. duration: description.duration
  13535. })}`);
  13536. }
  13537. // 判断是否是 URL 或流媒体地址
  13538. private isUrl(str: string): boolean {
  13539. if (!str) {
  13540. return false;
  13541. }
  13542. // 检查常见的流媒体协议
  13543. if (str.startsWith('http://') || str.startsWith('https://') ||
  13544. str.startsWith('rtmp://') || str.startsWith('rtsp://') ||
  13545. str.startsWith('rtp://') || str.startsWith('mms://')) {
  13546. return true;
  13547. }
  13548. // 扩展的URL正则表达式,支持多种协议
  13549. const urlPattern = new RegExp(
  13550. '^((https?|ftp|rtmp|rtsp|mms|ws|rtp|wss):\\/\\/)?' + // 支持多种协议
  13551. '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // 域名
  13552. '((\\d{1,3}\\.){3}\\d{1,3})|' + // 或IPv4地址
  13553. '\\[([a-f\\d]{1,4}:){7}[a-f\\d]{1,4}\\]|' + // 或IPv6地址
  13554. 'localhost)' + // 或localhost
  13555. '(\\:\\d+)?' + // 端口号(可选)
  13556. '(\\/[-a-z\\d%_.~+]*)*' + // 路径
  13557. '(\\?[;&a-z\\d%_.~+=-]*)?' + // 查询字符串(可选)
  13558. '(\\#[-a-z\\d_]*)?$', // 片段标识符(可选)
  13559. 'i' // 不区分大小写
  13560. );
  13561. return urlPattern.test(str);
  13562. }
  13563. async stopCast() {
  13564. try {
  13565. // 使用 CastController 释放资源
  13566. if (this.castControllerWrapper) {
  13567. await this.castControllerWrapper.releaseAVCast();
  13568. Logger.info('heanup stopCast', 'CastController 释放投播控制器成功');
  13569. }
  13570. // 清空引用
  13571. this.castControllerWrapper = undefined;
  13572. this.castController = undefined;
  13573. this.castItem = undefined;
  13574. this.castFile = undefined;
  13575. } catch (error) {
  13576. Logger.error('heanup stopCast', `停止投播失败: ${error}`);
  13577. }
  13578. }
  13579. private sessionPlayCallback = (): void => {
  13580. this.playOrPause()
  13581. };
  13582. private sessionPauseCallback = (): void => {
  13583. this.pause()
  13584. };
  13585. private async playOrPause() {
  13586. if (!this.debounce()) {
  13587. return;
  13588. }
  13589. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  13590. await this.pause();
  13591. } else {
  13592. // 如果是投播模式,使用 CastController 的 play 方法
  13593. if (this.castControllerWrapper && this.isCastPlaying) {
  13594. try {
  13595. Logger.info('heanup playOrPause', '投播模式播放');
  13596. await this.castControllerWrapper.setPlaying();
  13597. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  13598. this.setIsPlaying(true);
  13599. this.updateSessionPlayState(true);
  13600. Logger.info('heanup playOrPause', '投播播放成功');
  13601. this.playChange();
  13602. } catch (error) {
  13603. Logger.error('heanup playOrPause', `投播播放失败: ${error}`);
  13604. }
  13605. } else {
  13606. console.info('onecold startPlayOrResumePlay 11064')
  13607. this.startPlayOrResumePlay();
  13608. this.playChange()
  13609. }
  13610. }
  13611. }
  13612. private sessionPlayNextCallback = (): void => {
  13613. this.playNext().catch(() => {
  13614. Logger.error('heanup sessionPlayPreviousCallback', `播放下 一首失败`);
  13615. });
  13616. };
  13617. private sessionPlayPreviousCallback = (): void => {
  13618. this.playPrevious().catch(() => {
  13619. Logger.error('heanup sessionPlayPreviousCallback', `播放上一首失败`);
  13620. });
  13621. };
  13622. private sessionStopCallback = (): void => {
  13623. this.stop()
  13624. };
  13625. private sessionFastForwardCallback = async (time?: number) => {
  13626. if (!time) {
  13627. return;
  13628. }
  13629. let curPosition: number;
  13630. if (this.castController && this.isCastPlaying) {
  13631. // 投播模式,使用UI显示的时间
  13632. curPosition = this.currentTime2 * 1000;
  13633. } else if (this.mIjkMediaPlayer != null) {
  13634. // 本地播放器模式
  13635. curPosition = this.mIjkMediaPlayer.getCurrentPosition();
  13636. } else {
  13637. return;
  13638. }
  13639. let seeTime = curPosition + time * 1000;
  13640. // 限制 seekValue 在合法范围内
  13641. if (seeTime < 0) {
  13642. seeTime = 0;
  13643. } else if (seeTime > this.duration) {
  13644. seeTime = this.duration;
  13645. }
  13646. Logger.info('heanup sessionFastForwardCallback', `快进: ${time}秒, 目标位置: ${seeTime}ms`);
  13647. this.setSeekToActionProgress(seeTime);
  13648. await this.seekTo(seeTime + "");
  13649. };
  13650. private getActiveDuration(): number {
  13651. let duration = this.mIjkMediaPlayer.getDuration();
  13652. if (this.castControllerWrapper && this.isCastPlaying) {
  13653. return this.duration > 0 ? this.duration : duration;
  13654. }
  13655. if (duration <= 0 && this.duration > 0) {
  13656. duration = this.duration;
  13657. }
  13658. return duration;
  13659. }
  13660. private getSongDurationMs(song?: VideoItem): number {
  13661. if (!song || !song.duration) {
  13662. return 0;
  13663. }
  13664. const raw = song.duration.trim();
  13665. if (!raw) {
  13666. return 0;
  13667. }
  13668. const parts = raw.split(':').map((part) => Number(part));
  13669. if (parts.some((part) => Number.isNaN(part))) {
  13670. return 0;
  13671. }
  13672. let seconds = 0;
  13673. if (parts.length === 3) {
  13674. seconds = parts[0] * 3600 + parts[1] * 60 + parts[2];
  13675. } else if (parts.length === 2) {
  13676. seconds = parts[0] * 60 + parts[1];
  13677. } else if (parts.length === 1) {
  13678. seconds = parts[0];
  13679. }
  13680. return seconds > 0 ? seconds * 1000 : 0;
  13681. }
  13682. private updateCastProgress(position: number): void {
  13683. const duration = this.getActiveDuration();
  13684. if (duration <= 0) {
  13685. return;
  13686. }
  13687. this.slideEnable = true;
  13688. let pos = (position / duration) * 100;
  13689. if (pos > this.PROGRESS_MAX_VALUE) {
  13690. this.progressValue = this.PROGRESS_MAX_VALUE;
  13691. } else if (pos < 0) {
  13692. this.progressValue = 0;
  13693. } else {
  13694. this.progressValue = pos;
  13695. }
  13696. this.totalTime = this.stringForTime(duration);
  13697. if (position > duration) {
  13698. position = duration;
  13699. }
  13700. this.isCurrentTime = true;
  13701. this.currentTime = this.stringForTime(position);
  13702. this.isCurrentTime = false;
  13703. this.lyricController.updatePosition(position + this.timeOffset * 1000);
  13704. if(this.showPipLyric){
  13705. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000);
  13706. }
  13707. if(this.isShowSingleLineLyric){
  13708. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000);
  13709. }
  13710. }
  13711. /**
  13712. * Gesture method onActionUpdate.
  13713. *
  13714. * @param event Gesture event.手势拖动设置快进和后退
  13715. */
  13716. private setSeekToActionProgress(position: number) {
  13717. // 投播模式使用this.duration,本地模式使用播放器获取
  13718. let duration = this.getActiveDuration();
  13719. let pos = 0;
  13720. if (duration > 0) {
  13721. this.slideEnable = true;
  13722. let curPercent = position / duration;
  13723. pos = curPercent * 100;
  13724. if (pos > this.PROGRESS_MAX_VALUE) {
  13725. this.progressValue = this.PROGRESS_MAX_VALUE
  13726. } else {
  13727. this.progressValue = pos;
  13728. }
  13729. }
  13730. // LogUtils.getInstance()
  13731. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  13732. this.totalTime = this.stringForTime(duration);
  13733. if (position > duration) {
  13734. position = duration;
  13735. }
  13736. this.isCurrentTime = true;
  13737. this.currentTime = this.stringForTime(position);
  13738. this.isCurrentTime = false
  13739. }
  13740. private sessionRewindCallback = async (time?: number) => {
  13741. if (!time) {
  13742. return;
  13743. }
  13744. let curPosition: number;
  13745. if (this.castController && this.isCastPlaying) {
  13746. // 投播模式,使用UI显示的时间
  13747. curPosition = this.currentTime2 * 1000;
  13748. } else if (this.mIjkMediaPlayer != null) {
  13749. // 本地播放器模式
  13750. curPosition = this.mIjkMediaPlayer.getCurrentPosition();
  13751. } else {
  13752. return;
  13753. }
  13754. let seeTime = curPosition - time * 1000;
  13755. // 限制 seekValue 在合法范围内
  13756. if (seeTime < 0) {
  13757. seeTime = 0;
  13758. } else if (seeTime > this.duration) {
  13759. seeTime = this.duration;
  13760. }
  13761. Logger.info('heanup sessionRewindCallback', `快退: ${time}秒, 目标位置: ${seeTime}ms`);
  13762. this.setSeekToActionProgress(seeTime);
  13763. await this.seekTo(seeTime + "");
  13764. };
  13765. private sessionSeekCallback = async (seekTime: number) => {
  13766. Logger.info('heanup sessionSeekCallback', `收到seek请求: ${seekTime}ms, 投播模式: ${this.isCastPlaying}`);
  13767. // 投播模式直接调用seekTo,它会自动处理投播控制器的seek命令
  13768. await this.seekTo(seekTime + "");
  13769. };
  13770. private async getFileSize(filePath: string): Promise<number> {
  13771. try {
  13772. const stat = await fs.stat(filePath);
  13773. return stat.size;
  13774. } catch (err) {
  13775. console.error('Failed to get file size: ' + err.message);
  13776. return 0;
  13777. }
  13778. }
  13779. private async pause() {
  13780. // 如果是投播模式,使用 CastController 的 pause 方法
  13781. if (this.castControllerWrapper && this.isCastPlaying) {
  13782. try {
  13783. Logger.info('heanup pause', '投播模式暂停');
  13784. await this.castControllerWrapper.setPause();
  13785. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  13786. this.setIsPlaying(false);
  13787. this.updateSessionPlayState(false);
  13788. Logger.info('heanup pause', '投播暂停成功');
  13789. } catch (error) {
  13790. Logger.error('heanup pause', `投播暂停失败: ${error}`);
  13791. }
  13792. } else if (this.mIjkMediaPlayer.isPlaying()) {
  13793. // 本地播放器模式
  13794. this.savePlaybackPosition();
  13795. this.mIjkMediaPlayer.pause();
  13796. this.setProgress();
  13797. this.mDestroyPage = true;
  13798. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  13799. this.updateSessionPlayState(false)
  13800. this.playChange()
  13801. if (this.pipController) {
  13802. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  13803. PiPWindow.PiPControlStatus.PAUSE);
  13804. }
  13805. }
  13806. }
  13807. private stop() {
  13808. this.savePlaybackPosition();
  13809. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13810. this.mIjkMediaPlayer.stop();
  13811. this.mIjkMediaPlayer.release();
  13812. this.stopProgressTask();
  13813. this.updateSessionPlayState(false)
  13814. this.playChange()
  13815. this.watchStatus();
  13816. }
  13817. //保持记忆播放功能
  13818. private savePlaybackPosition() {
  13819. if (this.mIjkMediaPlayer != null) {
  13820. const position = this.mIjkMediaPlayer.getCurrentPosition();
  13821. // ToastUtil.showToast('保存记忆播放 = ' + position)
  13822. const duration = this.mIjkMediaPlayer.getDuration();
  13823. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  13824. // 如果播放位置接近视频末尾,则保存 position 为 0
  13825. const playbackPosition = (duration - position < threshold) ? 0 : position;
  13826. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  13827. }
  13828. }
  13829. //获取记忆播放功能
  13830. private restorePlaybackPosition() {
  13831. const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  13832. if (this.mIjkMediaPlayer != null && position > 0) {
  13833. this.seekTo(position + "");
  13834. }
  13835. }
  13836. private async seekTo(value: string) {
  13837. // if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  13838. // ToastUtil.showToast('wma格式不支持拖动快进。')
  13839. // return
  13840. // }
  13841. // 如果是投播模式,使用 CastController 的 seek 方法
  13842. if (this.castControllerWrapper && this.isCastPlaying) {
  13843. try {
  13844. let seekPos = Number.parseInt(value);
  13845. this.isSeekTo = true;
  13846. Logger.info('heanup seekTo', `投播模式seek到: ${seekPos}ms, 当前时长: ${this.duration}ms`);
  13847. // 检查是否接近末尾
  13848. if (this.duration > 0 && seekPos >= this.duration - 500) {
  13849. Logger.warn('heanup seekTo', `快进位置接近末尾(${seekPos}ms >= ${this.duration}ms),可能触发播放完成`);
  13850. }
  13851. await this.castControllerWrapper.seek(seekPos);
  13852. Logger.info('heanup seekTo', `投播seek命令发送成功,位置: ${seekPos}ms`);
  13853. } catch (error) {
  13854. Logger.error('heanup seekTo', `投播seek失败: ${error}`);
  13855. }
  13856. } else {
  13857. // 本地播放器模式
  13858. this.isSeekTo = true
  13859. this.mIjkMediaPlayer.seekTo(value);
  13860. this.setProgress()
  13861. this.isSeekTo = false
  13862. }
  13863. }
  13864. // 添加到下一首播放
  13865. private addToNextPlay(song: VideoItem) {
  13866. if (!this.debounce()) {
  13867. return;
  13868. }
  13869. if (this.currentSong) {
  13870. if (this.currentSong === song) {
  13871. ToastUtil.showToast('当前已经在播放这首歌了!')
  13872. return
  13873. }
  13874. }
  13875. // 如果未开始播放或队列为空
  13876. if (this.curIndex === -1 || this.songList.length === 0) {
  13877. this.songList = [song];
  13878. this.curIndex = 0;
  13879. this.doPlay(song)
  13880. return;
  13881. }
  13882. // 插入到当前索引+1的位置
  13883. const insertPos = this.curIndex + 1;
  13884. this.songList.splice(insertPos, 0, song);
  13885. this.songList = [...this.songList]; // 触发状态更新
  13886. this.sonDataSource.pushArrayData(this.songList)
  13887. ToastUtil.showToast('已添加至下一首播放')
  13888. }
  13889. //后退10s,可再设置设置默认几秒
  13890. async backForward() {
  13891. // 如果是投播模式,从currentTime2获取当前位置
  13892. let pos: number;
  13893. if (this.castController && this.isCastPlaying) {
  13894. pos = this.currentTime2 * 1000; // 使用秒转毫秒
  13895. Logger.info('heanup backForward', `投播模式当前位置: ${pos}ms`);
  13896. } else if (this.mIjkMediaPlayer) {
  13897. pos = this.mIjkMediaPlayer.getCurrentPosition();
  13898. } else {
  13899. return;
  13900. }
  13901. let value = pos - Number(this.fastForwardSeconds) * 1000;
  13902. if (value < 0) {
  13903. value = 0;
  13904. }
  13905. await this.seekTo(value + "");
  13906. }
  13907. //快进10s,可再设置设置默认几秒
  13908. async fastForward() {
  13909. // 如果是投播模式,从currentTime2获取当前位置
  13910. let pos: number;
  13911. if (this.castController && this.isCastPlaying) {
  13912. pos = this.currentTime2 * 1000; // 使用秒转毫秒
  13913. Logger.info('heanup fastForward', `投播模式当前位置: ${pos}ms`);
  13914. } else if (this.mIjkMediaPlayer) {
  13915. pos = this.mIjkMediaPlayer.getCurrentPosition();
  13916. } else {
  13917. return;
  13918. }
  13919. let value = pos + Number(this.fastForwardSeconds) * 1000;
  13920. // 限制不超过总时长
  13921. if (this.duration > 0 && value > this.duration) {
  13922. value = this.duration;
  13923. }
  13924. await this.seekTo(value + "");
  13925. }
  13926. //下一个
  13927. private async playNext() {
  13928. Logger.info('heanup playNext', '========== playNext 开始 ==========');
  13929. Logger.info('heanup playNext', `isCastPlaying=${this.isCastPlaying}, castControllerWrapper存在=${!!this.castControllerWrapper}`);
  13930. if (!this.debounce()) {
  13931. Logger.warn('heanup playNext', 'debounce() 返回 false,退出');
  13932. return;
  13933. }
  13934. Logger.info('heanup playNext', `playType=${this.playType}`);
  13935. if (this.playType == 3) { //3:随机播放
  13936. Logger.info('heanup playNext', '随机播放模式');
  13937. await this.randomPlay()
  13938. return;
  13939. }
  13940. if (ArrayUtil.isNotEmpty(this.songList)) {
  13941. if (this.curIndex >= this.songList.length - 1) {
  13942. await this.tryLoadNextPageForPlayback();
  13943. }
  13944. if (this.curIndex >= this.songList.length - 1) {
  13945. this.curIndex = 0;
  13946. } else {
  13947. this.curIndex++;
  13948. }
  13949. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  13950. this.currentSong = this.songList[this.curIndex];
  13951. console.info('heanup playNext', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  13952. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13953. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13954. context: this.context,
  13955. autoParseMusicName: this.autoParseMusicName
  13956. });
  13957. this.artist = this.songList[this.curIndex].artist
  13958. this.name = this.songList[this.curIndex].name
  13959. //this.cover = this.songList[this.curIndex].pixelMapPath
  13960. console.info('heanup playNext 1 ', `this.isCastPlaying: ${ this.isCastPlaying}`)
  13961. console.info('heanup playNext 2 ', `this.castControllerWrapper: ${this.castControllerWrapper}`)
  13962. // 如果是投播模式,使用 CastController 播放下一首
  13963. if (this.castControllerWrapper) {
  13964. console.info('heanup playNext', '使用 CastController 播放下一首');
  13965. try {
  13966. const nextDuration = this.getSongDurationMs(this.currentSong);
  13967. if (nextDuration > 0) {
  13968. this.duration = nextDuration;
  13969. this.durationTime = Math.floor(nextDuration / 1000);
  13970. this.durationStringTime = secondToTime(this.durationTime);
  13971. this.totalTime = this.stringForTime(nextDuration);
  13972. this.avSessionController.setAVMetadataMusic(this.currentSong, nextDuration, this.lyricContent);
  13973. }
  13974. this.updateCastProgress(0);
  13975. await this.castControllerWrapper.playNext(this.songList, this.curIndex, this.videoUrl, nextDuration);
  13976. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  13977. console.info('heanup playNext', 'CastController 播放下一首成功');
  13978. return;
  13979. } catch (error) {
  13980. console.error('heanup playNext', `CastController 播放下一首失败: ${error}`);
  13981. // 如果投播失败,回退到本地播放
  13982. this.isCastPlaying = false;
  13983. }
  13984. }
  13985. // 本地播放器模式,需要先stop
  13986. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13987. this.stop();
  13988. this.changeImageAnimation()
  13989. }
  13990. }
  13991. changeImageAnimation() {
  13992. if(this.openSkipSongAnimate){
  13993. // 第一步:淡出动画
  13994. this.getUIContext()?.animateTo({
  13995. duration: 500,
  13996. curve: Curve.EaseOut,
  13997. }, () => {
  13998. this.opacityValueImage = 0.1;
  13999. if(this.isCoverRectangle){
  14000. this.scaleValueImage = 0.88
  14001. }
  14002. });
  14003. // 第二步:切换图片后淡入
  14004. setTimeout(() => {
  14005. this.cover = this.songList[this.curIndex].pixelMapPath
  14006. this.getUIContext()?.animateTo({
  14007. duration: 500,
  14008. curve: Curve.EaseIn,
  14009. }, () => {
  14010. this.opacityValueImage = 1;
  14011. this.scaleValueImage = 1 // 图标恢复到原始大小
  14012. this.startPlayOrResumePlay()
  14013. });
  14014. }, 500);
  14015. }else{
  14016. this.cover = this.songList[this.curIndex].pixelMapPath
  14017. this.startPlayOrResumePlay()
  14018. }
  14019. }
  14020. // 内部方法:提前缓存下一首
  14021. private async preloadNextSongInternal(): Promise<void> {
  14022. // 随机模式下传递已播放索引集合
  14023. if (this.playType === 3) {
  14024. this.preloadNextRandomIndex = await preloadNextSongIfNeeded(
  14025. this.songList,
  14026. this.curIndex,
  14027. this.playType,
  14028. this.playedIndices
  14029. );
  14030. } else {
  14031. this.preloadNextRandomIndex = await preloadNextSongIfNeeded(
  14032. this.songList,
  14033. this.curIndex,
  14034. this.playType
  14035. );
  14036. }
  14037. }
  14038. // 存储已播放的歌曲索引
  14039. private playedIndices: Set<number> = new Set();
  14040. // 存储已播放的本地歌曲路径(随机播放去重用)
  14041. private playedLocalFilePaths: Set<string> = new Set();
  14042. // 随机播放模式下的播放历史栈(记录实际播放顺序,用于"上一首"功能)
  14043. private randomPlayHistory: VideoItem[] = [];
  14044. //随机播放
  14045. private async randomPlay() {
  14046. // if (!this.debounce()) {
  14047. // return;
  14048. // }
  14049. if (this.currentSong) {
  14050. // 将当前歌加入到随机播放历史栈(在切换到新歌之前)
  14051. this.randomPlayHistory.unshift(this.currentSong);
  14052. // 限制历史栈大小,避免无限增长
  14053. if (this.randomPlayHistory.length > 50) {
  14054. this.randomPlayHistory = this.randomPlayHistory.slice(0, 50);
  14055. }
  14056. Logger.info(TAG, `randomPlay: 将当前歌加入历史栈, 栈大小: ${this.randomPlayHistory.length}`);
  14057. const isCurrentRemote = isRemoteCloudType(this.currentSong.type);
  14058. const currentFilePath = this.currentSong.filePath;
  14059. if (isCurrentRemote) {
  14060. const remoteOptions: RandomSongQueryOptions = {
  14061. type: this.currentSong.type,
  14062. excludeFilePaths: currentFilePath ? [currentFilePath] : []
  14063. };
  14064. const randomRemoteSong = await this.table.queryRandomSong(remoteOptions);
  14065. if (randomRemoteSong) {
  14066. // 验证并修正webdav_account_id
  14067. if (randomRemoteSong.webdav_account_id) {
  14068. const manager = RemoteDriveManager.getInstance();
  14069. const account = await manager.getWebDavAccountById(randomRemoteSong.webdav_account_id);
  14070. if (!account) {
  14071. Logger.warn(TAG, `随机播放的歌曲账号ID无效: ${randomRemoteSong.webdav_account_id}, 尝试查找同类型账号`);
  14072. // 获取所有账号,查找相同类型的账号
  14073. const allAccounts = manager.getAllWebDavAccounts();
  14074. let foundAccount: WebDavAccount | null = null;
  14075. for (let i = 0; i < allAccounts.length; i++) {
  14076. if (allAccounts[i].webType === randomRemoteSong.type) {
  14077. foundAccount = allAccounts[i];
  14078. break;
  14079. }
  14080. }
  14081. if (foundAccount && foundAccount.id) {
  14082. Logger.info(TAG, `找到同类型账号,更新webdav_account_id: ${randomRemoteSong.webdav_account_id} -> ${foundAccount.id}`);
  14083. randomRemoteSong.webdav_account_id = foundAccount.id.toString();
  14084. // 更新数据库记录
  14085. await this.table.updateWebDavAccountId(randomRemoteSong.filePath, foundAccount.id.toString());
  14086. } else {
  14087. Logger.error(TAG, `无法找到类型为${randomRemoteSong.type}的账号,跳过此歌曲`);
  14088. return;
  14089. }
  14090. }
  14091. }
  14092. let nextIndex = this.songList.findIndex(song => song.filePath === randomRemoteSong.filePath);
  14093. if (nextIndex < 0) {
  14094. this.songList = [...this.songList, randomRemoteSong];
  14095. this.sonDataSource.pushArrayData(this.songList);
  14096. nextIndex = this.songList.length - 1;
  14097. }
  14098. this.curIndex = nextIndex;
  14099. this.playedIndices.add(this.curIndex);
  14100. this.CONTROL_PlayStatus = PlayStatus.INIT;
  14101. this.stop();
  14102. this.currentSong = randomRemoteSong;
  14103. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  14104. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  14105. context: this.context,
  14106. autoParseMusicName: this.autoParseMusicName
  14107. });
  14108. this.name = this.currentSong.name;
  14109. this.artist = this.currentSong.artist;
  14110. this.changeImageAnimation();
  14111. return;
  14112. }
  14113. Logger.warn(TAG, '随机播放未获取到网盘歌曲,回退到列表随机');
  14114. } else {
  14115. if (currentFilePath) {
  14116. this.playedLocalFilePaths.add(currentFilePath);
  14117. }
  14118. // 根据modeType构建不同的查询选项
  14119. const localOptions: RandomSongQueryOptions = {
  14120. type: CommonConstants.TYPE_LOCAL,
  14121. excludeFilePaths: Array.from(this.playedLocalFilePaths)
  14122. };
  14123. Logger.info(TAG, `randomPlay: 本地播放模式, modeType=${this.modeType}, currentPlaylistSongFilePaths.length=${this.currentPlaylistSongFilePaths.length}, currentPath=${this.currentPath}`);
  14124. // modeType==0: 文件夹模式,添加parentPath过滤
  14125. if (this.modeType === 0 && this.currentPath) {
  14126. localOptions.parentPath = this.currentPath;
  14127. Logger.info(TAG, `randomPlay: 文件夹模式, parentPath=${this.currentPath}`);
  14128. }
  14129. // modeType==4: 歌单模式,添加playlistSongFilePaths
  14130. else if (this.modeType === 4 && this.currentPlaylistSongFilePaths.length > 0) {
  14131. localOptions.playlistSongFilePaths = this.currentPlaylistSongFilePaths;
  14132. Logger.info(TAG, `randomPlay: 歌单模式,歌曲数量=${this.currentPlaylistSongFilePaths.length}, 前3首=${this.currentPlaylistSongFilePaths.slice(0, 3).join(', ')}`);
  14133. } else if (this.modeType === 4) {
  14134. Logger.warn(TAG, `randomPlay: 歌单模式但没有歌曲路径列表! currentPlaylistSongFilePaths.length=${this.currentPlaylistSongFilePaths.length}`);
  14135. }
  14136. let randomLocalSong = await this.table.queryRandomSong(localOptions);
  14137. if (!randomLocalSong) {
  14138. this.playedLocalFilePaths.clear();
  14139. if (currentFilePath) {
  14140. this.playedLocalFilePaths.add(currentFilePath);
  14141. }
  14142. const fallbackLocalOptions: RandomSongQueryOptions = {
  14143. type: CommonConstants.TYPE_LOCAL,
  14144. excludeFilePaths: currentFilePath ? [currentFilePath] : []
  14145. };
  14146. // fallback时也要保持modeType的过滤条件
  14147. if (this.modeType === 0 && this.currentPath) {
  14148. fallbackLocalOptions.parentPath = this.currentPath;
  14149. } else if (this.modeType === 4 && this.currentPlaylistSongFilePaths.length > 0) {
  14150. fallbackLocalOptions.playlistSongFilePaths = this.currentPlaylistSongFilePaths;
  14151. }
  14152. randomLocalSong = await this.table.queryRandomSong(fallbackLocalOptions);
  14153. }
  14154. if (randomLocalSong !== null) {
  14155. const selectedLocalSong = randomLocalSong;
  14156. let nextIndex = this.songList.findIndex(song => song.filePath === selectedLocalSong.filePath);
  14157. if (nextIndex < 0) {
  14158. this.songList = [...this.songList, selectedLocalSong];
  14159. this.sonDataSource.pushArrayData(this.songList);
  14160. nextIndex = this.songList.length - 1;
  14161. }
  14162. this.curIndex = nextIndex;
  14163. this.playedIndices.add(this.curIndex);
  14164. this.CONTROL_PlayStatus = PlayStatus.INIT;
  14165. this.stop();
  14166. this.currentSong = selectedLocalSong;
  14167. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  14168. context: this.context,
  14169. autoParseMusicName: this.autoParseMusicName
  14170. });
  14171. this.name = this.currentSong.name;
  14172. this.artist = this.currentSong.artist;
  14173. this.changeImageAnimation();
  14174. return;
  14175. }
  14176. Logger.warn(TAG, '随机播放未获取到本地歌曲,回退到列表随机');
  14177. }
  14178. }
  14179. if (ArrayUtil.isNotEmpty(this.songList)) {
  14180. if (this.curIndex >= 0 && this.curIndex < this.songList.length) {
  14181. this.playedIndices.add(this.curIndex);
  14182. }
  14183. if (this.songList.length > 3) {
  14184. // 优先使用预缓存的随机索引(仅网盘播放时)
  14185. const nextSong = this.songList[this.preloadNextRandomIndex >= 0 ? this.preloadNextRandomIndex : 0];
  14186. const isNextRemote = nextSong && isRemoteCloudType(nextSong.type);
  14187. const isCurrentRemote = this.currentSong && isRemoteCloudType(this.currentSong.type);
  14188. if (this.preloadNextRandomIndex >= 0 && this.preloadNextRandomIndex < this.songList.length && isNextRemote && isCurrentRemote) {
  14189. Logger.info('heanup randomPlay', `使用预缓存的随机索引: ${this.preloadNextRandomIndex} (网盘播放)`);
  14190. this.curIndex = this.preloadNextRandomIndex;
  14191. this.playedIndices.add(this.curIndex);
  14192. this.preloadNextRandomIndex = -1; // 重置预缓存索引
  14193. // 立即预缓存下一首,避免下次点击时没有预缓存
  14194. void this.preloadNextSongInternal();
  14195. } else {
  14196. // 如果没有预缓存索引,则正常随机选择
  14197. // 如果所有歌曲都播放过一次,清空已播放索引集合
  14198. if (this.playedIndices.size === this.songList.length) {
  14199. this.playedIndices.clear();
  14200. }
  14201. // 随机选择一个未播放的歌曲索引
  14202. let newIndex: number;
  14203. // 添加超时机制防止无限循环
  14204. let attempt = 0;
  14205. const maxAttempts = 100; // 根据需求调整
  14206. do {
  14207. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  14208. attempt++;
  14209. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  14210. if (attempt >= maxAttempts) {
  14211. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  14212. newIndex = Math.floor(Math.random() * this.songList.length);
  14213. }
  14214. this.curIndex = newIndex;
  14215. this.playedIndices.add(newIndex);
  14216. }
  14217. } else {
  14218. // 当歌曲数量小于或等于3时,直接播放下一首
  14219. if (this.curIndex == this.songList.length - 1) {
  14220. this.curIndex = 0;
  14221. } else {
  14222. this.curIndex++;
  14223. }
  14224. }
  14225. this.CONTROL_PlayStatus = PlayStatus.INIT;
  14226. this.stop();
  14227. this.currentSong = this.songList[this.curIndex];
  14228. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  14229. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  14230. context: this.context,
  14231. autoParseMusicName: this.autoParseMusicName
  14232. });
  14233. this.name = this.songList[this.curIndex].name;
  14234. this.artist = this.songList[this.curIndex].artist
  14235. // this.cover = this.songList[this.curIndex].pixelMapPath
  14236. this.changeImageAnimation()
  14237. // 预缓存下一首(包括网盘和本地)
  14238. void this.preloadNextSongInternal();
  14239. }
  14240. }
  14241. private async playIndex(index: number) {
  14242. if (!this.debounce()) {
  14243. return;
  14244. }
  14245. if (ArrayUtil.isNotEmpty(this.songList)) {
  14246. this.curIndex = index;
  14247. this.currentSong = this.songList[index];
  14248. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  14249. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  14250. context: this.context,
  14251. autoParseMusicName: this.autoParseMusicName
  14252. });
  14253. this.name = this.currentSong.name
  14254. this.artist = this.currentSong.artist
  14255. // 如果是投播模式,需要为投播设备准备当前歌曲
  14256. if (this.castController && this.isCastPlaying) {
  14257. Logger.info('heanup playIndex', '投播模式播放指定歌曲,不调用本地stop()');
  14258. this.initQueueItem();
  14259. await this.prepare();
  14260. this.cover = this.currentSong.pixelMapPath;
  14261. return;
  14262. }
  14263. // 本地播放器模式,需要先stop
  14264. this.CONTROL_PlayStatus = PlayStatus.INIT;
  14265. this.stop();
  14266. this.changeImageAnimation()
  14267. }
  14268. }
  14269. //上一个
  14270. private async playPrevious() {
  14271. if (!this.debounce()) {
  14272. return;
  14273. }
  14274. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  14275. this.randomModePlayFromHistory()
  14276. return;
  14277. }
  14278. if (this.curIndex == 0) {
  14279. this.curIndex = this.songList.length - 1;
  14280. } else {
  14281. this.curIndex--;
  14282. }
  14283. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  14284. this.currentSong = this.songList[this.curIndex];
  14285. Logger.info('heanup playPrevious', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  14286. // 验证并修正webdav_account_id(针对远程类型歌曲)
  14287. if (isRemoteCloudType(this.currentSong.type) && this.currentSong.webdav_account_id) {
  14288. const manager = RemoteDriveManager.getInstance();
  14289. const account = await manager.getWebDavAccountById(this.currentSong.webdav_account_id);
  14290. if (!account) {
  14291. Logger.warn(TAG, `playPrevious: 歌曲账号ID无效: ${this.currentSong.webdav_account_id}, 尝试查找同类型账号`);
  14292. // 获取所有账号,查找相同类型的账号
  14293. const allAccounts = manager.getAllWebDavAccounts();
  14294. let foundAccount: WebDavAccount | null = null;
  14295. for (let i = 0; i < allAccounts.length; i++) {
  14296. if (allAccounts[i].webType === this.currentSong.type) {
  14297. foundAccount = allAccounts[i];
  14298. break;
  14299. }
  14300. }
  14301. if (foundAccount && foundAccount.id) {
  14302. Logger.info(TAG, `playPrevious: 找到同类型账号,更新webdav_account_id: ${this.currentSong.webdav_account_id} -> ${foundAccount.id}`);
  14303. this.currentSong.webdav_account_id = foundAccount.id.toString();
  14304. // 更新数据库记录
  14305. await this.table.updateWebDavAccountId(this.currentSong.filePath, foundAccount.id.toString());
  14306. } else {
  14307. Logger.error(TAG, `playPrevious: 无法找到类型为${this.currentSong.type}的账号,跳过此歌曲`);
  14308. // 跳过无效账号的歌曲,继续查找上一首
  14309. if (this.curIndex == 0) {
  14310. this.curIndex = this.songList.length - 1;
  14311. } else {
  14312. this.curIndex--;
  14313. }
  14314. this.currentSong = this.songList[this.curIndex];
  14315. }
  14316. }
  14317. }
  14318. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  14319. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  14320. context: this.context,
  14321. autoParseMusicName: this.autoParseMusicName
  14322. });
  14323. this.name = this.songList[this.curIndex].name
  14324. this.artist = this.songList[this.curIndex].artist
  14325. // 如果是投播模式,使用 CastController 切换上一首
  14326. if (this.castControllerWrapper) {
  14327. Logger.info('heanup playPrevious', '投播模式播放上一首,不调用本地stop()');
  14328. try {
  14329. const prevDuration = this.getSongDurationMs(this.currentSong);
  14330. if (prevDuration > 0) {
  14331. this.duration = prevDuration;
  14332. this.durationTime = Math.floor(prevDuration / 1000);
  14333. this.durationStringTime = secondToTime(this.durationTime);
  14334. this.totalTime = this.stringForTime(prevDuration);
  14335. this.avSessionController.setAVMetadataMusic(this.currentSong, prevDuration, this.lyricContent);
  14336. }
  14337. this.updateCastProgress(0);
  14338. await this.castControllerWrapper.playPrevious(this.songList, this.curIndex, this.videoUrl, prevDuration);
  14339. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  14340. } catch (error) {
  14341. Logger.error('heanup playPrevious', `CastController 播放上一首失败: ${error}`);
  14342. this.isCastPlaying = false;
  14343. }
  14344. this.cover = this.songList[this.curIndex].pixelMapPath;
  14345. return;
  14346. }
  14347. // 本地播放器模式,需要先stop
  14348. this.CONTROL_PlayStatus = PlayStatus.INIT;
  14349. this.stop();
  14350. this.changeImageAnimation()
  14351. }
  14352. //随机播放模式下点击上一首: 播放刚刚播放过的那一首
  14353. private async randomModePlayFromHistory() {
  14354. if (this.randomPlayHistory.length >= 1) {
  14355. // 播放历史栈的第一首(刚刚播放过的)
  14356. const prevSong = this.randomPlayHistory[0];
  14357. Logger.info('heanup randomModePlayFromHistory', `从随机播放历史栈获取歌曲: ${prevSong.name}, type: ${prevSong.type}, 栈大小: ${this.randomPlayHistory.length}`);
  14358. // 从栈中移除这首歌(因为即将播放它,它应该成为当前歌,而不是历史)
  14359. this.randomPlayHistory.shift();
  14360. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  14361. this.CONTROL_PlayStatus = PlayStatus.INIT;
  14362. this.stop();
  14363. // 验证并修正webdav_account_id(针对远程类型歌曲)
  14364. if (isRemoteCloudType(prevSong.type) && prevSong.webdav_account_id) {
  14365. const manager = RemoteDriveManager.getInstance();
  14366. const account = await manager.getWebDavAccountById(prevSong.webdav_account_id);
  14367. if (!account) {
  14368. Logger.warn(TAG, `randomModePlayFromHistory: 歌曲账号ID无效: ${prevSong.webdav_account_id}, 尝试查找同类型账号`);
  14369. const allAccounts = manager.getAllWebDavAccounts();
  14370. let foundAccount: WebDavAccount | null = null;
  14371. for (let i = 0; i < allAccounts.length; i++) {
  14372. if (allAccounts[i].webType === prevSong.type) {
  14373. foundAccount = allAccounts[i];
  14374. break;
  14375. }
  14376. }
  14377. if (foundAccount && foundAccount.id) {
  14378. Logger.info(TAG, `randomModePlayFromHistory: 找到同类型账号,更新webdav_account_id: ${prevSong.webdav_account_id} -> ${foundAccount.id}`);
  14379. prevSong.webdav_account_id = foundAccount.id.toString();
  14380. await this.table.updateWebDavAccountId(prevSong.filePath, foundAccount.id.toString());
  14381. } else {
  14382. Logger.error(TAG, `randomModePlayFromHistory: 无法找到类型为${prevSong.type}的账号`);
  14383. // 无法播放这首歌,继续尝试下一首历史记录
  14384. if (this.randomPlayHistory.length >= 1) {
  14385. this.randomModePlayFromHistory();
  14386. return;
  14387. } else {
  14388. // 历史记录为空,无法继续
  14389. ToastUtil.showToast('没有更多历史记录');
  14390. return;
  14391. }
  14392. }
  14393. }
  14394. }
  14395. this.currentSong = prevSong;
  14396. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  14397. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  14398. context: this.context,
  14399. autoParseMusicName: this.autoParseMusicName
  14400. });
  14401. this.cover = this.currentSong.pixelMapPath
  14402. this.artist = this.currentSong.artist
  14403. this.name = this.currentSong.name;
  14404. console.info('onecold startPlayOrResumePlay randomModePlayFromHistory')
  14405. this.startPlayOrResumePlay();
  14406. } else {
  14407. ToastUtil.showToast('随机播放模式暂无历史记录');
  14408. }
  14409. }
  14410. debounce() {
  14411. const delay = 600;
  14412. let cur = new Date().getTime();
  14413. if (cur - this.last > delay) {
  14414. this.last = cur;
  14415. return true;
  14416. }
  14417. return false;
  14418. }
  14419. /**
  14420. * Sets whether the screen is a constant based on the playback status.
  14421. */
  14422. watchStatus() {
  14423. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  14424. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  14425. this.windowClass.setWindowKeepScreenOn(true);
  14426. } else {
  14427. this.windowClass.setWindowKeepScreenOn(false);
  14428. }
  14429. }
  14430. /**
  14431. * Volume gesture method onActionStart.
  14432. *
  14433. * @param event Gesture event.
  14434. */
  14435. private customDialogComponentIdMM: number = 0
  14436. @Builder
  14437. customDialogComponentMM() {
  14438. Column() {
  14439. Row() {
  14440. Blank()
  14441. Text('验证密码')
  14442. .fontSize(22)
  14443. .fontColor($r('app.color.pri_bg'))
  14444. .margin({ top: 18 })
  14445. Blank()
  14446. Image($r('app.media.close'))
  14447. .fillColor(Color.White)
  14448. .margin({ top: 18, right: 18 })
  14449. .width(20)
  14450. .onClick(() => {
  14451. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  14452. })
  14453. }
  14454. .width('100%') // 使Row占据整个宽度
  14455. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  14456. Verify({
  14457. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  14458. });
  14459. }.height('60%')
  14460. .backgroundColor($r('app.color.index_background'))
  14461. .justifyContent(FlexAlign.SpaceBetween)
  14462. }
  14463. private handleVerifyCompleted(isSuccess: boolean) {
  14464. if (isSuccess) {
  14465. console.log('验证成功');
  14466. // 在这里处理验证成功后的逻辑
  14467. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  14468. this.currentPath = this.lockPath
  14469. this.getSortedFiles(this.currentPath)
  14470. } else {
  14471. // console.log('验证失败');
  14472. ToastUtil.showToast('验证失败')
  14473. }
  14474. }
  14475. private showVerifyDialog() {
  14476. promptAction.openCustomDialog({
  14477. transition: TransitionEffect.asymmetric(
  14478. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  14479. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  14480. ,
  14481. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  14482. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  14483. ),
  14484. builder: () => {
  14485. this.customDialogComponentMM()
  14486. },
  14487. isModal: true,
  14488. autoCancel: true,
  14489. maskColor: Color.Transparent,
  14490. alignment: DialogAlignment.Bottom,
  14491. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  14492. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  14493. console.log("dialog onWillDismiss")
  14494. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  14495. dismissDialogAction.dismiss()
  14496. }
  14497. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  14498. dismissDialogAction.dismiss()
  14499. }
  14500. }
  14501. }).then((dialogId: number) => {
  14502. this.customDialogComponentIdMM = dialogId
  14503. })
  14504. }
  14505. //左滑操作 移动文件 重命名 删除等操作
  14506. @Builder
  14507. DeleteButton(item: VideoItem, index: number, filePath: string) {
  14508. Row() {
  14509. //加入收藏
  14510. Button() {
  14511. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  14512. .fillColor(Color.White)
  14513. .width(20)
  14514. }
  14515. .width(40)
  14516. .height(40)
  14517. .type(ButtonType.Circle)
  14518. .backgroundColor(this.themeColor)
  14519. .margin(5)
  14520. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  14521. .onClick(() => {
  14522. if (item) {
  14523. this.doFav(item)
  14524. }
  14525. })
  14526. //加入下一首播放
  14527. Button() {
  14528. Image($r('app.media.next_to_play'))
  14529. .fillColor(Color.White)
  14530. .width(20)
  14531. }
  14532. .width(40)
  14533. .height(40)
  14534. .type(ButtonType.Circle)
  14535. .backgroundColor(this.themeColor)
  14536. .margin(5)
  14537. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  14538. .onClick(() => {
  14539. this.addToNextPlay(item);
  14540. })
  14541. //复制文件
  14542. Button() {
  14543. Image($r('app.media.copy'))
  14544. .fillColor(Color.White)
  14545. .width(20)
  14546. }
  14547. .width(40)
  14548. .height(40)
  14549. .type(ButtonType.Circle)
  14550. .backgroundColor(this.themeColor)
  14551. .margin(5)
  14552. .id(filePath + 'copy')
  14553. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  14554. .onClick(() => {
  14555. this.showCopyDialog(false, item, index, filePath + 'copy');
  14556. })
  14557. //移动文件
  14558. Button() {
  14559. Image($r('app.media.cut'))
  14560. .fillColor(Color.White)
  14561. .width(20)
  14562. }
  14563. .width(40)
  14564. .height(40)
  14565. .type(ButtonType.Circle)
  14566. .backgroundColor(this.themeColor)
  14567. .margin(5)
  14568. .id(filePath)
  14569. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  14570. .onClick(() => {
  14571. this.showCutDialog(false, item, index, filePath);
  14572. })
  14573. Button() {
  14574. Image($r('app.media.cut_current'))
  14575. .fillColor(Color.White)
  14576. .width(20)
  14577. }
  14578. .width(40)
  14579. .height(40)
  14580. .type(ButtonType.Circle)
  14581. .backgroundColor(this.themeColor)
  14582. .margin(5)
  14583. .id(filePath + 'current')
  14584. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  14585. (this.isHasDir ? Visibility.Visible : Visibility.None))
  14586. .onClick(() => {
  14587. this.showCutDialog(true, item, index, filePath + 'current');
  14588. })
  14589. //重命名
  14590. Button() {
  14591. Image($r('app.media.rename2'))
  14592. .fillColor(Color.White)
  14593. .width(20)
  14594. }
  14595. .width(40)
  14596. .height(40)
  14597. .type(ButtonType.Circle)
  14598. .backgroundColor(this.themeColor)
  14599. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  14600. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  14601. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  14602. .margin(5)
  14603. .onClick(() => {
  14604. this.showReNameDialog(item, index + '', filePath)
  14605. })
  14606. Button() {
  14607. Image($r('app.media.delete2'))
  14608. .fillColor(Color.White)
  14609. .width(20)
  14610. }
  14611. .width(40)
  14612. .height(40)
  14613. .type(ButtonType.Circle)
  14614. .backgroundColor(this.themeColor)
  14615. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  14616. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  14617. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  14618. .margin(5)
  14619. .onClick(() => {
  14620. this.selectedFiles.push(item)
  14621. this.showWarnIsDelete()
  14622. // this.showWarnIsDeleteFile(item, index + '', filePath)
  14623. })
  14624. Button() {
  14625. Image($r('app.media.share2'))
  14626. .fillColor(Color.White)
  14627. .width(20)
  14628. }
  14629. .width(40)
  14630. .height(40)
  14631. .type(ButtonType.Circle)
  14632. .backgroundColor(this.themeColor)
  14633. .margin(5)
  14634. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  14635. .onClick(() => {
  14636. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  14637. })
  14638. }
  14639. }
  14640. /**
  14641. * 穿山甲banner广告
  14642. */
  14643. // private declare bannerAd: CSJNativeExpressAd;
  14644. // @State private status: string = "未加载"
  14645. // @State private isShowAd: boolean = false
  14646. // private declare mAdSlot: AdSlot;
  14647. // private mBiddingAdm = '' //服务端bidding才需要设置
  14648. // private expressLoadAdListener: NativeExpressAdListener = {
  14649. // /**
  14650. // * 加载失败的回调
  14651. // *
  14652. // * @param code
  14653. // * @param message
  14654. // */
  14655. // onError: (code: number, message: string) => {
  14656. // console.error("加载广告失败,code=" + code + ",message=" + message);
  14657. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  14658. // },
  14659. //
  14660. // /**
  14661. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  14662. // *
  14663. // * @param ads 返回的广告列表
  14664. // */
  14665. //
  14666. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  14667. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  14668. // if (ads && ads.length > 0) {
  14669. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  14670. // ad.setExpressInteractionListener({
  14671. // /**
  14672. // *广告的点击回调
  14673. // * @param type 广告的交互类型
  14674. // */
  14675. // onAdClicked: (type: number) => {
  14676. // console.log("BannerExpressAdPage==onAdClicked......");
  14677. // },
  14678. //
  14679. // /**
  14680. // * 广告的展示回调 每个广告仅回调一次
  14681. // * @param type 广告的交互类型
  14682. // */
  14683. // onAdShow: (type: number) => {
  14684. // console.log("BannerExpressAdPage==onAdShow......");
  14685. // },
  14686. //
  14687. // /**
  14688. // * 模板渲染失败
  14689. // */
  14690. // onRenderFail: (code: number, msg: string) => {
  14691. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  14692. // },
  14693. //
  14694. // /**
  14695. // * 模板渲染成功
  14696. // * @param width 返回view的宽 单位 vp
  14697. // * @param height 返回view的高 单位 vp
  14698. // */
  14699. // onRenderSuccess: (width: number, height: number) => {
  14700. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  14701. // this.bannerAd = ad;
  14702. // this.status = "广告加载完成待展示";
  14703. //
  14704. // this.showBannerAd()
  14705. // }
  14706. // })
  14707. // //渲染广告
  14708. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  14709. // this.setDislikeCallback(ad); //设置dislike
  14710. // ad.render(this.getUIContext())
  14711. // this.status = "广告加载中...";
  14712. // });
  14713. // }
  14714. // }
  14715. // }
  14716. //
  14717. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  14718. // ad.setDislikeCallback({
  14719. // /**
  14720. // * dislike show
  14721. // */
  14722. // onShow: () => {
  14723. // console.log("BannerExpressAdPage==dislike......show");
  14724. // },
  14725. //
  14726. // /**
  14727. // * @param position 选择的位置
  14728. // * @param value 选择的内容
  14729. // * @param enforceRemove 是否强制关闭广告
  14730. // */
  14731. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  14732. // this.isShowAd = false;
  14733. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  14734. // ",enforce=" + enforceRemove);
  14735. // },
  14736. //
  14737. // /**
  14738. // * 点击取消
  14739. // */
  14740. // onCancel: () => {
  14741. // console.log("BannerExpressAdPage==dislike......onCancel");
  14742. // }
  14743. //
  14744. // })
  14745. // }
  14746. /**
  14747. * 加载Banner广告
  14748. */
  14749. loadBannerAd(rit: string) {
  14750. // if (Utility.isNoble()) {
  14751. // return
  14752. // }
  14753. // if (!Utility.isPassInstallTime(2)) {
  14754. // return
  14755. // }
  14756. // this.isShowAd = false;
  14757. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  14758. // this.mAdSlot = new AdSlotBuilder()
  14759. // .setCodeId(rit)
  14760. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  14761. // .setAdCount(1)
  14762. // .setBidAdm(this.mBiddingAdm)
  14763. // .build()
  14764. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  14765. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  14766. // this.status = "广告加载中..."
  14767. }
  14768. /**
  14769. * 展示Banner广告
  14770. */
  14771. // showBannerAd() {
  14772. // if (!this.bannerAd) {
  14773. // return
  14774. // }
  14775. // this.isShowAd = true
  14776. // this.status = "已展示"
  14777. // }
  14778. /**
  14779. * 穿山甲广告代码结束
  14780. */
  14781. /**
  14782. * 处理歌单播放请求
  14783. */
  14784. private async handlePlaylistPlayRequest(playlistId: string, playlistName:
  14785. string, songFilePaths: string[], startIndex: number,isJump: boolean) {
  14786. try {
  14787. Logger.info(`heanup 处理歌单播放请求: ${playlistName}, 歌曲数量: ${songFilePaths.length}, 开始索引: ${startIndex}`)
  14788. // 检查是否为WebDAV播放请求
  14789. if (playlistId === 'webdav-playlist') {
  14790. Logger.info(`heanup 检测到WebDAV播放请求,从内存读取videoItems`)
  14791. // 从全局内存读取videoItems数据
  14792. const videoItems = getWebdavVideoItems();
  14793. const currentPlayIndex = getWebdavCurrentPlayIndex();
  14794. Logger.info(`heanup 从内存读取到WebDAV歌曲列表,长度:${videoItems.length},索引:${currentPlayIndex}`)
  14795. if (videoItems && videoItems.length > 0) {
  14796. // 验证webdav_account_id设置情况
  14797. const accountIds = videoItems.map(item => item.webdav_account_id).filter(id => id);
  14798. Logger.info(`heanup 有 ${accountIds.length}/${videoItems.length} 首歌曲设置了webdav_account_id`)
  14799. if(isJump){
  14800. this.setShowPlayTrue()//显示播放页
  14801. }
  14802. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName)
  14803. return
  14804. } else {
  14805. return
  14806. }
  14807. }
  14808. if (playlistId === 'navidrome-playlist') {
  14809. Logger.info(`heanup 检测到Navidrome播放请求,从内存读取videoItems`);
  14810. const videoItems = getNavidromeVideoItems();
  14811. const currentPlayIndex = getNavidromeCurrentPlayIndex();
  14812. Logger.info(`heanup Navidrome歌曲列表长度: ${videoItems.length}`);
  14813. if (videoItems && videoItems.length > 0) {
  14814. if(isJump){
  14815. this.setShowPlayTrue()//显示播放页
  14816. }
  14817. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName);
  14818. return;
  14819. } else {
  14820. Logger.warn('heanup Navidrome播放请求缺少歌曲数据');
  14821. return;
  14822. }
  14823. }
  14824. // 从数据库重新加载这些歌曲,使用索引记录位置以保持顺序
  14825. const songMap: Map<number, VideoItem> = new Map()
  14826. let completedQueries = 0
  14827. Logger.info(`heanup 开始从数据库查询 ${songFilePaths.length} 首歌曲`)
  14828. // 遍历所有文件路径,使用索引记录位置
  14829. for (let i = 0; i < songFilePaths.length; i++) {
  14830. const filePath = songFilePaths[i]
  14831. const index = i
  14832. // Logger.info(`heanup 正在查询歌曲[${index}]: ${filePath}`)
  14833. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  14834. const queryPromise = this.table.queryVideoByFilePath(filePath)
  14835. // Logger.info(`heanup 创建了查询Promise,开始等待结果[${index}]: ${filePath}`)
  14836. queryPromise.then((videoItem) => {
  14837. completedQueries++
  14838. // Logger.info(`heanup 查询Promise返回结果[${index}]: ${filePath}, 找到歌曲: ${videoItem ? videoItem.name : 'null'}`)
  14839. if (videoItem) {
  14840. // 使用索引作为key保存到Map中,保持原始顺序
  14841. songMap.set(index, videoItem)
  14842. // Logger.info(`heanup 从数据库找到歌曲[${index}]: ${videoItem.name} (${completedQueries}/${songFilePaths.length})`)
  14843. } else {
  14844. Logger.warn(`heanup 数据库中未找到歌曲[${index}]: ${filePath} (${completedQueries}/${songFilePaths.length})`)
  14845. }
  14846. // 检查是否所有歌曲都已加载完成
  14847. if (completedQueries === songFilePaths.length) {
  14848. // Logger.info(`heanup 所有数据库查询完成,共找到 ${songMap.size} 首歌曲`)
  14849. // 按照索引顺序重建歌曲数组
  14850. const songs: VideoItem[] = []
  14851. for (let j = 0; j < songFilePaths.length; j++) {
  14852. const song = songMap.get(j)
  14853. if (song) {
  14854. songs.push(song)
  14855. // Logger.info(`heanup 按顺序添加歌曲[${j}]: ${song.name}`)
  14856. }
  14857. }
  14858. Logger.info(`heanup 最终歌曲列表顺序: ${songs.map((s, idx) => `[${idx}]${s.name}`).join(', ')}`)
  14859. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  14860. }
  14861. }).catch((error: Error) => {
  14862. completedQueries++
  14863. Logger.error(`heanup 查询歌曲失败[${index}]: ${filePath}, 错误: ${error.message} (${completedQueries}/${songFilePaths.length})`)
  14864. // 即使出错也要检查是否完成所有查询
  14865. if (completedQueries === songFilePaths.length) {
  14866. Logger.info(`heanup 所有数据库查询完成(包含错误),共找到 ${songMap.size} 首歌曲`)
  14867. // 按照索引顺序重建歌曲数组
  14868. const songs: VideoItem[] = []
  14869. for (let j = 0; j < songFilePaths.length; j++) {
  14870. const song = songMap.get(j)
  14871. if (song) {
  14872. songs.push(song)
  14873. }
  14874. }
  14875. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  14876. }
  14877. })
  14878. }
  14879. } catch (error) {
  14880. Logger.error('heanup 处理简化歌单播放请求失败: ' + error)
  14881. ToastUtil.showToast('播放失败')
  14882. }
  14883. }
  14884. /**
  14885. * 完成歌单加载并开始播放
  14886. */
  14887. private finishLoadingPlaylist(songs: VideoItem[], startIndex: number, playlistName: string) {
  14888. if (songs.length === 0) {
  14889. Logger.error('heanup 没有找到任何可播放的歌曲')
  14890. ToastUtil.showToast('没有找到可播放的歌曲')
  14891. return
  14892. }
  14893. this.songList = songs
  14894. this.sonDataSource.pushArrayData(songs)
  14895. this.sonDataSource.notifyDataReload()
  14896. this.curIndex = startIndex
  14897. // 保存歌单的歌曲路径列表,用于随机播放
  14898. this.currentPlaylistSongFilePaths = songs.map(song => song.filePath);
  14899. Logger.info('heanup finishLoadingPlaylist', `保存歌单歌曲路径列表,数量=${this.currentPlaylistSongFilePaths.length}`);
  14900. if (songs[startIndex]) {
  14901. // 确保当前播放的歌曲也更新到存储
  14902. AppStorage.setOrCreate('currentSong', songs[startIndex])
  14903. // 设置isFromSonPlayList=true,避免doPlay方法重新从全局列表构建播放列表
  14904. this.doPlay(songs[startIndex], startIndex, true)
  14905. }
  14906. PreferencesUtil.putSync('LastMusicList', this.songList)
  14907. // ToastUtil.showToast(`开始播放歌单: ${playlistName}`)
  14908. }
  14909. }
  14910. //视频气泡窗口的布局
  14911. @Builder
  14912. function customPopupBuilder(dataBu: BubbleBean) {
  14913. List() {
  14914. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  14915. ListItem() {
  14916. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  14917. Row() {
  14918. Column() {
  14919. Image(dataBu.imageRes[index])
  14920. .height(28)
  14921. .fillColor(dataBu.color)
  14922. .alignSelf(ItemAlign.Center)
  14923. }
  14924. .width(32)
  14925. Text(item)
  14926. .padding({
  14927. top: 10,
  14928. bottom: 10,
  14929. right: 10,
  14930. left: 10
  14931. })
  14932. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  14933. .textAlign(TextAlign.Start)
  14934. .width("100%")
  14935. }
  14936. }
  14937. .backgroundColor($r('app.color.settings_background_main'))
  14938. .margin({ top: 6, bottom: 6 })
  14939. }
  14940. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  14941. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  14942. TransitionEffect.scale({ x: 0, y: 0 })))
  14943. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  14944. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  14945. .onClick(() => {
  14946. dataBu.onItemClick?.(index)
  14947. })
  14948. })
  14949. }
  14950. .scrollBar(BarState.Off)
  14951. .width(120)
  14952. .divider({
  14953. strokeWidth: 1,
  14954. color: "#22FFFFFF"
  14955. })
  14956. }
  14957. // Function to calculate a hash for the file list
  14958. function simpleHash(fileList: string[]): string {
  14959. let hash = 0;
  14960. const str = fileList.join(',');
  14961. for (let i = 0; i < str.length; i++) {
  14962. const char = str.charCodeAt(i);
  14963. hash = (hash << 5) - hash + char;
  14964. hash |= 0; // Convert to 32bit integer
  14965. }
  14966. return hash.toString();
  14967. }
  14968. interface MoreItem {
  14969. id: number;
  14970. image: Resource;
  14971. title: string;
  14972. }
  14973. //视频气泡窗口的布局
  14974. @Builder
  14975. function cutPopupBuilder(dataBu: BubbleBean) {
  14976. Column() {
  14977. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  14978. .padding({
  14979. top: 10,
  14980. bottom: 10,
  14981. right: 10,
  14982. left: 10
  14983. })
  14984. .textAlign(TextAlign.Start)
  14985. .width(160)
  14986. .fontWeight(666)
  14987. .fontSize(16)
  14988. List() {
  14989. ForEach(dataBu.data, (item: string, index: number) => {
  14990. ListItem() {
  14991. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  14992. Row() {
  14993. Column() {
  14994. Image($r('app.media.music_group'))
  14995. .height(28)
  14996. .fillColor(dataBu.color)
  14997. .alignSelf(ItemAlign.Center)
  14998. }
  14999. .width(32)
  15000. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  15001. .padding({
  15002. top: 10,
  15003. bottom: 10,
  15004. right: 10,
  15005. left: 10
  15006. })
  15007. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  15008. .fontSize(15)
  15009. }
  15010. }
  15011. .backgroundColor(Color.Transparent)
  15012. .margin({ top: 7, bottom: 7 })
  15013. }
  15014. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  15015. .animation({ duration: 500 }),
  15016. TransitionEffect.scale({ x: 0, y: 0 })))
  15017. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  15018. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  15019. .onClick(() => {
  15020. dataBu.onItemClick?.(index)
  15021. })
  15022. })
  15023. }
  15024. .scrollBar(BarState.Off)
  15025. .width(150)
  15026. .divider({
  15027. strokeWidth: 1,
  15028. color: "#22FFFFFF"
  15029. })
  15030. }
  15031. .height(300)
  15032. .padding({
  15033. bottom: 30
  15034. })
  15035. }
  15036. function getFileDirName(filePath: string,rootPath:string): string{
  15037. if(filePath===rootPath){
  15038. return '首页'
  15039. }
  15040. let result = FileUtil.getFileName(filePath)
  15041. if(StrUtil.isEmpty(result))
  15042. return ''
  15043. if(result.startsWith('.'))
  15044. result = result.replace(/\./g, '')
  15045. return result
  15046. }
  15047. //只扫描当前目录下文件(不扫描子文件夹)的方法
  15048. @Concurrent
  15049. async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
  15050. const table: MediaTable = new MediaTable(context);
  15051. try {
  15052. // 直接获取当前目录下的文件列表
  15053. const files = FileUtil.listFileSync(dirPath);
  15054. await Promise.all(files.map(async (file) => {
  15055. const fPath = `${dirPath}/${file}`;
  15056. // 跳过目录,只处理文件
  15057. if (FileUtil.isDirectory(fPath)) {
  15058. return;
  15059. }
  15060. // 跳过特定格式文件
  15061. if (fPath.endsWith('.lrc') || fPath.endsWith('.srt')) {
  15062. return;
  15063. }
  15064. // 检查是否为媒体文件
  15065. if (Utility.isMeidaByExtension(fPath)) {
  15066. let mType = CommonConstants.TYPE_LOCAL;
  15067. if (fPath.includes(lockPath)) {
  15068. mType = CommonConstants.TYPE_LOCK;
  15069. }
  15070. const mediaItem = await Utility.uriGetMusicAssetsFromFile(
  15071. context, fPath, mType, true
  15072. );
  15073. table.insert(mediaItem, (id: number) => {
  15074. // 插入回调函数
  15075. }, cover_api);
  15076. }
  15077. }));
  15078. } catch (error) {
  15079. console.error(' 扫描当前目录失败:', error);
  15080. }
  15081. }
  15082. //内嵌标签后更新库
  15083. @Concurrent
  15084. async function updateInfoDb(
  15085. context: Context,
  15086. filePath: string,
  15087. titleStr: string,
  15088. artistStr: string,
  15089. albumStr: string,
  15090. lyricConStr: string,
  15091. yearStr: string,
  15092. genreStr: string,
  15093. trackStr: string,
  15094. albumArtistStr: string,
  15095. composerStr: string,
  15096. lyricistStr: string,
  15097. commentStr: string,
  15098. discStr: string,
  15099. ): Promise<boolean> {
  15100. const table: MediaTable = new MediaTable(context);
  15101. await new Promise<void>((resolve, reject) => {
  15102. table.getRdbStore(context, (err:Error) => {
  15103. err ? reject(err) : resolve();
  15104. });
  15105. });
  15106. return await new Promise<boolean>((resolve) => {
  15107. table.updateMediaInfo(filePath, titleStr, artistStr, albumStr, lyricConStr,
  15108. yearStr, genreStr, trackStr, albumArtistStr, composerStr, lyricistStr, commentStr, discStr,
  15109. (success: boolean, error?: string) => {
  15110. if (success) {
  15111. console.log("onecold 编辑信息成功,数据库已同步");
  15112. } else {
  15113. console.error("onecold 编辑信息数据库失败原因: " + error);
  15114. }
  15115. resolve(success);
  15116. });
  15117. });
  15118. }