LocalMusic.ets 570 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374
  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. ButtonFancyModifier,
  9. ImageFancyModifier,
  10. ShadowModifier,
  11. SymbolGlyphFancyModifier } from '../common/util/AttributeModifierUtil'
  12. import {
  13. AppUtil,
  14. ArrayUtil,
  15. Base64Util,
  16. DateUtil,
  17. DeviceUtil,
  18. FileUtil,
  19. GlobalContext,
  20. LogUtil,
  21. MD5,
  22. PreferencesUtil,
  23. RandomUtil,
  24. StrUtil,
  25. ToastUtil
  26. } from '@pura/harmony-utils';
  27. import { imagePathToPixelMap } from '../common/util/CommUtils';
  28. import { unifiedDataChannel, uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData';
  29. import { CommonConstants } from '../common/constants/CommonConstants';
  30. import { BaiduConstants } from '../common/constants/BaiduConstants';
  31. import { EventConstants } from '../common/constants/EventConstants';
  32. import Logger from '../common/util/Logger';
  33. import { http } from '@kit.NetworkKit';
  34. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  35. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  36. import { BubbleBean } from '../viewmodel/BubbleBean';
  37. import { PopupPosition, XPopup } from '@chinalike/popup';
  38. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  39. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  40. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  41. import { MessageEvents, util, worker, ErrorEvent, JSON } from '@kit.ArkTS';
  42. import { Verify } from './Verify';
  43. import { taskpool } from '@kit.ArkTS';
  44. import { RotatingCover } from './RotatingCover';
  45. import { PointLightButton } from './PointLight/PointLightButton';
  46. import { PlayConstants } from '../common/constants/PlayConstants';
  47. import { effectKit } from '@kit.ArkGraphics2D';
  48. import { ColorConversion } from '../common/util/ColorConversion';
  49. import { Lyric, LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  50. import { AvSessionController } from '../controller/AvSessionController';
  51. import { CastController, CastControllerCallbacks } from '../controller/CastController';
  52. import { repairAudioMetadata, convertDsfToWav, getApiLyric,changeMusicCover} from '../common/util/MusicTagUtils';
  53. import { extractHwMediaMetadata, FFMpegTags,Utility } from '../common/util/Utility';
  54. import { TagsContentCover } from '../view/TagsContentCover';
  55. import {
  56. DeviceChangeReason,
  57. IjkMediaPlayer,
  58. InterruptEvent,
  59. InterruptHintType,
  60. LogUtils,
  61. OnBufferingUpdateListener,
  62. OnCompletionListener,
  63. OnErrorListener,
  64. OnInfoListener,
  65. OnPreparedListener,
  66. OnSeekCompleteListener,
  67. OnTimedTextListener,
  68. OnVideoSizeChangedListener
  69. } from '@ohos/ijkplayer';
  70. import { PlayStatus } from '../common/PlayStatus';
  71. import fs from '@ohos.file.fs';
  72. import { image } from '@kit.ImageKit';
  73. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  74. import { media } from '@kit.MediaKit';
  75. import { UniversalDetector } from '@ohos/juniversalchardet';
  76. import { SettingPage } from '../pages/SettingPage';
  77. import { secondToTime,getTransverterText } from '../common/util/CommUtils';
  78. import { CommonConstants2 } from '../common/util/CommonConstants2';
  79. import { hilog } from '@kit.PerformanceAnalysisKit';
  80. import { LazyDataSource } from '../common/util/LazyDataSource';
  81. import MediaTable, { PageQueryOptions, PageQueryResult, RandomSongQueryOptions } from '../common/util/MediaTable';
  82. import FileDeletionWatcher from '../common/util/FileDeletionWatcher';
  83. import LyricUtil from '../common/util/LyricUtil';
  84. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  85. import { ringtone } from '@kit.RingtoneKit';
  86. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  87. import { resourceManager } from '@kit.LocalizationKit';
  88. import { deviceInfo } from '@kit.BasicServicesKit';
  89. import '../common/network/RemoteCacheRegistry';
  90. import { ServerLogUtil } from '../common/util/ServerLogUtil';
  91. import { lyricService, SongData } from '../common/service/LyricService';
  92. import {
  93. cloneVideoItem,
  94. preloadNextSongIfNeeded,
  95. setVideoUrlForSong,
  96. getTypeOrder,
  97. isWebDavType,
  98. isSmbType,
  99. isNavidromeType,
  100. isFtpType,
  101. isBaiduType,
  102. isJellyfinType,
  103. isEmbyType,
  104. isAudioStationType,
  105. isPlexType,
  106. isRemoteCloudType,
  107. WorkerEditMusicResult,
  108. WebDavMetadataUpdatePayload
  109. } from '../common/util/RemotePlayerUtil';
  110. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  111. import app from '@system.app';
  112. import { TextNodeController } from './PipLyricTextBuilder';
  113. import { IndexerView } from './IndexerView';
  114. import { KeyCode } from '@kit.InputKit';
  115. import { KnockController } from '../controller/KnockController';
  116. import { DeleteComptent } from '../view/DeleteComptent';
  117. import { ABLoopComptent } from '../view/ABLoopComptent';
  118. import { FixMessyView } from '../view/FixMessyView';
  119. import { parseCueFile,CueTrack,CueInfo } from '../common/util/CueUtils';
  120. import { CueComptent } from '../view/CueComptent';
  121. import PlaylistTable from '../common/util/PlaylistTable';
  122. import { showAddToPlaylistDialog } from '../dialog/AddToPlaylistDialog';
  123. import { showCreatePlaylistDialog } from '../dialog/PlaylistDialog';
  124. import { convertPlaylistSongsToVideoItems, emptyView,updateAllSongsSortOrder } from '../pages/PlaylistDetailPage';
  125. import { Playlist, PlaylistSong } from '../viewmodel/Playlist';
  126. import { Song } from '../viewmodel/Song';
  127. import { WebDavAccount } from '../viewmodel/WebDavAccount';
  128. import { SongType } from '../common/enums/SongType';
  129. import { RemoteDriveManager, WebDavAuthInfo as WebDavManagerAuthInfo,
  130. buildHttpHeadersWithWebDav,
  131. WebDavAuthItem} from '../common/util/RemoteDriveManager';
  132. import PermissionUtil from '../common/util/PermissionUtil'
  133. import { EditAudio, setRingTone } from './EditAudio';
  134. import { ExtractAccompaniment } from './ExtractAccompaniment';
  135. import { ExtractAudioFromVideo } from './ExtractAudioFromVideo';
  136. import { AudioFormatConverter } from './AudioFormatConverter';
  137. import { MergeAudio } from './MergeAudio';
  138. import { AIVoiceSeparation } from './AIVoiceSeparation';
  139. import { WebDavUrlUtil } from '../common/util/WebDavUrlUtil';
  140. import { ChangeTone } from './ChangeTone';
  141. import {
  142. hdsEffect,
  143. HdsVisualComponent,
  144. HdsSceneController,
  145. HdsSceneType,
  146. HdsVisualComponentAttribute,
  147. } from '@kit.UIDesignKit';
  148. import { GlobalAlphabetIndexerModifier } from '../Styels/GlobalStyles'
  149. import { getFirstLetter } from '../Constants';
  150. import { audio } from '@kit.AudioKit';
  151. import { PointLightDefaultButton } from './PointLight/PointLightDeFaultButton';
  152. const TAG = 'LocalMusic';
  153. const HICAR_LOG_TAG = 'HiCarWindow';
  154. function logHiCarWindow(message: string): void {
  155. void ServerLogUtil.info(HICAR_LOG_TAG, message);
  156. }
  157. export interface WorkerMetadataPayload {
  158. originFilePath: string;
  159. originId?: string;
  160. bit_rate?: string;
  161. duration?: string;
  162. sampleRate?: string;
  163. mimeType?: string;
  164. md5Str?: string;
  165. videoSize?: number;
  166. size?: string;
  167. pixelMapPath?: string;
  168. artist?: string;
  169. album?: string;
  170. name?: string;
  171. lyricContent?: string;
  172. bits_per_raw_sample?: string;
  173. channels?: string;
  174. channel_layout?: string;
  175. start_time?: string;
  176. genre?: string;
  177. year?: string;
  178. probe_score?: number;
  179. track?: string;
  180. disc?: string;
  181. ALBUMARTIST?: string;
  182. COMPOSER?: string;
  183. COMMENT?: string;
  184. LYRICIST?: string;
  185. nb_streams?: number;
  186. nb_programs?: number;
  187. error?: string;
  188. }
  189. interface WorkerMessageScanDone {
  190. code: 101;
  191. data: Record<string, never>;
  192. }
  193. interface WorkerMessageMediaList {
  194. code: 102;
  195. data: Array<VideoItem>;
  196. totalCount: number;
  197. }
  198. interface WorkerMessageArtistList {
  199. code: 103;
  200. data1: Map<string, Array<VideoItem>>;
  201. data2: Array<VideoItem>;
  202. totalCount: number;
  203. }
  204. interface WorkerMessageAlbumList {
  205. code: 104;
  206. data1: Map<string, Array<VideoItem>>;
  207. data2: Array<VideoItem>;
  208. totalCount: number;
  209. }
  210. interface WorkerMessageMetadata {
  211. code: 105;
  212. data: WorkerMetadataPayload;
  213. }
  214. interface WorkerMessageEditResult {
  215. code: 106;
  216. data: WorkerEditMusicResult;
  217. }
  218. type LocalMusicWorkerMessage =
  219. WorkerMessageScanDone
  220. | WorkerMessageMediaList
  221. | WorkerMessageArtistList
  222. | WorkerMessageAlbumList
  223. | WorkerMessageMetadata
  224. | WorkerMessageEditResult;
  225. /**
  226. * 歌单播放事件数据
  227. */
  228. interface PlaylistEventData {
  229. playlistId: string;
  230. playlistName: string;
  231. songCount: number;
  232. startIndex: number;
  233. songFilePaths: string[];
  234. isJump: boolean;
  235. webDavAuthInfo?: WebDavAuthItem; // 新增WebDAV认证信息
  236. }
  237. const DEFAULT_INDEX =
  238. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  239. 'X', 'Y', 'Z']
  240. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  241. // 元数据提取状态追踪
  242. const metadataExtractionInFlight: Map<string, Promise<void>> = new Map();
  243. // setVideoUrlForSong 函数已移至 MusicPlayerUtil.ets
  244. // 定义接口
  245. interface HiCarAspectRatio {
  246. ratio: number;
  247. name: string;
  248. }
  249. interface GeneratedObjectLiteralInterface_1 {
  250. assetId: string;
  251. title: string;
  252. artist: string;
  253. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  254. mediaUri: string;
  255. // 该字段大写,音频'AUDIO',视频'VIDEO'
  256. mediaType: string;
  257. mediaSize: number;
  258. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  259. startPosition: number;
  260. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  261. duration: number;
  262. albumCoverUri: string;
  263. albumTitle: string;
  264. appName: string;
  265. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  266. drmScheme: string;
  267. }
  268. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  269. const ITEM_HEIGHT: number = 65; // 列表项中高度
  270. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  271. //功能强大的音乐播放器
  272. @Preview
  273. @Component
  274. export struct LocalMusic {
  275. @State showFindLocation: boolean = true
  276. @StorageProp("EnablePointLight") enablePointLight: boolean = true
  277. @State showSimple: boolean = true//开启沉浸模式
  278. @State isPaging: boolean = true;//是否分页加载机制
  279. @State isCoverRectangle: boolean = true;
  280. @State showZMIndex: boolean = false //是否右侧显示字母索引
  281. private prevOffsetY: number = 0; // 记录上一次的Y轴偏移量
  282. @State autoHideTitle: boolean = true //滚动自动隐藏标题栏
  283. // 字母表
  284. @State alphaBet: string[] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
  285. 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  286. @State alphaBetStyle: GlobalAlphabetIndexerModifier = new GlobalAlphabetIndexerModifier()
  287. @State selectAlphaBetIndex: number = 0
  288. @State isShowAlphaBet: boolean = false
  289. @State isScrolling: boolean = false
  290. @State isTouchingAlphaBet: boolean = false
  291. @State alphabetHeight: number = 0
  292. public enableShowAlphabet: boolean = true // 是否显示字母表
  293. private alphaBetHideTimer: number = 0
  294. private alphaBetCacheKey: string = ''
  295. @State isShowPrecious: boolean = false //播控条显示上一首按钮
  296. //背景两侧流光控制器
  297. @State sceneBgController: HdsSceneController|undefined = deviceInfo.sdkApiVersion>=20
  298. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  299. new HdsSceneController()
  300. .setSceneParams({
  301. backgroundMaskColors: [Color.Green, Color.Red],
  302. firstEdgeFlowLight: {
  303. startPos: 0,
  304. endPos: 0.5,
  305. color: Color.Red
  306. },
  307. secondEdgeFlowLight: {
  308. startPos: 0,
  309. endPos: -0.5,
  310. color: Color.Green
  311. }
  312. }) : undefined;
  313. //背景流光控制器
  314. @State bgController: hdsEffect.ShaderEffectController|undefined = deviceInfo.sdkApiVersion>=20
  315. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  316. new hdsEffect.ShaderEffectController():undefined;
  317. @State showAddSheet:boolean = false
  318. private loadingDialogId: string = ''
  319. private loadingProgressDialogId: string = ''
  320. searchController: SearchController = new SearchController()
  321. @State rightTopImage:Resource = $r('sys.symbol.sort')
  322. @State isEditAudio:boolean = false
  323. @State isExtractAcc:boolean = false
  324. @State isConverter:boolean = false
  325. @State isAIVoiceSeparation:boolean = false
  326. @State isExtractAudio:boolean = false
  327. @State isMergeAudio:boolean = false
  328. @State isCopyFileToDownLoad: boolean = false
  329. @State isChangeTone:boolean = false
  330. @State offHeight: number = 75
  331. @State currentSongList: Array<VideoItem> = []//当前歌单
  332. @Consume currentSongListName:string //当前歌单名称
  333. @Consume @Watch('onIDChange') currentSongListID:string //当前歌单ID
  334. @State isRefreshing: boolean = false;
  335. @State maxRefreshingHeight: number = 100.0;
  336. @State isPlayerLoading: boolean = false; // 播放器加载状态
  337. private contentNode?: ComponentContent<Object> = undefined;
  338. // WebDAV相关实例变量(现在改为从内存读取,不再需要存储)
  339. @State ratioL: number = 1;
  340. @State mediaKuCount: number = 0;
  341. @State albumCount: number = 0;
  342. @State artistCount: number = 0;
  343. @State fastForwardSeconds: string = '10'
  344. @State isShowBackFast: boolean = true//快进快退按钮
  345. @State isCanAuto:boolean = true
  346. @State opacityValueImage: number = 1;
  347. @State tipPopup:boolean = false
  348. @State preloadNextSong: boolean = PreferencesUtil.getBooleanSync('preload_next_song', true) // 是否提前缓存下一首
  349. @Consume mType: number;
  350. @StorageProp('themeColor') themeColor: string =
  351. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  352. themeMode: number = 0;
  353. @State titleName: string = '首页'
  354. @State textStr: string = ''
  355. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  356. // private download_path: string = '';
  357. @Consume rootPath: string //音频根目录
  358. @Consume currentPath: string
  359. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  360. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  361. @State lockPath: string = ''
  362. @State favPath: string = ''
  363. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  364. @State historyPath: string = ''
  365. @State historyList: Array<VideoItem> = []
  366. @Consume isHistory: boolean
  367. static readonly HISTORY_MUSIC: string = 'music_historyList';
  368. private table: MediaTable = new MediaTable(getContext(this))
  369. private playlistTable: PlaylistTable | null = null
  370. private deletionWatcher: FileDeletionWatcher | null = null
  371. @State allPlaylists: Playlist[] = []
  372. @State isZero: boolean = false
  373. @State fileList: Array<string> = []
  374. @State dirList: Array<VideoItem> = []
  375. @Consume videoLocalList:VideoItem[]
  376. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  377. @State listRefreshKey: number = 0
  378. @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  379. @State artistList: Array<VideoItem> = []; //艺术家文件
  380. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  381. @State artistSongCountMap: Map<string, number> = new Map();
  382. @State albumList: Array<VideoItem> = []; //专辑文件
  383. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  384. @State albumSongCountMap: Map<string, number> = new Map();
  385. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  386. @State imageOpacities: number[] = [];
  387. @Consume isCanBack: boolean
  388. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  389. @State showSingleLyric: boolean = false
  390. @State sortType: number = 4 //默认排序方式
  391. @State isShowSimi: boolean = false //是否显示私密音频
  392. @State isShowFAV: boolean = true //是否显示我的收藏
  393. @State isShowTitleBar: boolean = true //是否显示分类导航条
  394. @State isShowAllBar: boolean = true //是否显示播放全部条
  395. @State isShowSingleLineLyric: boolean = false //是否显示单行歌词
  396. @State isShowHistory: boolean = true //是否显示最近播放
  397. @State @Watch('onColorModeChange') isCustomizeBg: boolean = false //自定义背景界面
  398. @State isGridMusic: boolean = false //是否网格布局
  399. @State isCircleBtn: boolean = false //是否圆形播放按钮
  400. @State twoFingerType: number = 3 //双支放大缩小的类型
  401. @State isScrollHide: boolean = false //是否滚动隐藏
  402. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  403. @State isStartAutoPlay: boolean = false //启动后自动播放
  404. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  405. @State isShowHeader: boolean = true
  406. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  407. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  408. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  409. @State isSwipe: boolean = false //listItem的左滑开关
  410. @State openSkipSongAnimate: boolean = true//切歌动画效果
  411. @State customizeBgPath: string | undefined = '';
  412. @State isDarkMode: boolean = false
  413. @State lyricTextWeight: number = 400
  414. @State lyricTextWeightPip: number = 400
  415. @State currentSwiperIndex: number = 0
  416. @State blurValue: number = 0 //背景模糊
  417. @State bgBrightness: number = 0 //背景亮度
  418. private listScroller: ListScroller = new ListScroller()
  419. private playListScroller: Scroller = new Scroller()
  420. @State isOneKeyTags:boolean = false
  421. @State isFixMessy:boolean = false
  422. // 分页相关状态
  423. @State private currentPage: number = 0 // 当前页码
  424. @State private pageSize: number = 50 // 每页数量
  425. @State private totalCount: number = 0 // 总记录数
  426. @State private hasMoreData: boolean = true // 是否还有更多数据
  427. @State private isLoadingPage: boolean = false // 是否正在加载分页数据
  428. private pageCache: Map<number, VideoItem[]> = new Map() // 页面缓存(最多保留3页)
  429. private prefetchingPages: Set<number> = new Set()
  430. private playQueueScope: 'view' | 'history' | 'fav' | 'playlist' | 'single' = 'view'
  431. private isHydratingPlayList: boolean = false
  432. @StorageProp('isLandscape') @Watch('onIsLandscapeChange') isLandscape: boolean = false;
  433. @StorageProp('topSafeHeight') topSafeHeight: number = 0;
  434. @StorageProp('bottomSafeHeight') bottomSafeHeight: number = 0;
  435. @StorageProp('windowWidth') windowWidth: number = 0;
  436. @StorageProp('windowHeight') windowHeight: number = 0;
  437. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  438. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  439. private UNKONWN:string = '';
  440. private listArea: Area = {
  441. width: 0,
  442. height: 0,
  443. position: {},
  444. globalPosition: {}
  445. }
  446. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  447. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  448. // WebDAV认证信息缓存(作为实例变量,比全局上下文更可靠)
  449. private currentWebDavAuthInfo: WebDavAuthItem | null = null;
  450. //瀑布流的列数横竖屏动态切换
  451. onIsLandscapeChange() {
  452. if(this.isLandscape){
  453. this.columns = 4
  454. }else{
  455. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  456. }
  457. }
  458. onColorModeChange() {
  459. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  460. }
  461. //点击某个歌单id发生变化的时候回调
  462. onIDChange(){
  463. console.log('onecold 歌单id发生变化this.currentSongListID='+this.currentSongListID)
  464. console.log('onecold 歌单id发生变化this.currentSongListName='+this.currentSongListName)
  465. if(this.modeType==4){
  466. this.titleName = this.currentSongListName
  467. this.rightTopImage = $r('sys.symbol.sort')
  468. //获取缓存
  469. const cacheSongs:string =PreferencesUtil.getStringSync(this.currentSongListID+'currentSongList', '')
  470. console.log('onecold 歌单id发生变化获取缓存2 cacheSongs = '+cacheSongs)
  471. if(StrUtil.isNotEmpty(cacheSongs)){
  472. this.currentSongList = JSON.parse(cacheSongs) as VideoItem[]
  473. this.updateListData(this.currentSongList, true)
  474. }
  475. this.doSongListTask()//获取歌单信息
  476. }
  477. }
  478. async doSongListTask() {
  479. // 初始化歌单数据库
  480. const playlistTable = new PlaylistTable(this.context);
  481. // 查询歌单中的所有歌曲
  482. const playlistSongs: PlaylistSong[] = await playlistTable.queryPlaylistSongs(this.currentSongListID);
  483. console.log('onecold 歌单id发生变化获取缓存7 playlistSongs='+playlistSongs.length)
  484. if (ArrayUtil.isEmpty(playlistSongs)) {
  485. this.updateListData([], true)
  486. } else {
  487. this.currentSongList = await convertPlaylistSongsToVideoItems(this.context, playlistSongs);
  488. console.log('onecold 从数据库读取的歌曲为 playlistSongs='+this.currentSongList.length)
  489. this.updateListData(this.currentSongList, true)
  490. if (ArrayUtil.isNotEmpty(this.currentSongList)&&this.currentSongList.length > 100) {
  491. // 只保存前100条记录到缓存中
  492. let canceList = this.currentSongList.slice(0, 100);
  493. PreferencesUtil.putSync(this.currentSongListID+'currentSongList',
  494. JSON.stringify(canceList))
  495. } else {
  496. PreferencesUtil.putSync(this.currentSongListID+'currentSongList', JSON.stringify(this.currentSongList));
  497. }
  498. }
  499. this.isRefreshing = false
  500. }
  501. async onModeChange(): Promise<void> {
  502. this.isFavMusic = false
  503. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  504. Logger.info('heanup LocalMusic', `onModeChange: 切换模式 modeType=${this.modeType}`);
  505. switch (this.modeType) {
  506. case 0:
  507. // 首页模式已在 resetAndLoadFirstPage 中处理
  508. // 切换模式时加载对应的排序类型
  509. this.titleName = Utility.resourceToString(this.context,$r('app.string.home'))
  510. this.sortType = this.loadSortTypeForCurrentMode()
  511. break
  512. case 1:
  513. this.rightTopImage = $r('sys.symbol.sort')
  514. this.titleName = Utility.resourceToString(this.context,$r('app.string.media_ku'))
  515. // 切换模式时加载对应的排序类型
  516. this.sortType = this.loadSortTypeForCurrentMode()
  517. break
  518. case 2:
  519. this.rightTopImage = $r('sys.symbol.sort')
  520. this.titleName = Utility.resourceToString(this.context,$r('app.string.artist'))
  521. // 切换到艺术家模式时,加载艺术家模式的排序类型(默认按数量降序)
  522. this.sortType = this.loadSortTypeForCurrentMode()
  523. break
  524. case 3:
  525. this.rightTopImage = $r('sys.symbol.sort')
  526. this.titleName = Utility.resourceToString(this.context,$r('app.string.album'))
  527. // 切换到专辑模式时,加载专辑模式的排序类型(默认按数量降序)
  528. this.sortType = this.loadSortTypeForCurrentMode()
  529. break
  530. }
  531. // 模式切换时重置分页状态并加载第一页
  532. await this.resetAndLoadFirstPage();
  533. Logger.info('heanup onModeChange', `doSortType: 切换排序方式 sortType=${this.sortType}, mode=${this.modeType}`);
  534. }
  535. // @Consume currentSong: VideoItem | undefined;
  536. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  537. // @StorageLink('isPlay') isPlay: boolean = false;
  538. @Consume isShowPlay: boolean ;
  539. @StorageLink('songList') songList: Array<VideoItem> = [];
  540. @State translateY: number = 0;
  541. @State isShowSheet: boolean = false;
  542. @State isShowSheetView: boolean = false;
  543. @State isShowTimeCloseView: boolean = false;
  544. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  545. @StorageLink('currIndex') curIndex: number = 0;
  546. @Consume isShowDrawer: boolean;
  547. @Consume offsetX: number;
  548. @State isFac: boolean = false;
  549. @State favList: Array<VideoItem> = []
  550. @Consume isFavMusic: boolean
  551. @State isClickedPLayAll: boolean = false;
  552. private scrollerForlist: ListScroller = new ListScroller();
  553. private knockController: KnockController | undefined = undefined;
  554. // 修改为:
  555. imagesF: ImageFrameInfo[] = CommonConstants.IMAGE_FRAME_INFO;
  556. @StorageProp('animationState') animationState: AnimationStatus = AnimationStatus.Initial
  557. // 缓存机制
  558. private cache: Map<string, Array<VideoItem>> = new Map();
  559. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  560. // 持久化缓存
  561. private async saveCacheToStorage() {
  562. const cacheArray = Array.from(this.cache.entries());
  563. const stringCacheArray = Array.from(this.stringCache.entries());
  564. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  565. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  566. }
  567. // 载入缓存
  568. private async loadCacheFromStorage() {
  569. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  570. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  571. if (cacheString) {
  572. const parsedCache: Object | null = JSON.parse(cacheString);
  573. if (parsedCache && Array.isArray(parsedCache)) {
  574. const cacheArray: [string, Array<VideoItem>][] = parsedCache;
  575. this.cache = new Map(cacheArray);
  576. }
  577. }
  578. if (stringCacheString) {
  579. const parsedStringCache: Object | null = JSON.parse(stringCacheString);
  580. if (parsedStringCache && Array.isArray(parsedStringCache)) {
  581. const stringCacheArray: [string, string][] = parsedStringCache;
  582. this.stringCache = new Map(stringCacheArray);
  583. }
  584. }
  585. }
  586. // 查找缓存
  587. private findCache(key: string): Array<VideoItem> | undefined {
  588. return this.cache.get(key);
  589. }
  590. // 查找字符串缓存
  591. private findStringCache(key: string): string | undefined {
  592. return this.stringCache.get(key);
  593. }
  594. // 添加缓存
  595. private addCache(key: string, value: Array<VideoItem>) {
  596. this.cache.set(key, value);
  597. }
  598. // 添加字符串缓存
  599. private addStringCache(key: string, value: string) {
  600. this.stringCache.set(key, value);
  601. }
  602. // 删除缓存
  603. private deleteCache(key: string) {
  604. this.cache.delete(key);
  605. this.saveCacheToStorage()
  606. }
  607. // 删除字符串缓存
  608. private deleteStringCache(key: string) {
  609. this.stringCache.delete(key);
  610. }
  611. // 多选机制
  612. @State selectedFiles: Array<VideoItem> = [];
  613. @Consume isMultiSelect: boolean;
  614. @State isAllSelected: boolean = false;
  615. @State appName: string = ''
  616. @State isHasDir: boolean = false
  617. @State packName: string = ''
  618. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  619. doSwipBack() {
  620. if(this.isSearchMode){
  621. console.info('onecold doSwipBack = ' +this.isSearchMode)
  622. this.isSearchMode = false
  623. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  624. this.searchText = ''
  625. this.getSortedFiles(this.currentPath)
  626. return
  627. }
  628. this.onSearchInput('')
  629. return
  630. }
  631. this.isZero = false
  632. if (this.modeType !== 0 && this.isCanBack) {
  633. this.onModeChange()
  634. this.isCanBack = false
  635. // 返回专辑列表时恢复滚动偏移量,支持列表和网格
  636. setTimeout(() => {
  637. if (this.modeType == 2) {
  638. if (this.isGridMusic||this.twoFingerType==4) {
  639. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  640. let lastWaterOffset = this.mScrollMap.get('lastWaterArtistScrollOffset') ?? 0
  641. if(this.twoFingerType==4){
  642. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  643. }else{
  644. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  645. }
  646. } else {
  647. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  648. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  649. }
  650. } else if (this.modeType == 3) {
  651. if (this.isGridMusic||this.twoFingerType==4) {
  652. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  653. let lastWaterOffset = this.mScrollMap.get('lastWaterAlBumScrollOffset') ?? 0
  654. if(this.twoFingerType==4){
  655. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  656. }else{
  657. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  658. }
  659. } else {
  660. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  661. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  662. }
  663. }
  664. }, 200)
  665. return
  666. }
  667. if (this.isHistory || this.isFavMusic) {
  668. this.isHistory = false
  669. this.getSortedFiles(this.currentPath)
  670. return
  671. }
  672. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  673. animateTo({ duration: 555 }, () => {
  674. // 动画闭包内控制Image组件的出现和消失
  675. this.isShowDrawer = !this.isShowDrawer
  676. this.offsetX = 0
  677. })
  678. return
  679. }
  680. //返回上一级歌单的滚动位置
  681. setTimeout(() => {
  682. if (this.modeType == 0) {
  683. if (this.isGridMusic||this.twoFingerType==4) {
  684. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  685. let lastWaterOffset = this.mScrollMap.get('lastWaterDirScrollOffset') ?? 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('lastListDirScrollOffset') ?? 0
  693. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  694. }
  695. }
  696. }, 100)
  697. this.currentPath = Utility.getParentDirectory(this.currentPath)
  698. Logger.info('this.currentPath2 = ' + this.currentPath)
  699. this.getSortedFiles(this.currentPath)
  700. }
  701. // 组件生命周期
  702. aboutToAppear() {
  703. console.info('onecold aboutToAppear sdkApiVersion = '+deviceInfo.sdkApiVersion)
  704. if(ArrayUtil.isNotEmpty(this.videoLocalList)&&this.modeType==0){
  705. this.updateListData(this.videoLocalList)
  706. }
  707. // 初始化 PlaylistTable
  708. this.playlistTable = new PlaylistTable(getContext(this))
  709. this.sonTwoFingerType = PreferencesUtil.getNumberSync('sonTwoFingerType', 3);
  710. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  711. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  712. this.tipPopup = !this.tipPopup
  713. PreferencesUtil.putSync('isFirstTiped',false)
  714. }
  715. this.initSetting()
  716. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  717. Utility.getAppName(getContext(this)).then((appName: string) => {
  718. this.appName = appName
  719. })
  720. this.packName = AppUtil.getBundleName()
  721. this.tabSelectedIndexes[0] = this.modeType//SegmentButton的索引
  722. this.loadCacheFromStorage(); // 加载文件夹缓存
  723. // 在首页初始化时读取媒体库,艺术家,专辑等缓存数据
  724. this.initLoadCache()
  725. this.mkDownLoadDir()
  726. let eventMusic: emitter.InnerEvent = { eventId: EventConstants.EVENT_AUDIO_OPEN }
  727. // 监听广播事件(打开其他应用处理)
  728. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  729. this.saveVideoDatas([eventData.data?.message], true)
  730. });
  731. //侧滑广播接收时间
  732. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_UPDATE }
  733. // 监听广播事件(手势返回处理)
  734. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  735. animateTo({ duration: 555 }, () => {
  736. this.doSwipBack()
  737. })
  738. });
  739. //ScanFilePage广播接收时间
  740. let eventScanUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_SCAN_UPDATE }
  741. // 监听ScanFilePage广播事件(更新数据库)
  742. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  743. this.doUpdateData()
  744. });
  745. // 监听歌单播放请求事件
  746. let eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY }
  747. emitter.on(eventPlaylistPlay, async (eventData: emitter.EventData) => {
  748. const data = eventData.data as Record<string, Object>
  749. if (!data) {
  750. Logger.error('heanup eventPlaylistPlay: eventData.data is undefined or null')
  751. return
  752. }
  753. // 检查歌单播放数据结构
  754. if (data.playlistId && data.songFilePaths && data.startIndex !== undefined) {
  755. const playlistData: PlaylistEventData = {
  756. playlistId: data.playlistId as string,
  757. playlistName: data.playlistName as string,
  758. songCount: data.songCount as number,
  759. startIndex: data.startIndex as number,
  760. isJump: data.isJump as boolean,
  761. songFilePaths: data.songFilePaths as string[]
  762. }
  763. await this.handlePlaylistPlayRequest(
  764. playlistData.playlistId,
  765. playlistData.playlistName,
  766. playlistData.songFilePaths,
  767. playlistData.startIndex,
  768. playlistData.isJump,
  769. )
  770. return
  771. }
  772. Logger.error('heanup eventPlaylistPlay: 接收到无效的数据结构')
  773. });
  774. let eventRefreshSort: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_REFRESH_SORT }
  775. // 监听广播事件(通用设置配置更新)
  776. emitter.on(eventRefreshSort, (eventData: emitter.EventData) => {
  777. if(this.modeType ==4){
  778. this.doSongListTask()//获取歌单信息
  779. }
  780. });
  781. let eventSetting: emitter.InnerEvent = { eventId: EventConstants.EVENT_SETTING_UPDATE }
  782. // 监听广播事件(通用设置配置更新)
  783. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  784. this.initSetting()
  785. });
  786. // 监听 WebDAV 元数据更新事件
  787. let eventWebDavMetadata: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED }
  788. emitter.on(eventWebDavMetadata, (eventData: emitter.EventData) => {
  789. const payloads = eventData?.data as WebDavMetadataUpdatePayload[] | undefined;
  790. if (!payloads || payloads.length === 0) {
  791. Logger.info(TAG, 'LocalMusic: WebDav metadata event received but payload empty');
  792. return;
  793. }
  794. Logger.info(TAG, `LocalMusic: WebDav metadata event payload count: ${payloads.length}`);
  795. // 处理每个元数据更新
  796. for (let i = 0; i < payloads.length; i++) {
  797. const payload = payloads[i];
  798. if (!payload || !payload.filePath) {
  799. continue;
  800. }
  801. // 重要:只更新当前正在播放的歌曲
  802. // 如果 filePath 不匹配,说明是其他歌曲的元数据更新,忽略不做处理
  803. if (this.currentSong && this.currentSong.filePath === payload.filePath) {
  804. Logger.info(TAG, `LocalMusic: 更新当前播放歌曲的元数据: ${payload.filePath}`);
  805. if (payload.name && payload.name.length > 0) {
  806. this.name = payload.name;
  807. if (this.currentSong) {
  808. this.currentSong.name = payload.name;
  809. }
  810. }
  811. if (payload.artist && payload.artist.length > 0) {
  812. this.artist = payload.artist;
  813. if (this.currentSong) {
  814. this.currentSong.artist = payload.artist;
  815. }
  816. }
  817. if (payload.pixelMapPath && payload.pixelMapPath.length > 0) {
  818. this.cover = payload.pixelMapPath;
  819. if (this.currentSong) {
  820. this.currentSong.pixelMapPath = payload.pixelMapPath;
  821. }
  822. Logger.info(TAG, `LocalMusic: 封面已更新: ${payload.pixelMapPath}`);
  823. }
  824. // 同步更新 AppStorage
  825. AppStorage.setOrCreate('currentSong', this.currentSong);
  826. } else {
  827. Logger.info(TAG, `LocalMusic: 跳过非当前播放歌曲的元数据更新: ${payload.filePath}, 当前: ${this.currentSong?.filePath}`);
  828. }
  829. }
  830. });
  831. // 监听广播事件(通用设置配置更新)
  832. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  833. this.doChangeSetting()
  834. });
  835. let event: Callback<InterruptEvent> = (event) => {
  836. // LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  837. console.info(`heanup onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`)
  838. this.savePlaybackPosition()
  839. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  840. this.pause();
  841. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  842. console.info(`heanup onecold audioInterrupt startPlayOrResumePlay: ${JSON.stringify(event)}`)
  843. this.startPlayOrResumePlay();
  844. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  845. console.info(`heanup onecold 与其他应用音频冲突 被截断点 INTERRUPT_HINT_STOP`)
  846. if(!this.isSameTimePlay){
  847. this.stop();
  848. }
  849. }
  850. }
  851. this.mIjkMediaPlayer.on('audioInterrupt', event);
  852. // 音频设备断连回调处理比如蓝牙耳机断开
  853. let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  854. LogUtils.getInstance().LOGI(`Heanup deviceChange event: ${JSON.stringify(event)}`);
  855. if (event.reason === DeviceChangeReason.REASON_NEW_DEVICE_AVAILABLE) { // 音频设备连接
  856. } else if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  857. console.info('heanup onecold 音频设备断开连接, 暂停播放')
  858. this.pause();
  859. }
  860. }
  861. // 订阅音频设备断开和连接事件
  862. this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  863. const eventPause: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAY_PAUSE }
  864. // 监听广播事件(hicar断开暂停播放)
  865. emitter.on(eventPause, (eventData: emitter.EventData) => {
  866. console.info('heanup onecold hicar断开暂停播放, 暂停播放')
  867. this.pause();
  868. });
  869. // 有线耳机断开和连接的监听。监听音频设备状态变化。
  870. let audioManager = audio.getAudioManager(); // 需要先创建AudioManager实例。
  871. let audioRoutingManager = audioManager.getRoutingManager(); // 再调用AudioManager的方法创建AudioRoutingManager实例。
  872. audioRoutingManager.on('deviceChange', audio.DeviceFlag.INPUT_DEVICES_FLAG, (deviceChanged: audio.DeviceChangeAction) => {
  873. console.info('device change type : ' + deviceChanged.type); // 设备连接状态变化,0为连接,1为断开连接。
  874. // 设备类型 22是USB耳机,带麦克风,3是有线耳机。
  875. if(deviceChanged.type==1&&
  876. (deviceChanged.deviceDescriptors[0].deviceType== 22||
  877. deviceChanged.deviceDescriptors[0].deviceType==3)){
  878. console.info('heanup onecold 有线耳机断开, 暂停播放')
  879. this.pause();
  880. }
  881. });
  882. this.makeWorker()
  883. //折叠屏的屏幕显示模式变化
  884. display.on('foldDisplayModeChange', (data) => {
  885. this.doChangeBarHeight()
  886. });
  887. display.on('foldStatusChange', (data) => {
  888. Logger.info('onecold foldStatusChange ')
  889. });
  890. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  891. // 读取 themeMode 并同步 currentColorMode
  892. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  893. this.applyThemeMode(this.themeMode)
  894. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  895. AppStorage.setOrCreate('themeColor', themeColor);
  896. this.themeColor = themeColor;
  897. this.doChangeSetting()
  898. this.windowClass.on('windowSizeChange', (size: window.Size) => {
  899. LogUtil.info('onecold windowSizeChange')
  900. this.doChangeBarHeight()
  901. let viewWidth = px2vp(size.width);
  902. let viewHeight = px2vp(size.height);
  903. if(this.isPhoneLan()){
  904. this.is_auto_hide_progress = false
  905. if(this.isHiCar()){
  906. return
  907. }
  908. setTimeout(() => {
  909. this.is_auto_hide_progress = true
  910. }, 6000)
  911. }else{
  912. this.startAutoHide()
  913. }
  914. });
  915. this.eventHub.on('onStateChange', (fg: boolean) => {
  916. if (fg && this.curState === 'STARTED') {
  917. this.stopPip();
  918. }
  919. });
  920. //NewIndex的博空调收到eventHub消息控制播放
  921. this.getUIContext().getHostContext()!.eventHub.on('playOrPause', () => {
  922. if (ArrayUtil.isNotEmpty(this.songList)) {
  923. this.playOrPause();
  924. } else {
  925. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  926. }
  927. });
  928. this.getUIContext().getHostContext()!.eventHub.on('playPrevious', () => {
  929. if (ArrayUtil.isNotEmpty(this.songList)) {
  930. this.playPrevious();
  931. } else {
  932. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  933. }
  934. });
  935. this.getUIContext().getHostContext()!.eventHub.on('playNext', () => {
  936. if (ArrayUtil.isNotEmpty(this.songList)) {
  937. this.playNext();
  938. } else {
  939. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  940. }
  941. });
  942. this.getUIContext().getHostContext()!.eventHub.on('showPlayerView', () => {
  943. this.showPlayerView();
  944. });
  945. this.getUIContext().getHostContext()!.eventHub.on('openPlayList', () => {
  946. this.openPlayList();
  947. });
  948. }
  949. //载入媒体库,艺术家,专辑等缓存
  950. initLoadCache(){
  951. this.mediaKuCount = PreferencesUtil.getNumberSync('mediaKuCount', 0)
  952. this.artistCount = PreferencesUtil.getNumberSync('artistCount', 0)
  953. this.albumCount = PreferencesUtil.getNumberSync('albumCount', 0)
  954. let cachedListStr:string = PreferencesUtil.getStringSync('mediaKuList', '[]');
  955. let cachedList = JSON.parse(cachedListStr) as Array<VideoItem>;
  956. if(ArrayUtil.isNotEmpty(cachedList)){
  957. this.mediaKuList = cachedList
  958. if(this.modeType==1){
  959. this.updateListData(this.mediaKuList)
  960. }
  961. }
  962. let artistListStr:string = PreferencesUtil.getStringSync('artistList', '[]');
  963. let artistCachedList = JSON.parse(artistListStr) as Array<VideoItem>;
  964. if(ArrayUtil.isNotEmpty(artistCachedList)){
  965. this.artistList = artistCachedList
  966. let artistMapStr:string = PreferencesUtil.getStringSync('artistMap', '[]');
  967. const parsedArray = JSON.parse(artistMapStr) as [string, VideoItem[]][];
  968. this.artistMap = new Map(parsedArray);
  969. // this.artistMap = JSON.parse(artistMapStr) as Map<string, VideoItem[]>;
  970. if(this.modeType==2){
  971. this.updateListData(this.artistList)
  972. }
  973. }
  974. let albumListStr:string = PreferencesUtil.getStringSync('albumList', '[]');
  975. let albumCachedList = JSON.parse(albumListStr) as Array<VideoItem>;
  976. if(ArrayUtil.isNotEmpty(albumCachedList)){
  977. this.albumList = albumCachedList
  978. let albumMapStr:string = PreferencesUtil.getStringSync('albumMap', '[]');
  979. const parsedArray = JSON.parse(albumMapStr) as [string, VideoItem[]][];
  980. this.albumMap = new Map(parsedArray);
  981. if(this.modeType==3){
  982. this.updateListData(this.albumList)
  983. }
  984. }
  985. }
  986. startAutoHide() {
  987. if(this.isHiCar()){
  988. return
  989. }
  990. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  991. console.info('onecold startAutoHide')
  992. this.is_auto_hide_progress = false
  993. setTimeout(() => {
  994. this.is_auto_hide_progress = true
  995. }, 6000)
  996. }
  997. }
  998. applyThemeMode(mode: number) {
  999. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  1000. if (mode === 1) {
  1001. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  1002. } else if (mode === 2) {
  1003. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1004. }
  1005. AppStorage.setOrCreate('currentColorMode', colorMode)
  1006. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  1007. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  1008. AppStorage.setOrCreate('themeMode', mode)
  1009. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1010. // 只有强制浅色/深色时才主动设置
  1011. const context = getContext(this) as common.UIAbilityContext
  1012. context.getApplicationContext().setColorMode(colorMode)
  1013. }
  1014. initSetting() {
  1015. this.enablePointLight = PreferencesUtil.getBooleanSync('enablePointLight', true)
  1016. AppStorage.setOrCreate('EnablePointLight', this.enablePointLight);
  1017. this.showSimple = PreferencesUtil.getBooleanSync('showSimple', true)
  1018. this.showFindLocation = PreferencesUtil.getBooleanSync('showFindLocation', true)
  1019. this.showZMIndex = PreferencesUtil.getBooleanSync('showZMIndex', false)
  1020. this.autoHideTitle = PreferencesUtil.getBooleanSync('autoHideTitle', true)
  1021. this.isShowPrecious = PreferencesUtil.getBooleanSync('isShowPrecious', false)
  1022. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1023. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  1024. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  1025. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, false)
  1026. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  1027. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  1028. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  1029. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  1030. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  1031. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  1032. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  1033. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  1034. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  1035. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 2)
  1036. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  1037. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  1038. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  1039. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  1040. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  1041. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  1042. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  1043. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  1044. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  1045. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  1046. this.volumeSmall = PreferencesUtil.getBooleanSync('volumeSmall', false)
  1047. this.autoParseMusicName = PreferencesUtil.getBooleanSync('autoParseMusicName', true)
  1048. this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
  1049. this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
  1050. this.fastForwardSeconds = PreferencesUtil.getStringSync('fastForwardSeconds', '10')
  1051. this.isShowBackFast = PreferencesUtil.getBooleanSync('isShowBackFast', false)
  1052. this.isCopyFileToDownLoad = PreferencesUtil.getBooleanSync(SettingPage.IS_COPYFILE_TO_DOWNLOAD, false)
  1053. let audioManager = audio.getAudioManager();
  1054. let audioSessionManager: audio.AudioSessionManager = audioManager.getSessionManager();
  1055. if(this.isSameTimePlay){
  1056. //与其他应用同时播放,关键代码
  1057. let strategy: audio.AudioSessionStrategy = {
  1058. concurrencyMode: audio.AudioConcurrencyMode.CONCURRENCY_MIX_WITH_OTHERS
  1059. };
  1060. audioSessionManager.activateAudioSession(strategy).then(() => {
  1061. console.info('onecold Succeeded in doing activateAudioSession.');
  1062. }).catch((err: BusinessError) => {
  1063. console.error(`Failed to activateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1064. });
  1065. }else{
  1066. let isActivated = audioSessionManager.isAudioSessionActivated();
  1067. if(isActivated){
  1068. audioSessionManager.deactivateAudioSession().then(() => {
  1069. console.info('Succeeded in doing deactivateAudioSession.');
  1070. }).catch((err: BusinessError) => {
  1071. console.error(`Failed to deactivateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1072. });
  1073. }
  1074. }
  1075. if(this.volumeSmall){
  1076. this.volume = 0.5
  1077. }else{
  1078. this.volume = 1
  1079. }
  1080. //如果是hicar连接状态,这些都是false
  1081. if(this.isHiCar()){
  1082. this.autoHideTitle = false
  1083. this.isCoverRectangle= true
  1084. this.columns=4
  1085. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  1086. {
  1087. this.isGridMusic= false//用list不用网格
  1088. this.isCoverTopBig = false
  1089. }
  1090. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  1091. }
  1092. if (this.isSavePlayMode) {
  1093. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  1094. }
  1095. }
  1096. doChangeSetting() {
  1097. this.initSetting()
  1098. this.deleteCache(this.currentPath)
  1099. if (this.modeType === 0) {
  1100. this.getSortedFiles(this.currentPath)
  1101. }
  1102. }
  1103. doChangeBarHeight() {
  1104. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  1105. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  1106. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  1107. this.setBarHeightNormal()
  1108. }
  1109. }
  1110. onPageShow() {
  1111. this.knockController?.immersiveListening();
  1112. app.setImageCacheCount(100);
  1113. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  1114. app.setImageRawDataCacheSize(104857600);
  1115. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  1116. }
  1117. //开启线程查看各个数据库
  1118. makeWorker() {
  1119. setTimeout(() => {
  1120. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  1121. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  1122. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  1123. // workerInstance.postMessage({
  1124. // code: 1,
  1125. // data1: this.context,
  1126. // data2: this.rootPath,
  1127. // data3: this.lockPath,
  1128. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  1129. // data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  1130. // });
  1131. PreferencesUtil.putSync('isFirstApp', false)
  1132. } else {
  1133. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1134. workerInstance.postMessage({ code: 3, data: this.context });
  1135. workerInstance.postMessage({ code: 4, data: this.context });
  1136. this.getHistoryList(false)
  1137. }
  1138. }, 1000)
  1139. workerInstance.onmessage = (e: MessageEvents): void => {
  1140. const message = e.data as LocalMusicWorkerMessage;
  1141. switch (message.code) {
  1142. case 101: //第一次扫描文件夹入库
  1143. ToastUtil.showToast('刷新同步数据库成功!')
  1144. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  1145. this.doAllUpdateData()
  1146. break;
  1147. case 102: //查询媒体库列表
  1148. this.isRefreshing = false
  1149. this.mediaKuList = message.data // 只包含前100条
  1150. const mediaTotalCount: number = message.totalCount ?? this.mediaKuList.length;
  1151. this.mediaKuCount = mediaTotalCount;
  1152. Logger.info(`heanup 查询媒体库列表 缓存数=${this.mediaKuList.length}, 总数=${mediaTotalCount}`)
  1153. Utility.doSortListAscending(this.mediaKuList)
  1154. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  1155. // 媒体库模式下重新加载第一页(分页查询)
  1156. if (this.modeType === 1) {
  1157. this.resetAndLoadFirstPage();
  1158. }
  1159. PreferencesUtil.putSync('mediaKuCount', mediaTotalCount)
  1160. // 只保存前100条记录到缓存中
  1161. PreferencesUtil.putSync('mediaKuList', JSON.stringify(this.mediaKuList));
  1162. break;
  1163. case 103: //收到查询艺术家列表
  1164. this.isRefreshing = false
  1165. this.artistMap = message.data1; // 只包含前60个艺术家的歌曲
  1166. this.artistList = message.data2; // 只包含前100个艺术家
  1167. const artistTotalCount: number = message.totalCount ?? this.artistList.length;
  1168. this.artistCount = artistTotalCount;
  1169. const nextArtistCountMap = new Map(this.artistSongCountMap);
  1170. this.artistMap.forEach((songs, artist) => {
  1171. nextArtistCountMap.set(artist, songs.length);
  1172. });
  1173. this.artistSongCountMap = nextArtistCountMap;
  1174. Logger.info(`heanup 查询艺术家列表 缓存数=${this.artistList.length}, 总数=${artistTotalCount}`)
  1175. PreferencesUtil.putSync('artistCount', artistTotalCount)
  1176. // 艺术家模式下重新加载第一页(分页查询)
  1177. if (this.modeType === 2) {
  1178. this.resetAndLoadFirstPage();
  1179. }
  1180. // 保存前100条艺术家列表
  1181. PreferencesUtil.putSync('artistList', JSON.stringify(this.artistList));
  1182. // 保存前60条艺术家的歌曲Map
  1183. const sortedEntries = Array.from(this.artistMap.entries());
  1184. PreferencesUtil.putSync('artistMap', JSON.stringify(sortedEntries));
  1185. break;
  1186. case 104: //收到查询专辑列表
  1187. this.isRefreshing = false
  1188. this.albumMap = message.data1;
  1189. this.albumList = message.data2
  1190. const albumTotalCount: number = message.totalCount ?? this.albumList.length;
  1191. this.albumCount = albumTotalCount;
  1192. const nextAlbumCountMap = new Map(this.albumSongCountMap);
  1193. this.albumMap.forEach((songs, album) => {
  1194. nextAlbumCountMap.set(album, songs.length);
  1195. });
  1196. this.albumSongCountMap = nextAlbumCountMap;
  1197. Logger.info(`heanup 查询专辑列表 缓存数=${this.albumList.length}, 总数=${albumTotalCount}`)
  1198. // 专辑模式下重新加载第一页(分页查询)
  1199. if (this.modeType === 3) {
  1200. this.resetAndLoadFirstPage();
  1201. }
  1202. //查询完毕在启动是否自动播放
  1203. if (this.isStartAutoPlay&&this.isCanAuto) {
  1204. this.isCanAuto = false
  1205. console.info('onecold startPlayOrResumePlay 757')
  1206. this.startPlayOrResumePlay()
  1207. }
  1208. PreferencesUtil.putSync('albumCount', albumTotalCount)
  1209. // 保存前100条专辑列表(Worker已经只发送了100条)
  1210. PreferencesUtil.putSync('albumList', JSON.stringify(this.albumList));
  1211. // 保存前60条专辑Map(Worker已经只发送了60条)
  1212. const mapArrayAlbum = Array.from(this.albumMap.entries());
  1213. PreferencesUtil.putSync('albumMap', JSON.stringify(mapArrayAlbum));
  1214. break;
  1215. case 105: // 缓存完成后返回的元数据
  1216. this.handleWorkerMetadataPayload(message.data);
  1217. break;
  1218. case 106: // 编辑音乐元数据和封面完成
  1219. this.handleEditMusicResult(message.data);
  1220. break;
  1221. }
  1222. };
  1223. // 在调用terminate后,执行onexit
  1224. workerInstance.onexit = (code) => {
  1225. metadataExtractionInFlight.clear();
  1226. Logger.info(TAG, 'workerInstance 线程已退出,code: ' + code);
  1227. }
  1228. workerInstance.onerror = (err: ErrorEvent) => {
  1229. metadataExtractionInFlight.clear();
  1230. console.error('workerInstance 线程执行发生异常: ' + err.message)
  1231. }
  1232. }
  1233. private handleWorkerMetadataPayload(payload: WorkerMetadataPayload | undefined): void {
  1234. if (!payload || !payload.originFilePath) {
  1235. return;
  1236. }
  1237. metadataExtractionInFlight.delete(payload.originFilePath);
  1238. if (payload.error) {
  1239. Logger.warn(TAG, `缓存文件元数据解析失败: ${payload.error}`);
  1240. return;
  1241. }
  1242. this.applyMetadataToCollections(payload.originFilePath, payload);
  1243. }
  1244. private applyMetadataToCollections(filePath: string, payload: WorkerMetadataPayload): void {
  1245. const targets: Array<VideoItem> = [];
  1246. let mainListUpdated = false;
  1247. let playlistUpdated = false;
  1248. if (this.currentSong && this.currentSong.filePath === filePath) {
  1249. targets.push(this.currentSong);
  1250. }
  1251. const collectFromList = (list?: Array<VideoItem>, markUpdated?: () => void) => {
  1252. if (!list || list.length === 0) {
  1253. return;
  1254. }
  1255. const found = Utility.getItemByFilePath(list, filePath);
  1256. if (found) {
  1257. markUpdated?.();
  1258. targets.push(found);
  1259. }
  1260. };
  1261. collectFromList(this.videoLocalList, () => {
  1262. mainListUpdated = true;
  1263. });
  1264. collectFromList(this.songList, () => {
  1265. playlistUpdated = true;
  1266. });
  1267. collectFromList(this.historyList);
  1268. collectFromList(this.favList);
  1269. const remoteManager = RemoteDriveManager.getInstance();
  1270. collectFromList(remoteManager.webDavSongs);
  1271. const updated = new Set<VideoItem>();
  1272. const remoteMetadataUpdates: Map<string, WebDavMetadataUpdatePayload> = new Map();
  1273. for (let i = 0; i < targets.length; i++) {
  1274. const target = targets[i];
  1275. if (!target || updated.has(target)) {
  1276. continue;
  1277. }
  1278. updated.add(target);
  1279. this.mergeVideoItemWithPayload(target, payload);
  1280. if (isRemoteCloudType(target.type) && StrUtil.isNotEmpty(target.filePath)) {
  1281. remoteMetadataUpdates.set(target.filePath, {
  1282. filePath: target.filePath,
  1283. pixelMapPath: target.pixelMapPath,
  1284. name: target.name,
  1285. artist: target.artist
  1286. });
  1287. }
  1288. }
  1289. if (this.currentSong && this.currentSong.filePath === filePath) {
  1290. this.mergeVideoItemWithPayload(this.currentSong, payload);
  1291. if (payload.name) {
  1292. this.name = payload.name;
  1293. }
  1294. if (payload.artist) {
  1295. this.artist = payload.artist;
  1296. }
  1297. if (payload.pixelMapPath) {
  1298. this.cover = payload.pixelMapPath;
  1299. }
  1300. if (payload.lyricContent) {
  1301. this.applyInlineLyricContent(payload.lyricContent);
  1302. }
  1303. let avSessionDurationMs: number = this.duration;
  1304. if (payload.duration) {
  1305. const durationSeconds = Number(payload.duration);
  1306. if (!Number.isNaN(durationSeconds) && durationSeconds > 0) {
  1307. avSessionDurationMs = durationSeconds * 1000;
  1308. this.duration = avSessionDurationMs;
  1309. this.durationTime = Math.floor(avSessionDurationMs / 1000);
  1310. this.durationStringTime = secondToTime(this.durationTime);
  1311. }
  1312. }
  1313. if (avSessionDurationMs > 0) {
  1314. this.avSessionController.setAVMetadataMusic(this.currentSong, avSessionDurationMs, this.lyricContent);
  1315. }
  1316. this.currentSong = cloneVideoItem(this.currentSong);
  1317. AppStorage.setOrCreate('currentSong', this.currentSong);
  1318. }
  1319. const primaryTarget = targets.length > 0 ? targets[0] : undefined;
  1320. if (primaryTarget) {
  1321. this.persistRemoteMetadataToDb(primaryTarget).catch((error: Error) => {
  1322. Logger.error(TAG, `缓存元数据持久化失败: ${error.message}`);
  1323. });
  1324. }
  1325. if (remoteMetadataUpdates.size > 0) {
  1326. const eventUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
  1327. emitter.emit(eventUpdate, { data: Array.from(remoteMetadataUpdates.values()) });
  1328. }
  1329. this.refreshLazyListViews(mainListUpdated, playlistUpdated);
  1330. }
  1331. private handleEditMusicResult(result: WorkerEditMusicResult): void {
  1332. // 关闭进度条
  1333. DialogHelper.closeDialog(this.loadingDialogId)
  1334. if (result.success) {
  1335. console.log("heanup 编辑信息成功,数据库已同步");
  1336. if (result.coverResult) {
  1337. ToastUtil.showToast('内嵌封面成功');
  1338. }
  1339. ToastUtil.showToast('内嵌音乐标签成功');
  1340. this.isShowMoreView = false;
  1341. this.name = this.titleStr;
  1342. // 同步当前播放的歌曲信息
  1343. if (this.editingItem && this.currentSong && this.editingItem.filePath == this.currentSong.filePath) {
  1344. this.currentSong.name = this.titleStr;
  1345. this.artist = this.artistStr;
  1346. this.currentSong.artist = this.artistStr;
  1347. this.currentSong.album = this.ablumStr;
  1348. this.currentSong.year = this.yearStr;
  1349. this.currentSong.genre = this.genreStr;
  1350. this.currentSong.track = this.trackStr;
  1351. this.currentSong.lyricContent = this.lyricConStr;
  1352. this.currentSong.ALBUMARTIST = this.albumArtistStr;
  1353. this.currentSong.COMPOSER = this.composerStr;
  1354. this.currentSong.LYRICIST = this.lyricistStr;
  1355. this.currentSong.COMMENT = this.commentStr;
  1356. }
  1357. // if (result.needRefreshList && this.modeType == 0) {
  1358. // this.deleteCache(this.currentPath);
  1359. // this.getSortedFiles(this.currentPath);
  1360. // }
  1361. // 同步编辑字段到本地列表
  1362. if (this.editingItem) {
  1363. this.syncEditedFields(this.editingItem);
  1364. this.syncListsAfterEdit(this.editingItem.filePath);
  1365. this.doUpateEditedFields(this.editingItem);
  1366. }
  1367. // 清理临时变量
  1368. this.longItemFilePath = '';
  1369. this.tempLyricContent = '';
  1370. this.isShowEdit = false;
  1371. this.imagePathStr = '';
  1372. } else {
  1373. console.error("heanup 编辑信息失败: " + result.error);
  1374. ToastUtil.showToast('编辑失败: ' + (result.error || '未知错误'));
  1375. // 清理临时变量
  1376. this.longItemFilePath = '';
  1377. this.tempLyricContent = '';
  1378. this.isShowEdit = false;
  1379. this.imagePathStr = '';
  1380. }
  1381. }
  1382. private assignStringMetadata(target: VideoItem, key: keyof VideoItem, value?: string | null, allowEmpty = false): void {
  1383. if (value === undefined || value === null) {
  1384. return;
  1385. }
  1386. const text = value.toString();
  1387. if (!allowEmpty && text.trim().length === 0) {
  1388. return;
  1389. }
  1390. Reflect.set(target, key as string, value);
  1391. }
  1392. private assignNumberMetadata(target: VideoItem, key: keyof VideoItem, value?: number | null): void {
  1393. if (value === undefined || value === null || Number.isNaN(value)) {
  1394. return;
  1395. }
  1396. Reflect.set(target, key as string, value);
  1397. }
  1398. private mergeVideoItemWithPayload(target: VideoItem, payload: WorkerMetadataPayload): void {
  1399. if (!target || !payload) {
  1400. return;
  1401. }
  1402. this.assignStringMetadata(target, 'name', payload.name);
  1403. this.assignStringMetadata(target, 'artist', payload.artist);
  1404. this.assignStringMetadata(target, 'album', payload.album);
  1405. this.assignStringMetadata(target, 'bit_rate', payload.bit_rate);
  1406. this.assignStringMetadata(target, 'duration', payload.duration);
  1407. this.assignStringMetadata(target, 'sampleRate', payload.sampleRate);
  1408. this.assignStringMetadata(target, 'mimeType', payload.mimeType);
  1409. this.assignStringMetadata(target, 'size', payload.size);
  1410. this.assignStringMetadata(target, 'pixelMapPath', payload.pixelMapPath);
  1411. this.assignStringMetadata(target, 'lyricContent', payload.lyricContent, true);
  1412. this.assignStringMetadata(target, 'genre', payload.genre);
  1413. this.assignStringMetadata(target, 'track', payload.track);
  1414. this.assignStringMetadata(target, 'bits_per_raw_sample', payload.bits_per_raw_sample);
  1415. this.assignStringMetadata(target, 'channels', payload.channels);
  1416. this.assignStringMetadata(target, 'channel_layout', payload.channel_layout);
  1417. this.assignStringMetadata(target, 'start_time', payload.start_time);
  1418. this.assignStringMetadata(target, 'year', payload.year);
  1419. this.assignStringMetadata(target, 'disc', payload.disc);
  1420. this.assignStringMetadata(target, 'ALBUMARTIST', payload.ALBUMARTIST);
  1421. this.assignStringMetadata(target, 'COMPOSER', payload.COMPOSER);
  1422. this.assignStringMetadata(target, 'LYRICIST', payload.LYRICIST);
  1423. this.assignStringMetadata(target, 'COMMENT', payload.COMMENT, true);
  1424. this.assignNumberMetadata(target, 'videoSize', payload.videoSize);
  1425. this.assignNumberMetadata(target, 'probe_score', payload.probe_score);
  1426. this.assignNumberMetadata(target, 'nb_streams', payload.nb_streams);
  1427. this.assignNumberMetadata(target, 'nb_programs', payload.nb_programs);
  1428. }
  1429. private mergeVideoItemFromSource(target: VideoItem, source: VideoItem): void {
  1430. if (!target || !source) {
  1431. return;
  1432. }
  1433. this.assignStringMetadata(target, 'name', source.name);
  1434. this.assignStringMetadata(target, 'artist', source.artist);
  1435. this.assignStringMetadata(target, 'album', source.album);
  1436. this.assignStringMetadata(target, 'bit_rate', source.bit_rate);
  1437. this.assignStringMetadata(target, 'duration', source.duration);
  1438. this.assignStringMetadata(target, 'sampleRate', source.sampleRate);
  1439. this.assignStringMetadata(target, 'trackCount', source.trackCount);
  1440. this.assignStringMetadata(target, 'mimeType', source.mimeType);
  1441. this.assignStringMetadata(target, 'size', source.size);
  1442. this.assignStringMetadata(target, 'pixelMapPath', source.pixelMapPath);
  1443. this.assignStringMetadata(target, 'lyricContent', source.lyricContent, true);
  1444. this.assignStringMetadata(target, 'genre', source.genre);
  1445. this.assignStringMetadata(target, 'track', source.track);
  1446. this.assignStringMetadata(target, 'bits_per_raw_sample', source.bits_per_raw_sample);
  1447. this.assignStringMetadata(target, 'channels', source.channels);
  1448. this.assignStringMetadata(target, 'channel_layout', source.channel_layout);
  1449. this.assignStringMetadata(target, 'start_time', source.start_time);
  1450. this.assignStringMetadata(target, 'year', source.year);
  1451. this.assignStringMetadata(target, 'disc', source.disc);
  1452. this.assignStringMetadata(target, 'ALBUMARTIST', source.ALBUMARTIST);
  1453. this.assignStringMetadata(target, 'COMPOSER', source.COMPOSER);
  1454. this.assignStringMetadata(target, 'LYRICIST', source.LYRICIST);
  1455. this.assignStringMetadata(target, 'COMMENT', source.COMMENT, true);
  1456. this.assignNumberMetadata(target, 'videoSize', source.videoSize);
  1457. this.assignNumberMetadata(target, 'probe_score', source.probe_score);
  1458. this.assignNumberMetadata(target, 'nb_streams', source.nb_streams);
  1459. this.assignNumberMetadata(target, 'nb_programs', source.nb_programs);
  1460. if (source.remote_rel_path && StrUtil.isEmpty(target.remote_rel_path)) {
  1461. target.remote_rel_path = source.remote_rel_path;
  1462. }
  1463. }
  1464. private async hydrateRemoteSongFromDb(item: VideoItem | undefined): Promise<void> {
  1465. if (!item || !isRemoteCloudType(item.type)) {
  1466. return;
  1467. }
  1468. const storagePath = item.remote_rel_path || WebDavUrlUtil.toStoragePath(item.filePath);
  1469. if (!storagePath) {
  1470. return;
  1471. }
  1472. try {
  1473. const cached = await this.table.queryVideoByFilePath(storagePath);
  1474. if (!cached) {
  1475. return;
  1476. }
  1477. this.mergeVideoItemFromSource(item, cached);
  1478. if (StrUtil.isEmpty(item.remote_rel_path)) {
  1479. item.remote_rel_path = storagePath;
  1480. }
  1481. if (item === this.currentSong) {
  1482. if (StrUtil.isNotEmpty(item.name)) {
  1483. this.name = item.name;
  1484. }
  1485. if (StrUtil.isNotEmpty(item.artist)) {
  1486. this.artist = item.artist!;
  1487. }
  1488. if (StrUtil.isNotEmpty(item.pixelMapPath)) {
  1489. this.cover = item.pixelMapPath!;
  1490. }
  1491. if (StrUtil.isNotEmpty(item.lyricContent) && StrUtil.isEmpty(this.lyricContent)) {
  1492. this.applyInlineLyricContent(item.lyricContent as string);
  1493. }
  1494. }
  1495. } catch (error) {
  1496. Logger.error(TAG, `hydrateRemoteSongFromDb 失败: ${(error as Error).message}`);
  1497. }
  1498. }
  1499. private applyInlineLyricContent(content: string): void {
  1500. if (StrUtil.isEmpty(content)) {
  1501. return;
  1502. }
  1503. this.lyricContent = content;
  1504. const lines: string[] = content.split('\n').map((line: string) => line.trim());
  1505. const lyric: Lyric = this.parser.parse(lines);
  1506. this.lyricController.setLyric(lyric);
  1507. this.lyricControllerXF.setLyric(lyric);
  1508. this.lyricControllerSingle.setLyric(lyric);
  1509. }
  1510. private extractParentPathFromStoragePath(path: string): string {
  1511. if (!path) {
  1512. return '';
  1513. }
  1514. const lastSlash = path.lastIndexOf('/');
  1515. if (lastSlash <= 0) {
  1516. return '';
  1517. }
  1518. return path.substring(0, lastSlash);
  1519. }
  1520. private resolveRemoteStoragePath(target: VideoItem): string | null {
  1521. if (!target || !isRemoteCloudType(target.type)) {
  1522. return null;
  1523. }
  1524. if (isWebDavType(target.type)) {
  1525. const storagePath = target.remote_rel_path || WebDavUrlUtil.toStoragePath(target.filePath);
  1526. if (storagePath) {
  1527. target.remote_rel_path = storagePath;
  1528. return storagePath;
  1529. }
  1530. return null;
  1531. }
  1532. if (target.remote_rel_path && target.remote_rel_path.length > 0) {
  1533. return target.remote_rel_path;
  1534. }
  1535. return null;
  1536. }
  1537. private async persistRemoteMetadataToDb(target: VideoItem): Promise<void> {
  1538. if (!this.context || !target || !isRemoteCloudType(target.type)) {
  1539. return;
  1540. }
  1541. const storagePath = this.resolveRemoteStoragePath(target);
  1542. if (!storagePath) {
  1543. return;
  1544. }
  1545. const table = new MediaTable(this.context);
  1546. await new Promise<void>((resolve) => {
  1547. table.getRdbStore(this.context as Context, () => resolve());
  1548. });
  1549. const cloneItem = cloneVideoItem(target);
  1550. cloneItem.filePath = storagePath;
  1551. cloneItem.remote_rel_path = storagePath;
  1552. cloneItem.parentPath = this.extractParentPathFromStoragePath(storagePath);
  1553. await table.saveOrUpdateWebDavItem(cloneItem);
  1554. }
  1555. onPageHide(): void {
  1556. this.knockController?.immersiveDisableListening();
  1557. }
  1558. @State isFirstStartPlay: boolean = false
  1559. private async startFileDeletionWatcher(): Promise<void> {
  1560. if (!this.rootPath) {
  1561. return;
  1562. }
  1563. if (!this.deletionWatcher) {
  1564. this.deletionWatcher = new FileDeletionWatcher(this.context, this.table);
  1565. }
  1566. try {
  1567. await this.deletionWatcher.watchDirectories([
  1568. this.rootPath,
  1569. this.lockPath,
  1570. this.favPath,
  1571. this.historyPath
  1572. ]);
  1573. } catch (error) {
  1574. Logger.error(TAG, `初始化文件删除监听失败: ${(error as Error).message}`);
  1575. }
  1576. }
  1577. //获取download_path
  1578. async mkDownLoadDir() {
  1579. const documentViewPicker = new picker.DocumentViewPicker()
  1580. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  1581. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  1582. PreferencesUtil.putSync('download_path', this.rootPath+'/')
  1583. this.currentPath = this.rootPath
  1584. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  1585. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  1586. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  1587. Logger.info('onecold rootPath = ' + this.rootPath)
  1588. Logger.info('onecold lockPath = ' + this.lockPath)
  1589. if (!FileUtil.accessSync(this.lockPath)) {
  1590. FileUtil.mkdirSync(this.lockPath)
  1591. }
  1592. if (!FileUtil.accessSync(this.favPath)) {
  1593. FileUtil.mkdirSync(this.favPath)
  1594. }
  1595. if (!FileUtil.accessSync(this.historyPath)) {
  1596. FileUtil.mkdirSync(this.historyPath)
  1597. }
  1598. // await this.startFileDeletionWatcher();
  1599. this.getSortedFiles(this.rootPath).then(async () => {
  1600. this.isFavMusic = false
  1601. //穿山甲
  1602. // this.loadBannerAd(CSJUtil.getBannerID())
  1603. this.restoreLastPlayContext();
  1604. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  1605. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  1606. if (ArrayUtil.isEmpty(this.songList)) {
  1607. this.songList = this.getCurFileList()
  1608. } else {
  1609. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  1610. }
  1611. if (ArrayUtil.isNotEmpty(this.songList)) {
  1612. this.isFirstStartPlay = true
  1613. this.sonDataSource.pushArrayData(this.songList)
  1614. if (this.currentSong === undefined) {
  1615. this.isFirstStartPlay = false
  1616. this.currentSong = this.songList[0]
  1617. }
  1618. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  1619. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  1620. context: this.context,
  1621. autoParseMusicName: this.autoParseMusicName
  1622. });
  1623. Logger.info(TAG, `WebDAV URL同步构建完成: ${this.videoUrl}`);
  1624. this.name = this.currentSong.name
  1625. this.cover = this.currentSong.pixelMapPath
  1626. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  1627. } else {
  1628. this.name = '空空如也'
  1629. }
  1630. })
  1631. this.getFavList(false)
  1632. }
  1633. getFavList(isFavRefresh: boolean) {
  1634. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  1635. this.favList = result
  1636. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  1637. this.videoLocalList = this.favList
  1638. this.updateListData(this.videoLocalList, true)
  1639. }
  1640. })
  1641. }
  1642. getHistoryList(isRefresh: boolean) {
  1643. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  1644. this.historyList = result
  1645. // for (let i = 0; i < this.historyList.length; i++) {
  1646. //
  1647. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  1648. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  1649. // }
  1650. if (isRefresh) {
  1651. this.videoLocalList = this.historyList
  1652. this.updateListData(this.videoLocalList, true)
  1653. }
  1654. })
  1655. }
  1656. // 组件消失生命周期
  1657. aboutToDisappear() {
  1658. console.info('LifeCycleComponent aboutToDisappear');
  1659. this.deletionWatcher?.stop();
  1660. this.knockController?.immersiveDisableListening();
  1661. this.curIndex = 0
  1662. emitter.off(EventConstants.EVENT_AUDIO_OPEN);
  1663. emitter.off(EventConstants.EVENT_SCAN_UPDATE);
  1664. emitter.off(EventConstants.EVENT_SWIPE_BACK_UPDATE);
  1665. emitter.off(EventConstants.EVENT_SETTING_UPDATE);
  1666. emitter.off(EventConstants.EVENT_WEBDAV_METADATA_UPDATED);
  1667. this.mDestroyPage = true;
  1668. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  1669. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  1670. this.stop();
  1671. }
  1672. this.mIjkMediaPlayer.off('audioInterrupt');
  1673. this.mIjkMediaPlayer.off('deviceChange');
  1674. if (workerInstance) {
  1675. workerInstance.terminate();
  1676. }
  1677. this.stopPip();
  1678. this.destroyPipController()
  1679. this.getUIContext().getHostContext()!.eventHub.off('playOrPause');
  1680. this.getUIContext().getHostContext()!.eventHub.off('playPrevious');
  1681. this.getUIContext().getHostContext()!.eventHub.off('playNext');
  1682. this.getUIContext().getHostContext()!.eventHub.off('showPlayerView');
  1683. this.getUIContext().getHostContext()!.eventHub.off('openPlayList');
  1684. }
  1685. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean,openItem?:VideoItem) {
  1686. this.isFavMusic = false
  1687. console.info('onecold getSortedFiles 1 curPath '+curPath)
  1688. if (isWorkerPost) {
  1689. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1690. }
  1691. if (this.modeType !== 0) {
  1692. return
  1693. }
  1694. console.info('onecold getSortedFiles 2')
  1695. this.isCanBack = false
  1696. this.currentPath = curPath
  1697. console.info('onecold getSortedFiles this.currentPath ='+this.currentPath)
  1698. this.titleName = getFileDirName(this.currentPath,this.rootPath)
  1699. if (curPath === this.rootPath) {
  1700. this.rightTopImage = $r('sys.symbol.sort')
  1701. } else {
  1702. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  1703. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  1704. this.rightTopImage = $r('sys.symbol.chevron_left')
  1705. }
  1706. }
  1707. // Get the current file list and calculate its hash
  1708. this.fileList = FileUtil.listFileSync(curPath);
  1709. const currentHash = simpleHash(this.fileList);
  1710. // Check cache
  1711. const cachedValue = this.findCache(curPath);
  1712. Logger.info('onecold cachedValue = ' + cachedValue)
  1713. const cachedHash = this.findStringCache(curPath + '_hash');
  1714. const cachedDirList = this.findCache(curPath + "_dirList");
  1715. if (cachedValue !== undefined&&!this.isRefreshing) {
  1716. // this.videoLocalList = cachedValue;
  1717. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  1718. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  1719. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  1720. }
  1721. this.isRefreshing = false
  1722. this.updateListData(cachedValue)
  1723. }
  1724. if (cachedDirList !== undefined) {
  1725. this.dirList = cachedDirList
  1726. }
  1727. //通过当前hash值和缓存hash判断list有没有变化
  1728. if (cachedValue && cachedHash === currentHash) {
  1729. return;
  1730. }
  1731. // this.fileList = FileUtil.listFileSync(curPath)
  1732. let directories: Array<VideoItem> = [];
  1733. let files: Array<VideoItem> = [];
  1734. for (let i = 0; i < this.fileList.length; i++) {
  1735. // console.info(`The name of file: ${this.fileList[i]}`);
  1736. let path = curPath + '/' + this.fileList[i]
  1737. if (FileUtil.isDirectory(path)) {
  1738. let item: VideoItem =
  1739. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  1740. '')
  1741. if (this.isShowDir(item.name)) {
  1742. directories.push(item);
  1743. }
  1744. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1745. // Utility.doSortListAscending(directories)
  1746. } else {
  1747. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  1748. let item: VideoItem =
  1749. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  1750. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  1751. files.push(item);
  1752. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1753. // this.doSortListAscending(files)
  1754. }
  1755. }
  1756. }
  1757. }
  1758. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  1759. if (this.currentPath !== this.lockPath) {
  1760. files = result;
  1761. }
  1762. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1763. Utility.doSortListAscending(files)
  1764. if (this.currentPath === this.rootPath) {
  1765. this.dirList = directories
  1766. this.addCache(curPath + "_dirList", this.dirList);
  1767. }
  1768. //插入广告先注释掉
  1769. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  1770. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  1771. // directories.push(adItem)
  1772. // }
  1773. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  1774. this.videoLocalList = directories.concat(files);
  1775. this.updateListData(this.videoLocalList)
  1776. if (ArrayUtil.isNotEmpty(files)) {
  1777. if (this.currentPath != this.rootPath) {
  1778. if (files) {
  1779. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  1780. }
  1781. }
  1782. // 缓存结果
  1783. this.addCache(curPath, this.videoLocalList);
  1784. await this.saveCacheToStorage(); // 保存缓存至本地存储
  1785. this.addStringCache(curPath + '_hash', currentHash);
  1786. }
  1787. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  1788. for (let i = 0; i < this.videoLocalList.length; i++) {
  1789. console.info(`onecold gengxin 1: ${this.videoLocalList[i].name}`);
  1790. }
  1791. // this.setButtonStatus()
  1792. this.openMusic(isOpen, destPath,openItem)
  1793. this.isRefreshing = false
  1794. });
  1795. }
  1796. //第三方app打开天天静听导入音乐后播放
  1797. openMusic(isOpen?: boolean, destPath?: string,openItem?:VideoItem){
  1798. if (isOpen&&destPath) {
  1799. if (destPath === undefined) {
  1800. // 处理 destPath 为 undefined 的情况
  1801. return
  1802. }
  1803. if (destPath.endsWith('.lrc')) {
  1804. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  1805. if (StrUtil.isNotEmpty(this.videoUrl)) {
  1806. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  1807. this.initLyric(lyricPath);
  1808. }
  1809. return
  1810. }
  1811. if(openItem){
  1812. this.doPlay(openItem,0,false,true)
  1813. // this.isShowPlay = true
  1814. this.setShowPlayTrue()
  1815. }
  1816. }
  1817. }
  1818. //扫描文件夹入库
  1819. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  1820. const files = FileUtil.listFileSync(curPath);
  1821. let mediaItems: VideoItem[] = [];
  1822. Logger.info('onecold scanDirectory start ')
  1823. for (const file of files) {
  1824. const fPath = `${curPath}/${file}`;
  1825. if (fPath === this.lockPath) {
  1826. Logger.info(`Skipping locked path: ${fPath}`);
  1827. continue;
  1828. }
  1829. if (FileUtil.isDirectory(fPath)) {
  1830. // Recursively scan subdirectories
  1831. const subDirItems = await this.scanDirectory(fPath);
  1832. mediaItems = mediaItems.concat(subDirItems);
  1833. } else {
  1834. Logger.info('onecold scanDirectory filePath = ' + fPath)
  1835. // Process media files
  1836. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  1837. let mediaItem: VideoItem =
  1838. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1839. mediaItems.push(mediaItem);
  1840. this.table.insert(mediaItem, (id: number) => {
  1841. });
  1842. }
  1843. }
  1844. }
  1845. return mediaItems;
  1846. }
  1847. updateListData(mList: Array<VideoItem>, noSort?: boolean) {
  1848. this.isShowTitleBar = true
  1849. this.getUIContext().animateTo({ duration: 666 }, () => {
  1850. this.opacityItem = 0.5;
  1851. });
  1852. setTimeout(() => {
  1853. this.videoLocalList = mList;
  1854. if (!noSort) {
  1855. if (this.modeType === 0 || this.modeType === 1) {
  1856. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1857. this.doSortType(this.sortType)
  1858. }
  1859. }
  1860. this.dataSource.pushArrayData(this.videoLocalList)
  1861. this.getUIContext().animateTo({ duration: 666 }, () => {
  1862. this.opacityItem = 1;
  1863. });
  1864. this.setButtonStatus()
  1865. //添加到字母索引表
  1866. this.setAlphaBet()
  1867. }, 200);
  1868. }
  1869. getCurFileList(): Array<VideoItem> {
  1870. if(this.isSearchMode){
  1871. return this.filteredList
  1872. }
  1873. let files: Array<VideoItem> = [];
  1874. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1875. for (let i = 0; i < this.videoLocalList.length; i++) {
  1876. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  1877. files.push(this.videoLocalList[i]);
  1878. }
  1879. }
  1880. }
  1881. return files
  1882. }
  1883. setButtonStatus() {
  1884. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1885. this.isZero = false
  1886. } else {
  1887. this.isZero = true
  1888. }
  1889. if (this.currentPath !== this.rootPath &&
  1890. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  1891. this.isHasDir = true //不为空,说明有子文件夹
  1892. } else {
  1893. this.isHasDir = false
  1894. }
  1895. }
  1896. private getPlayListDisplayCount(): number {
  1897. if (this.playQueueScope === 'history') {
  1898. return this.historyList.length;
  1899. }
  1900. if (this.playQueueScope === 'fav') {
  1901. return this.favList.length;
  1902. }
  1903. if (this.playQueueScope === 'playlist') {
  1904. return this.currentSongList.length;
  1905. }
  1906. if (this.playQueueScope === 'view' && this.modeType === 1 && this.totalCount > 0) {
  1907. return this.totalCount;
  1908. }
  1909. return this.songList.length;
  1910. }
  1911. private restoreLastPlayContext(): void {
  1912. const scope = PreferencesUtil.getStringSync('LastPlayQueueScope', 'view') as string;
  1913. if (scope === 'history' || scope === 'fav' || scope === 'playlist' || scope === 'single') {
  1914. this.playQueueScope = scope;
  1915. } else {
  1916. this.playQueueScope = 'view';
  1917. }
  1918. const lastModeType = PreferencesUtil.getNumberSync('LastPlayModeType', this.modeType);
  1919. const lastTotalCount = PreferencesUtil.getNumberSync('LastPlayTotalCount', 0);
  1920. if (lastModeType === 1 && this.totalCount === 0 && lastTotalCount > 0) {
  1921. this.totalCount = lastTotalCount;
  1922. }
  1923. }
  1924. private async hydrateFullMediaPlayListIfNeeded(isSonList:boolean = true): Promise<void> {
  1925. if (this.isHydratingPlayList) {
  1926. return;
  1927. }
  1928. if (this.playQueueScope !== 'view' || this.modeType !== 1) {
  1929. return;
  1930. }
  1931. if (this.totalCount === 0 || this.songList.length >= this.totalCount) {
  1932. return;
  1933. }
  1934. this.isHydratingPlayList = true;
  1935. try {
  1936. const fullList: VideoItem[] = [];
  1937. let pageIndex = 0;
  1938. let hasMore = true;
  1939. while (hasMore) {
  1940. const result = await this.table.queryMediaLibraryPaged({
  1941. pageIndex,
  1942. pageSize: this.pageSize,
  1943. sortType: this.sortType,
  1944. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  1945. isShowFileName: this.isShowFileName
  1946. });
  1947. if (result.items.length === 0) {
  1948. break;
  1949. }
  1950. fullList.push(...result.items);
  1951. hasMore = result.hasMore;
  1952. pageIndex += 1;
  1953. if (fullList.length >= result.totalCount) {
  1954. hasMore = false;
  1955. }
  1956. }
  1957. if (fullList.length > 0) {
  1958. if(isSonList){
  1959. this.songList = fullList;
  1960. this.sonDataSource.pushArrayData(this.songList);
  1961. }else{
  1962. this.videoLocalList = fullList;
  1963. this.dataSource.pushArrayData(this.videoLocalList);
  1964. }
  1965. }
  1966. } finally {
  1967. this.isHydratingPlayList = false;
  1968. }
  1969. }
  1970. @Builder
  1971. SortMenuBuilder() {
  1972. Menu() {
  1973. MenuItem({
  1974. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  1975. content: "按艺术家升序"
  1976. })
  1977. .onClick(async () => {
  1978. await this.doSortType(0)
  1979. })
  1980. MenuItem({
  1981. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  1982. content: "按艺术家降序"
  1983. })
  1984. .onClick(async () => {
  1985. await this.doSortType(1)
  1986. })
  1987. MenuItem({
  1988. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat_size_square')),
  1989. content: "按专辑升序"
  1990. })
  1991. .onClick(async () => {
  1992. await this.doSortType(2)
  1993. })
  1994. MenuItem({
  1995. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.character_arrow_clockwise')),
  1996. content: "按专辑降序"
  1997. })
  1998. .onClick(async () => {
  1999. await this.doSortType(3)
  2000. })
  2001. MenuItem({
  2002. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  2003. content: $r('app.string.sort_by_name')
  2004. })
  2005. .onClick(async () => {
  2006. await this.doSortType(4)
  2007. })
  2008. MenuItem({
  2009. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  2010. content: '按名称降序'
  2011. })
  2012. .onClick(async () => {
  2013. await this.doSortType(5)
  2014. })
  2015. MenuItem({
  2016. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2017. content: $r('app.string.sort_by_time')
  2018. })
  2019. .onClick(async () => {
  2020. await this.doSortType(6)
  2021. })
  2022. MenuItem({
  2023. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
  2024. content: '按添加时间降序'
  2025. })
  2026. .onClick(async () => {
  2027. await this.doSortType(7)
  2028. })
  2029. }.attributeModifier(new MenuModifier())
  2030. }
  2031. @Builder
  2032. SortMenuForArtistAblumBuilder() {
  2033. Menu() {
  2034. MenuItem({
  2035. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  2036. content: $r('app.string.sort_by_name')
  2037. })
  2038. .onClick(async () => {
  2039. await this.doSortType(4)
  2040. })
  2041. MenuItem({
  2042. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  2043. content: '按名称降序'
  2044. })
  2045. .onClick(async () => {
  2046. await this.doSortType(5)
  2047. })
  2048. MenuItem({
  2049. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2050. content: '按数量升序'
  2051. })
  2052. .onClick(async () => {
  2053. await this.doSortType(8)
  2054. })
  2055. MenuItem({
  2056. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
  2057. content: '按数量降序'
  2058. })
  2059. .onClick(async () => {
  2060. await this.doSortType(9)
  2061. })
  2062. }.attributeModifier(new MenuModifier())
  2063. }
  2064. async doSortType(index: number): Promise<void> {
  2065. Logger.info('heanup LocalMusic', `doSortType: 切换排序方式 sortType=${index}, mode=${this.modeType}`);
  2066. this.sortType = index;
  2067. this.saveSortTypeForCurrentMode(index);
  2068. // 分页模式下,排序需要重新从数据库查询
  2069. await this.resetAndLoadFirstPage();
  2070. }
  2071. /**
  2072. * 根据当前模式保存排序类型到不同的存储键
  2073. */
  2074. private saveSortTypeForCurrentMode(sortType: number): void {
  2075. let storageKey = SettingPage.SORT_TYPE;
  2076. if (this.modeType === 2) {
  2077. storageKey = 'SORT_TYPE_ARTIST';
  2078. } else if (this.modeType === 3) {
  2079. storageKey = 'SORT_TYPE_ALBUM';
  2080. } else {
  2081. storageKey = SettingPage.SORT_TYPE;
  2082. }
  2083. PreferencesUtil.putSync(storageKey, sortType);
  2084. }
  2085. /**
  2086. * 根据当前模式加载排序类型
  2087. */
  2088. private loadSortTypeForCurrentMode(): number {
  2089. let storageKey = SettingPage.SORT_TYPE;
  2090. let defaultSortType = 4;
  2091. if (this.modeType === 2) {
  2092. storageKey = 'SORT_TYPE_ARTIST';
  2093. defaultSortType = 9; // 艺术家模式默认按数量降序
  2094. } else if (this.modeType === 3) {
  2095. storageKey = 'SORT_TYPE_ALBUM';
  2096. defaultSortType = 9; // 专辑模式默认按数量降序
  2097. }
  2098. return PreferencesUtil.getNumberSync(storageKey, defaultSortType);
  2099. }
  2100. showSheelDialog() {
  2101. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  2102. // this.showTips()
  2103. // return
  2104. // }
  2105. this.showAddDialog()
  2106. }
  2107. showAddDialog() {
  2108. if (this.modeType === 2 || this.modeType === 3) {
  2109. return
  2110. }
  2111. DialogHelper.showActionSheetDialog({
  2112. title: "请选择添加方式(建议歌词文件一起导入)",
  2113. sheets: [
  2114. { value: "新建文件夹", fontColor: $r('app.color.text_color') },
  2115. { value: "手动导入", fontColor: $r('app.color.text_color') },
  2116. { value: "自动导入", fontColor: $r('app.color.text_color') },
  2117. { value: "全选导入", fontColor: $r('app.color.text_color') },
  2118. ],
  2119. maskColor: Color.Transparent,
  2120. backgroundColor: $r('app.color.bg_card'),
  2121. transition: AnimationHelper.transitionInDown(555),
  2122. onAction: (index) => {
  2123. switch (index) {
  2124. case 0:
  2125. if (this.modeType === 0) {
  2126. this.showMkDialog()
  2127. } else {
  2128. ToastUtil.showToast('请切换到首页才能新建文件夹!')
  2129. }
  2130. break;
  2131. case 1:
  2132. this.callFilePickerSelectFile()
  2133. break;
  2134. case 2:
  2135. this.showTips()
  2136. break;
  2137. case 3:
  2138. this.goSelectMusic()
  2139. break;
  2140. }
  2141. }
  2142. })
  2143. }
  2144. //拉起音频
  2145. goSelectMusic() {
  2146. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  2147. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  2148. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  2149. ) {
  2150. ToastUtil.showToast('暂时不支持该设备')
  2151. return
  2152. }
  2153. try {
  2154. let documentSelectOptions = new picker.DocumentSelectOptions();
  2155. documentSelectOptions.authMode = true
  2156. documentSelectOptions.multiAuthMode = true
  2157. if( deviceInfo.sdkApiVersion>=21){//如果api大于21 ,可以支持1w首歌以上
  2158. documentSelectOptions.maxSelectNumber = 20000
  2159. }
  2160. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  2161. let documentPicker = new picker.DocumentViewPicker(this.context);
  2162. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  2163. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  2164. this.saveVideoDatas(documentSelectResult)
  2165. }
  2166. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  2167. JSON.stringify(documentSelectResult));
  2168. }).catch((err: BusinessError) => {
  2169. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  2170. });
  2171. } catch (error) {
  2172. let err: BusinessError = error as BusinessError;
  2173. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2174. }
  2175. }
  2176. async showTips() {
  2177. try {
  2178. this.getUIContext().getPromptAction().showDialog({
  2179. title: '导入指南',
  2180. message:'用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  2181. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  2182. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  2183. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后去文件扫描一下。\n',
  2184. buttons: [
  2185. {
  2186. text: '知道了',
  2187. color: '#000000'
  2188. },
  2189. ]
  2190. }, (err, data) => {
  2191. if (err) {
  2192. console.error('showDialog err: ' + err);
  2193. return;
  2194. }
  2195. console.info('showDialog success callback, click button: ' + data.index);
  2196. });
  2197. } catch (error) {
  2198. let message = (error as BusinessError).message;
  2199. let code = (error as BusinessError).code;
  2200. console.error(`showDialog args error code is ${code}, message is ${message}`);
  2201. };
  2202. }
  2203. showMkDialog() {
  2204. DialogHelper.showTextInputDialog({
  2205. title: '新建歌单',
  2206. maskColor: Color.Transparent,
  2207. text: '',
  2208. transition: AnimationHelper.transitionInDown(666),
  2209. onChange: (text) => {
  2210. console.error("onChange: " + text);
  2211. },
  2212. onAction: (action, dialogId, content) => {
  2213. // ToastUtil.showToast('content = ' +content)
  2214. if (action == DialogAction.TWO) {
  2215. const newName = content
  2216. const newPath = this.currentPath + '/' + newName
  2217. FileUtil.mkdir(newPath, true).then(() => {
  2218. this.cache.delete(this.currentPath); // 删除目标路径缓存
  2219. this.getSortedFiles(this.currentPath)
  2220. }).catch((error: BusinessError) => {
  2221. console.error(error.message);
  2222. });
  2223. }
  2224. }
  2225. })
  2226. }
  2227. @State progress: number = 0;
  2228. async saveVideoDatas(uris:string[],isOpen?:boolean){
  2229. if (ArrayUtil.isEmpty(uris)) {
  2230. return;
  2231. }
  2232. console.info('onecold this.isCopyFileToDownLoad = ' + this.isCopyFileToDownLoad);
  2233. if(this.isCopyFileToDownLoad||this.currentPath==this.lockPath||isOpen){
  2234. this.saveVideoDatasToDownLoad(uris,isOpen)
  2235. return
  2236. }
  2237. // 初始化进度条
  2238. this.progress = 0;
  2239. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  2240. progress: this.progress,
  2241. backCancel: false,
  2242. autoCancel: false,
  2243. loadColor: $r('app.color.title_bar_bg'),
  2244. fontColor: $r('app.color.title_bar_bg')
  2245. });
  2246. // 计算处理总数用于进度计算
  2247. const totalItems = uris.length;
  2248. let processedItems = 0;
  2249. for (let i = 0; i < uris.length; i++) {
  2250. let filePath = uris[i];
  2251. try {
  2252. if (this.currentPath !== this.lockPath) { // 判断不是私密音乐,才入库
  2253. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2254. let mediaItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context,
  2255. filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2256. console.info('onecold saveVideoDatas filePath = ' + filePath)
  2257. if (!filePath.includes(this.rootPath)) {
  2258. console.info('onecold saveVideoDatas mediaItem.parentPath111 = ' + mediaItem.parentPath)
  2259. mediaItem.parentPath = this.currentPath;
  2260. }
  2261. console.info('onecold saveVideoDatas mediaItem.parentPath = ' + mediaItem.parentPath)
  2262. this.table.insert(mediaItem, (id: number) => {
  2263. // 插入完成回调
  2264. });
  2265. }
  2266. }
  2267. // 更新进度
  2268. processedItems++;
  2269. this.progress = Math.floor((processedItems / totalItems) * 100);
  2270. DialogHelper.updateLoading(this.loadingProgressDialogId,` 正在处理 ${this.progress}%`, this.progress);
  2271. } catch (error) {
  2272. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2273. // 即使出错也更新进度
  2274. processedItems++;
  2275. this.progress = Math.floor((processedItems / totalItems) * 100);
  2276. DialogHelper.updateLoading(this.loadingProgressDialogId,` 正在处理 ${this.progress}%`, this.progress);
  2277. }
  2278. }
  2279. // 关闭进度条
  2280. DialogHelper.closeDialog(this.loadingProgressDialogId)
  2281. this.isZero = false
  2282. // 删除目标路径缓存
  2283. setTimeout(() => {
  2284. this.cache.delete(this.currentPath);
  2285. this.getSortedFiles(this.currentPath,false,uris[0],isOpen)
  2286. this.setButtonStatus()
  2287. }, 500);
  2288. }
  2289. async saveVideoDatasToDownLoad(uris: string[], isOpen?: boolean) {
  2290. if (ArrayUtil.isEmpty(uris)) {
  2291. return;
  2292. }
  2293. let newUris: string[] = [];
  2294. this.progress = 0
  2295. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  2296. progress: this.progress,
  2297. backCancel: false,
  2298. autoCancel: false,
  2299. loadColor: this.themeColor,
  2300. fontColor: this.themeColor
  2301. });
  2302. // 计算所有文件的总大小
  2303. let totalSize = 0;
  2304. for (let uri of uris) {
  2305. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  2306. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  2307. await fileIo.close(sourceFile.fd);
  2308. }
  2309. let totalRead = 0;
  2310. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  2311. Logger.info(TAG, 'destPath uri: ' + destPath);
  2312. for (let i = 0; i < uris.length; i++) {
  2313. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  2314. Logger.info(TAG, 'filePath uri: ' + filePath);
  2315. newUris.push(filePath);
  2316. try {
  2317. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  2318. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  2319. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  2320. const buffer = new ArrayBuffer(buffSize);
  2321. let len = await fileIo.read(sourceFile.fd, buffer);
  2322. while (len > 0) {
  2323. await fileIo.write(destFile.fd, buffer.slice(0, len));
  2324. totalRead += len;
  2325. // 计算总进度
  2326. this.progress = Math.floor((totalRead / totalSize) * 100);
  2327. DialogHelper.updateLoading( this.loadingProgressDialogId,`正在导入 ${this.progress}%`, this.progress);
  2328. len = await fileIo.read(sourceFile.fd, buffer);
  2329. }
  2330. await fileIo.close(sourceFile.fd);
  2331. await fileIo.close(destFile.fd);
  2332. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  2333. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2334. let mediaItem: VideoItem =
  2335. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2336. this.table.insert(mediaItem, (id: number) => {
  2337. // 删除目标路径缓存
  2338. this.cache.delete(this.currentPath);
  2339. this.getSortedFiles(this.currentPath, true, destPath, isOpen,mediaItem)
  2340. });
  2341. }
  2342. }
  2343. } catch (error) {
  2344. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2345. }
  2346. }
  2347. DialogHelper.closeDialog(this.loadingProgressDialogId);
  2348. this.isZero = false
  2349. Logger.info(TAG, 'scan select video result:' + newUris)
  2350. }
  2351. //拉起音频
  2352. // goSelectMusic(){
  2353. //
  2354. // try {
  2355. // let audioSelectOptions = new picker.AudioSelectOptions();
  2356. // let audioPicker = new picker.AudioViewPicker(this.context);
  2357. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  2358. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  2359. // this.saveVideoDatas(audioSelectResult)
  2360. // }
  2361. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  2362. // }).catch((err: BusinessError) => {
  2363. //
  2364. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  2365. // });
  2366. // } catch (error) {
  2367. // let err: BusinessError = error as BusinessError;
  2368. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2369. // }
  2370. //
  2371. //
  2372. //
  2373. // }
  2374. async goSelectImage(item: VideoItem): Promise<string | undefined> {
  2375. if (!item) {
  2376. return undefined;
  2377. }
  2378. try {
  2379. let selectUris: Array<string> = [];
  2380. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  2381. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  2382. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  2383. photoSelectOptions.maxSelectNumber = 1;
  2384. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  2385. selectUris = photoSelectResult.photoUris;
  2386. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  2387. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  2388. console.info('file fd: ' + file.fd);
  2389. let name = await MD5.digestSync(this.videoUrl)+'.jpg'
  2390. let imagePath = this.context.filesDir + FileUtil.separator + name
  2391. imagePath = fileUri.getUriFromPath(imagePath)
  2392. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  2393. fileIo.copyFileSync(file.fd, file2.fd)
  2394. fileIo.closeSync(file);
  2395. fileIo.closeSync(file2);
  2396. if (item.filePath == this.currentSong?.filePath) {
  2397. this.cover = imagePath
  2398. }
  2399. if (item) {
  2400. item.pixelMapPath = imagePath
  2401. }
  2402. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  2403. if (success) {
  2404. this.doUpdateData()
  2405. console.log("onecold 更新音乐封面成功,数据库已同步");
  2406. } else {
  2407. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  2408. }
  2409. });
  2410. LogUtil.debug("onecold this.cover =" + this.cover)
  2411. return FileUtil.getFilePath(imagePath); // Return the image path here
  2412. } catch (err) {
  2413. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  2414. return undefined;
  2415. }
  2416. }
  2417. // 拉起picker选择文件管理器
  2418. async callFilePickerSelectFile(): Promise<void> {
  2419. try {
  2420. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  2421. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  2422. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  2423. } else {
  2424. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  2425. }
  2426. let documentPicker = new picker.DocumentViewPicker();
  2427. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  2428. Logger.info(TAG,
  2429. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  2430. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  2431. this.saveVideoDatas(DocumentSelectResult)
  2432. }
  2433. }).catch((err: BusinessError) => {
  2434. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  2435. });
  2436. } catch (err) {
  2437. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  2438. }
  2439. }
  2440. //重命名的对话框
  2441. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  2442. if(!item.filePath.includes(this.packName)){
  2443. ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限重命名')
  2444. return
  2445. }
  2446. DialogHelper.showTextInputDialog({
  2447. title: '重命名',
  2448. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  2449. maskColor: Color.Transparent,
  2450. backgroundColor: Color.Grey,
  2451. transition: AnimationHelper.transitionInDown(666),
  2452. onChange: (text) => {
  2453. console.error("onChange: " + text);
  2454. },
  2455. onAction: (action, dialogId, content) => {
  2456. // ToastUtil.showToast('content = ' +content)
  2457. if (action == DialogAction.TWO) {
  2458. const newName = content
  2459. const newPath = this.currentPath + '/' + newName
  2460. console.log("onecold item = " + item.type);
  2461. this.doReName(index, newName, filePath, newPath, item)
  2462. }
  2463. }
  2464. })
  2465. }
  2466. //剪切 移动到另个文件夹的对话框
  2467. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  2468. Logger.info('onecold showCutDialog')
  2469. let mList: Array<string> = []
  2470. let rPath = this.rootPath
  2471. if (isCurrent) {
  2472. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2473. rPath = this.currentPath
  2474. } else {
  2475. mList = Utility.getNameList(this.dirList);
  2476. rPath = this.rootPath
  2477. }
  2478. let dataBean = new BubbleBean()
  2479. dataBean.data = mList
  2480. dataBean.color = this.themeColor
  2481. dataBean.onItemClick = (i) => {
  2482. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  2483. Logger.info('newPath = ' + newPath)
  2484. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  2485. ToastUtil.showToast('移动成功')
  2486. this.table.deleteData(item, () => {
  2487. });
  2488. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2489. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2490. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2491. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2492. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2493. this.table.insert(newItem, (id: number) => {
  2494. //加入数据库
  2495. });
  2496. }
  2497. this.cache.delete(this.currentPath); // 删除原路径缓存
  2498. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  2499. this.getSortedFiles(this.currentPath, true)
  2500. }).catch((error: BusinessError) => {
  2501. console.error(error.message);
  2502. });
  2503. XPopup.dismissTop()
  2504. }
  2505. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  2506. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  2507. popupPosition = PopupPosition.TOP
  2508. }
  2509. if (index <= 3) {
  2510. popupPosition = PopupPosition.BOTTOM
  2511. }
  2512. let pup: XPopup
  2513. if (this.isDarkMode) {
  2514. pup = XPopup.Builder()
  2515. .setPopupPosition(popupPosition)
  2516. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  2517. .setBackgroundColor(Color.Black)
  2518. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2519. .show()
  2520. } else {
  2521. pup = XPopup.Builder()
  2522. .setPopupPosition(popupPosition)
  2523. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  2524. .setBackgroundColor(Color.White)
  2525. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2526. .show()
  2527. }
  2528. }
  2529. //复制 到另个文件夹的对话框
  2530. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  2531. Logger.info('onecoldv showCopyDialog')
  2532. let mList: Array<string> = []
  2533. let rPath = this.rootPath
  2534. if (isCurrent) {
  2535. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2536. rPath = this.currentPath
  2537. } else {
  2538. mList = Utility.getNameList(this.dirList);
  2539. rPath = this.rootPath
  2540. }
  2541. let dataBean = new BubbleBean()
  2542. dataBean.data = mList
  2543. dataBean.isCopy = true
  2544. dataBean.color = this.themeColor
  2545. dataBean.onItemClick = (i) => {
  2546. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  2547. Logger.info('newPath = ' + newPath)
  2548. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  2549. ToastUtil.showToast('复制成功')
  2550. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  2551. this.getSortedFiles(this.currentPath)
  2552. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2553. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2554. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2555. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2556. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2557. this.table.insert(newItem, (id: number) => {
  2558. //加入数据库
  2559. });
  2560. }
  2561. }).catch((error: BusinessError) => {
  2562. console.error(error.message);
  2563. });
  2564. XPopup.dismissTop()
  2565. }
  2566. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  2567. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  2568. popupPosition = PopupPosition.TOP
  2569. }
  2570. if (index <= 3) {
  2571. popupPosition = PopupPosition.BOTTOM
  2572. }
  2573. let pup: XPopup
  2574. if (this.isDarkMode) {
  2575. pup = XPopup.Builder()
  2576. .setPopupPosition(popupPosition)
  2577. .atView(id)
  2578. .setMaxHeight('60%')
  2579. .setBackgroundColor(Color.Black)
  2580. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2581. .show();
  2582. } else {
  2583. pup = XPopup.Builder()
  2584. .setPopupPosition(popupPosition)
  2585. .atView(id)
  2586. .setMaxHeight('60%')
  2587. .setBackgroundColor(Color.White)
  2588. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2589. .show();
  2590. }
  2591. }
  2592. //重命名索引index的视频
  2593. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  2594. FileUtil.rename(oldPath, newPath).then(async () => {
  2595. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2596. if (info.type === CommonConstants.TYPE_IS_DIR) {
  2597. //如果是文件夹先删除源数据,再添加新数据
  2598. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  2599. if (success) {
  2600. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  2601. } else {
  2602. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  2603. }
  2604. });
  2605. this.scanDirectory(newPath)
  2606. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  2607. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  2608. if (success) {
  2609. console.log(" onecold 重命名成功,数据库已同步");
  2610. } else {
  2611. console.error(" onecold 重命名数据库失败原因: " + error);
  2612. }
  2613. });
  2614. }
  2615. let mediaItem: VideoItem =
  2616. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2617. this.videoLocalList[index] = mediaItem;
  2618. }
  2619. this.cache.delete(this.currentPath)
  2620. this.getSortedFiles(this.currentPath, true)
  2621. }).catch((error: BusinessError) => {
  2622. console.error(error.message);
  2623. });
  2624. }
  2625. build() {
  2626. Stack() {
  2627. this.ContentBuild()
  2628. Stack() {
  2629. Column()
  2630. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  2631. height: '95%',
  2632. dragBar: true,
  2633. showClose: true,
  2634. blurStyle: BlurStyle.Thin,
  2635. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  2636. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  2637. title: {
  2638. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  2639. + `(${this.getPlayListDisplayCount()}首)`
  2640. }
  2641. })
  2642. }
  2643. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  2644. modalTransition:ModalTransition.DEFAULT,
  2645. onWillDisappear: () => {
  2646. this.setShowPlayFalse()
  2647. },
  2648. })
  2649. }
  2650. .alignContent(Alignment.Bottom)
  2651. .width('100%')
  2652. .height('100%')
  2653. }
  2654. @Builder
  2655. ContentBuild() {
  2656. Scroll() {
  2657. Column() {
  2658. Stack() {
  2659. //libraryname加上去后onKeyEvent监听不了,因为目前的解决方案是上面的XComponent,去掉libraryname
  2660. XComponent({ id: 'for_onKeyEvent',type: XComponentType.SURFACE,
  2661. controller: this.xcomponentController })
  2662. .onLoad(async (event?: object) => {
  2663. })
  2664. .focusable(true)
  2665. .height(0)
  2666. .focusOnTouch(true)
  2667. .defaultFocus(true) // 自动获取键盘焦点
  2668. .onKeyEvent((event?: KeyEvent) => {
  2669. console.info('onecold点击 onKeyEvent')
  2670. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  2671. if (!event || event.type !== KeyType.Down) {
  2672. return;
  2673. }
  2674. console.info('onecold点击 onKeyEvent event.keyCode: ' + event.keyCode)
  2675. //空格键 Space key controls pause/play
  2676. if (event.keyCode === KeyCode.KEYCODE_SPACE|| event.keyCode === KeyCode.KEYCODE_MEDIA_PLAY_PAUSE) {
  2677. this.playOrPause()
  2678. }
  2679. if (event.keyCode === KeyCode.KEYCODE_DPAD_UP) {
  2680. this.playPrevious()
  2681. }
  2682. if (event.keyCode === KeyCode.KEYCODE_DPAD_DOWN) {
  2683. this.playNext()
  2684. }
  2685. // Right-click to fast forward
  2686. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  2687. this.fastForward()
  2688. }
  2689. // Left-click to rewind
  2690. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  2691. this.backForward()
  2692. }
  2693. })
  2694. Column() {
  2695. XComponent({
  2696. id: 'xcomponentId',
  2697. type: 'surface',
  2698. libraryname: 'ijkplayer_napi',
  2699. controller: this.xcomponentController
  2700. })
  2701. .onLoad((event?: object) => {
  2702. if (!!event) {
  2703. this.initDelayPlay(event);
  2704. }
  2705. })
  2706. .onDestroy(() => {
  2707. })
  2708. .width('100%')// .width(this.videoWidth)
  2709. .aspectRatio(this.videoAspectRatio)
  2710. }
  2711. .aspectRatio(this.videoAspectRatio)
  2712. .justifyContent(FlexAlign.Center)
  2713. .backgroundColor(Color.Transparent)
  2714. .visibility(Visibility.Hidden)
  2715. .height(CommonConstants.FULL_PERCENT)
  2716. .width(CommonConstants.FULL_PERCENT)
  2717. .bindSheet($$this.isABSheet, this.ABLoopSheet(), {
  2718. height:this.isLandscape?'80%': '43%',
  2719. dragBar: true,
  2720. showClose: true,
  2721. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  2722. blurStyle:BlurStyle.Thin,
  2723. backgroundColor:Color.Transparent,
  2724. title: { title: 'AB循环' }
  2725. })
  2726. Stack() {
  2727. Column() {
  2728. if(this.twoFingerType==4){
  2729. this.getWaterView()
  2730. }else{
  2731. if(this.isGridMusic){
  2732. this.getGridView()
  2733. }else {
  2734. this.getListView()
  2735. }
  2736. }
  2737. if (this.modeType ==0||this.modeType==4) {
  2738. Column() {
  2739. emptyView(this.themeColor)
  2740. }
  2741. .padding({ right:25 })
  2742. .onClick(()=>{
  2743. this.asyncCurrentPathOnlyFile()
  2744. })
  2745. .alignItems(HorizontalAlign.Center)
  2746. .position({ top: 200 })
  2747. .justifyContent(FlexAlign.Center)
  2748. .opacity(this.isZero ? 1 : 0)
  2749. .visibility(this.isZero&&!this.isLoadingPage && !this.isFavMusic && !this.isHistory
  2750. ? Visibility.Visible : Visibility.None)
  2751. .animation({
  2752. duration: 500,
  2753. curve: Curve.Friction // 可选动画曲线
  2754. })
  2755. .width('100%')
  2756. }
  2757. }
  2758. .layoutWeight(1)
  2759. .height('100%')
  2760. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  2761. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  2762. .onDrop((event?: DragEvent) => {
  2763. try {
  2764. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  2765. if (dragData !== undefined) {
  2766. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  2767. if (records.length > 0) {
  2768. for (let i = 0; i < records.length; i++) {
  2769. let types = records[i].getTypes();
  2770. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  2771. const fileUriUds =
  2772. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  2773. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  2774. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  2775. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  2776. this.targetFile = fileUriUds.oriUri;
  2777. this.saveVideoDatas([this.targetFile])
  2778. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  2779. }
  2780. }
  2781. }
  2782. } else {
  2783. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  2784. }
  2785. } else {
  2786. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  2787. }
  2788. } catch (error) {
  2789. const err = error as BusinessError;
  2790. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  2791. }
  2792. })
  2793. // 右侧居中的字母表索引
  2794. this.indexBuilder()
  2795. this.topTitleBar()
  2796. }
  2797. .alignContent(Alignment.Top)
  2798. .layoutWeight(1)
  2799. .height('100%')
  2800. Row() {
  2801. Button(this.isAllSelected ? '反选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  2802. .width(45)
  2803. .height(45)
  2804. .fontSize(10)
  2805. .margin({ top: 10, bottom: 10, right: 6 })
  2806. .backgroundColor(this.themeColor)
  2807. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2808. .onClick(() => {
  2809. if (this.isAllSelected) {
  2810. // 全不选
  2811. this.selectedFiles = [];
  2812. } else {
  2813. // 全选
  2814. this.selectedFiles = [...this.getCurFileList()];
  2815. }
  2816. this.isAllSelected = !this.isAllSelected;
  2817. })
  2818. Button('内嵌标签', { type: ButtonType.Capsule, stateEffect: true })
  2819. .width(72)
  2820. .height(45)
  2821. .fontSize(10)
  2822. .margin({ top: 10, bottom: 10, right: 6 })
  2823. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2824. .backgroundColor(this.themeColor)
  2825. .bindContentCover($$this.isOneKeyTags, this.TagsContentCoverBuilder(), {
  2826. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2827. })
  2828. .onClick(() => {
  2829. // if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  2830. this.isOneKeyTags = !this.isOneKeyTags
  2831. // }else{
  2832. // ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限批量内嵌标签,导入的时候请勾选复制一份。')
  2833. // }
  2834. })
  2835. Button('合并', { type: ButtonType.Circle, stateEffect: true })
  2836. .width(45)
  2837. .height(45)
  2838. .fontSize(10)
  2839. .margin({ top: 10, bottom: 10, right: 6 })
  2840. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2841. .backgroundColor(this.themeColor)
  2842. .bindContentCover($$this.isMergeAudio, this.MergeAudioBuilder(), {
  2843. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2844. })
  2845. .onClick(() => {
  2846. if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  2847. this.isMergeAudio = !this.isMergeAudio
  2848. }else{
  2849. ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限合并')
  2850. }
  2851. })
  2852. Button('+歌单', { type: ButtonType.Circle, stateEffect: true })
  2853. .width(45)
  2854. .height(45)
  2855. .fontSize(10)
  2856. .margin({ top: 10, bottom: 10, right: 6 })
  2857. .backgroundColor(this.themeColor)
  2858. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2859. .onClick(async () => {
  2860. this.longItemFilePath = ''
  2861. await this.openAddToPlaylistDialog(this.selectedFiles)
  2862. })
  2863. // Button('乱码', { type: ButtonType.Circle, stateEffect: true })
  2864. // .width(45)
  2865. // .height(45)
  2866. // .fontSize(10)
  2867. // .margin({ top: 10, bottom: 10, right: 6 })
  2868. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2869. // .backgroundColor(this.themeColor)
  2870. // .bindContentCover($$this.isFixMessy, this.FixMessyViewBuilder(), {
  2871. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2872. // })
  2873. // .onClick(() => {
  2874. // this.isFixMessy = !this.isFixMessy
  2875. // })
  2876. // Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  2877. // .width('35%')
  2878. // .height(60)
  2879. // .id('music_cut')
  2880. // .margin({ top: 10, bottom: 10, right: 6 })
  2881. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2882. // .backgroundColor(this.themeColor)
  2883. // .onClick(() => {
  2884. // this.showCutDialogForMultipleFiles(false, 'music_cut')
  2885. // })
  2886. //
  2887. // Button('移动', { type: ButtonType.Circle, stateEffect: true })
  2888. // .width('35%')
  2889. // .height(60)
  2890. // .id('music_cut_current')
  2891. // .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  2892. // .margin({ top: 10, bottom: 10, right: 6 })
  2893. // .backgroundColor(this.themeColor)
  2894. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2895. // .onClick(() => {
  2896. //
  2897. // this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  2898. // })
  2899. // Button('复制', { type: ButtonType.Circle, stateEffect: true })
  2900. // .width('35%')
  2901. // .height(60)
  2902. // .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  2903. // .margin({ top: 10, bottom: 10, right: 6 })
  2904. // .backgroundColor(this.themeColor)
  2905. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2906. // .onClick(() => {
  2907. // this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  2908. // })
  2909. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  2910. .width(45)
  2911. .height(45)
  2912. .fontSize(10)
  2913. .margin({ top: 10, bottom: 10, right: 6 })
  2914. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  2915. .backgroundColor(this.themeColor)
  2916. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2917. .onClick(() => {
  2918. this.showWarnIsDelete()
  2919. })
  2920. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  2921. .width(45)
  2922. .height(45)
  2923. .fontSize(10)
  2924. .margin({ top: 10, bottom: 10, right: 6 })
  2925. .backgroundColor(this.themeColor)
  2926. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2927. .onClick(() => {
  2928. this.selectedFiles = [];
  2929. this.isAllSelected = false
  2930. this.isMultiSelect = false
  2931. })
  2932. }
  2933. .width('100%')
  2934. .justifyContent(FlexAlign.Center)
  2935. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  2936. .opacity(this.isMultiSelect ? 1 : 0)
  2937. .animation({
  2938. duration: 666,
  2939. curve: 'ease-in-out' // 可选动画曲线
  2940. })
  2941. .position({ bottom: 20 }) // 将 Row 固定在底部
  2942. }
  2943. .width('100%')
  2944. .height('100%')
  2945. .alignContent(Alignment.Top)
  2946. }
  2947. .width('100%')
  2948. .height('100%')
  2949. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  2950. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  2951. .backgroundImagePosition(Alignment.Center)
  2952. .backdropBlur(this.blurValue)
  2953. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  2954. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  2955. }
  2956. }
  2957. //字母表索引
  2958. @Builder
  2959. indexBuilder(){
  2960. Column({space: 5}){
  2961. if(this.showZMIndex&&this.enableShowAlphabet){
  2962. if(this.isShowAlphaBet&&!(this.modeType==2&&!this.isCanBack)
  2963. &&!(this.modeType==3&&!this.isCanBack)){
  2964. AlphabetIndexer({arrayValue: this.alphaBet,selected: this.selectAlphaBetIndex})
  2965. .attributeModifier(this.alphaBetStyle)
  2966. .usingPopup(this.isTouchingAlphaBet)
  2967. .onAreaChange((old_value,new_value)=>{
  2968. this.alphabetHeight = new_value.height as number
  2969. })
  2970. .popupPosition({
  2971. x: 40,
  2972. y: this.alphabetHeight / 2
  2973. })
  2974. .onSelect((index: number) => {
  2975. void this.onSelectIndexItem(this.alphaBet[index])
  2976. })
  2977. .onTouch((event: TouchEvent) =>{
  2978. this.showAlphabetIndex()
  2979. if(event.type === TouchType.Up || event.type === TouchType.Cancel){
  2980. this.isTouchingAlphaBet = false
  2981. this.hideAlphabetIndexAfterDelay(1500)
  2982. }else{
  2983. this.isTouchingAlphaBet = true
  2984. }
  2985. })
  2986. .transition(
  2987. TransitionEffect.translate({x: 10})
  2988. .combine(TransitionEffect.opacity(0.1))
  2989. .animation({
  2990. duration: 150,
  2991. curve: Curve.EaseInOut,
  2992. })
  2993. )
  2994. }
  2995. }
  2996. if(this.showFindLocation){
  2997. if(!(this.showZMIndex&&this.enableShowAlphabet)){
  2998. Blank()
  2999. .layoutWeight(1)
  3000. }
  3001. PointLightDefaultButton({
  3002. isSysBol:true,
  3003. pointColor:Color.Gray,
  3004. imageResource:$r('sys.symbol.local_fill'),
  3005. isPx: false,
  3006. builderHeight: 30,
  3007. builderWidth: 30,
  3008. })
  3009. .onClick(() =>{
  3010. void this.locateCurrentSong();
  3011. })
  3012. .clickEffect({level:ClickEffectLevel.LIGHT,scale: 0.5})
  3013. .margin({
  3014. bottom: this.bottomSafeHeight+100,right:10
  3015. })
  3016. }
  3017. }
  3018. .padding({
  3019. bottom: 0
  3020. })
  3021. .margin({right:5})
  3022. .position({x:'92%'})
  3023. .height('100%')
  3024. .justifyContent(FlexAlign.Center)
  3025. }
  3026. async onSelectIndexItem(letter: string) {
  3027. await this.ensureFullListForAlphabetIndex();
  3028. const findTargetIndex = (): number => {
  3029. const songs = this.videoLocalList;
  3030. for (let i = 0; i < songs.length; i++) {
  3031. const song = songs[i];
  3032. let text = this.isShowFileName ? song.fileName :
  3033. (song.type != CommonConstants.TYPE_IS_DIR && song.pyStr) ? song.pyStr : song.name;
  3034. if (this.sortType === 0 || this.sortType == 1) {
  3035. text = song.artist;
  3036. } else if (this.sortType === 2 || this.sortType == 3) {
  3037. text = song.album;
  3038. }
  3039. if (text) {
  3040. const firstPinyin = getFirstLetter(text);
  3041. if (firstPinyin && firstPinyin === letter) {
  3042. return i;
  3043. }
  3044. }
  3045. }
  3046. return -1;
  3047. };
  3048. const targetIndex = findTargetIndex();
  3049. if (targetIndex !== -1) {
  3050. if (this.isGridMusic || this.twoFingerType == 4) {
  3051. this.scroller.scrollToIndex(targetIndex, false);
  3052. } else {
  3053. this.listScroller.scrollToIndex(targetIndex);
  3054. }
  3055. }
  3056. }
  3057. private showAlphabetIndex(): void {
  3058. this.isShowAlphaBet = true;
  3059. if (this.alphaBetHideTimer) {
  3060. clearTimeout(this.alphaBetHideTimer);
  3061. this.alphaBetHideTimer = 0;
  3062. }
  3063. }
  3064. private hideAlphabetIndexAfterDelay(delayMs: number): void {
  3065. if (this.alphaBetHideTimer) {
  3066. clearTimeout(this.alphaBetHideTimer);
  3067. }
  3068. this.alphaBetHideTimer = setTimeout(() => {
  3069. if (!this.isTouchingAlphaBet) {
  3070. this.isShowAlphaBet = false;
  3071. }
  3072. this.alphaBetHideTimer = 0;
  3073. }, delayMs) as number;
  3074. }
  3075. private async ensureFullListForAlphabetIndex(): Promise<void> {
  3076. if (this.isLoadingPage) {
  3077. return;
  3078. }
  3079. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  3080. return;
  3081. }
  3082. if (this.totalCount === 0 || this.videoLocalList.length >= this.totalCount) {
  3083. return;
  3084. }
  3085. if (this.modeType !== 0 && this.modeType !== 1) {
  3086. return;
  3087. }
  3088. this.isLoadingPage = true;
  3089. try {
  3090. const options: PageQueryOptions = {
  3091. pageIndex: 0,
  3092. pageSize: this.totalCount,
  3093. sortType: this.sortType,
  3094. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  3095. isShowFileName: this.isShowFileName
  3096. };
  3097. if (this.modeType === 0) {
  3098. options.parentPath = this.currentPath;
  3099. }
  3100. let result: PageQueryResult;
  3101. if (this.modeType === 0) {
  3102. result = await this.table.queryByParentPathPaged(options);
  3103. if (!this.isSearchMode) {
  3104. const directories: VideoItem[] = await this.loadDirectories(this.currentPath);
  3105. result.items = [...directories, ...result.items];
  3106. result.totalCount += directories.length;
  3107. }
  3108. } else {
  3109. result = await this.table.queryMediaLibraryPaged(options);
  3110. }
  3111. this.videoLocalList = result.items;
  3112. this.dataSource.pushArrayData(this.videoLocalList);
  3113. this.pageCache.clear();
  3114. this.currentPage = 0;
  3115. this.totalCount = result.totalCount;
  3116. this.hasMoreData = false;
  3117. if (this.modeType === 1) {
  3118. this.mediaKuCount = result.totalCount;
  3119. }
  3120. this.setButtonStatus();
  3121. this.setAlphaBet();
  3122. } catch (err) {
  3123. const error = err as Error;
  3124. Logger.warn('heanup LocalMusic', `ensureFullListForAlphabetIndex error: ${error.message}`);
  3125. } finally {
  3126. this.isLoadingPage = false;
  3127. }
  3128. }
  3129. // 找到对应字母表的索引
  3130. findAlphaBetIndex(song: VideoItem):number{
  3131. let text = this.isShowFileName?song.fileName:
  3132. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  3133. if(this.sortType === 0||this.sortType==1){
  3134. text = song.artist
  3135. }else if(this.sortType === 2||this.sortType==3){
  3136. text = song.album
  3137. }
  3138. if(text){
  3139. let firstLetter = getFirstLetter(text)
  3140. for(let i=0;i<this.alphaBet.length;i++){
  3141. if(this.alphaBet[i] === firstLetter){
  3142. return i
  3143. }
  3144. }
  3145. }
  3146. return 0
  3147. }
  3148. async setAlphaBet(){
  3149. if(!this.showZMIndex){
  3150. return
  3151. }
  3152. if (this.modeType === 1 && this.totalCount > this.videoLocalList.length) {
  3153. await this.refreshAlphaBetFromMediaLibrary()
  3154. return
  3155. }
  3156. return new Promise<void>((resolve,reject) => {
  3157. try {
  3158. let songs = this.videoLocalList
  3159. if(songs.length > 40000){
  3160. this.alphaBet = []
  3161. resolve()
  3162. return
  3163. }
  3164. let alphabetSet = new Set<string>();
  3165. for (let song of songs) {
  3166. let text = this.isShowFileName?song.fileName:
  3167. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  3168. if(this.sortType === 0||this.sortType==1){
  3169. text = song.artist
  3170. }else if(this.sortType === 2||this.sortType==3){
  3171. text = song.album
  3172. }
  3173. if(text){
  3174. let firstPinyin = getFirstLetter(text)
  3175. if(!alphabetSet.has(firstPinyin)){
  3176. alphabetSet.add(firstPinyin)
  3177. }
  3178. }
  3179. // const pyStr = song.pyStr
  3180. // if(pyStr){
  3181. // if(!alphabetSet.has(pyStr)){
  3182. // alphabetSet.add(pyStr)
  3183. // }
  3184. // }
  3185. }
  3186. this.alphaBet = Array.from(alphabetSet).sort((a,b)=>{
  3187. if(this.sortType ===4||this.sortType==0||this.sortType==2||this.sortType==6){
  3188. return a.localeCompare(b)
  3189. }else{
  3190. return b.localeCompare(a)
  3191. }
  3192. })
  3193. if(this.videoLocalList.length > 0){
  3194. this.listScroller.scrollToIndex(0)
  3195. this.selectAlphaBetIndex = 0
  3196. }
  3197. resolve()
  3198. }catch (e) {
  3199. console.error('testTag','排序字母表出错',JSON.stringify(e))
  3200. resolve()
  3201. }
  3202. })
  3203. }
  3204. private async refreshAlphaBetFromMediaLibrary(): Promise<void> {
  3205. if (this.totalCount <= 0) {
  3206. return
  3207. }
  3208. if (this.totalCount > 40000) {
  3209. this.alphaBet = []
  3210. return
  3211. }
  3212. const keyword = this.isSearchMode ? this.searchText : ''
  3213. const cacheKey = `${this.modeType}-${this.sortType}-${this.isShowFileName}-${keyword}-${this.totalCount}`
  3214. if (this.alphaBetCacheKey === cacheKey && this.alphaBet.length > 0) {
  3215. return
  3216. }
  3217. const result = await this.table.queryMediaLibraryPaged({
  3218. pageIndex: 0,
  3219. pageSize: this.totalCount,
  3220. sortType: this.sortType,
  3221. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  3222. isShowFileName: this.isShowFileName
  3223. })
  3224. let alphabetSet = new Set<string>()
  3225. for (let song of result.items) {
  3226. let text = this.isShowFileName ? song.fileName :
  3227. (song.type != CommonConstants.TYPE_IS_DIR && song.pyStr) ? song.pyStr : song.name
  3228. if (this.sortType === 0 || this.sortType == 1) {
  3229. text = song.artist
  3230. } else if (this.sortType === 2 || this.sortType == 3) {
  3231. text = song.album
  3232. }
  3233. if (text) {
  3234. let firstPinyin = getFirstLetter(text)
  3235. if (!alphabetSet.has(firstPinyin)) {
  3236. alphabetSet.add(firstPinyin)
  3237. }
  3238. }
  3239. }
  3240. this.alphaBet = Array.from(alphabetSet).sort((a, b) => {
  3241. if (this.sortType === 4 || this.sortType == 0 || this.sortType == 2 || this.sortType == 6) {
  3242. return a.localeCompare(b)
  3243. } else {
  3244. return b.localeCompare(a)
  3245. }
  3246. })
  3247. this.alphaBetCacheKey = cacheKey
  3248. }
  3249. @Builder
  3250. topTitleBar(){
  3251. Column() {
  3252. Row({ space: 15 }) {
  3253. if (!this.isSearchMode ) {
  3254. //左侧滑动按钮
  3255. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3256. SymbolGlyph(this.rightTopImage)
  3257. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3258. }
  3259. .attributeModifier(new ButtonFancyModifier(40, 40))
  3260. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3261. .animation({ duration: 300, curve: Curve.Ease })
  3262. .onClick(() => {
  3263. this.doSwipBack()
  3264. })
  3265. .attributeModifier(new ShadowModifier())
  3266. .zIndex(0)
  3267. }else{
  3268. //左侧搜索返回按钮
  3269. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3270. SymbolGlyph($r('sys.symbol.chevron_left'))
  3271. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3272. }
  3273. .attributeModifier(new ButtonFancyModifier(40, 40))
  3274. .margin({bottom:5})
  3275. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3276. .animation({ duration: 300, curve: Curve.Ease })
  3277. .onClick(() => {
  3278. this.isSearchMode = false
  3279. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  3280. this.searchText = ''
  3281. this.getSortedFiles(this.currentPath)
  3282. return
  3283. }
  3284. this.onSearchInput('')
  3285. })
  3286. .attributeModifier(new ShadowModifier())
  3287. .zIndex(0)
  3288. }
  3289. if (!this.isSearchMode) {
  3290. Text(this.modeType==1?`${this.titleName}(${this.mediaKuCount}首)`:this.titleName)
  3291. .margin({left:3,right:10})
  3292. .fontColor($r('app.color.text_color'))
  3293. .fontSize(this.twoFingerType==3?17:16)
  3294. .maxLines(1)
  3295. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3296. .layoutWeight(1)
  3297. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3298. }
  3299. //搜索框
  3300. Search({ controller: this.searchController,value: this.searchText, placeholder: '搜索标题、艺术家...' })
  3301. .searchButton('搜索',{fontColor:this.themeColor})
  3302. .searchIcon({
  3303. src: $r('sys.media.ohos_ic_public_search_filled')
  3304. })
  3305. .cancelButton({
  3306. style: CancelButtonStyle.CONSTANT,
  3307. icon: {
  3308. src: $r('sys.media.ohos_ic_public_cancel_filled')
  3309. }
  3310. })
  3311. .layoutWeight(1)
  3312. .height(40)
  3313. .maxLength(20)
  3314. .backgroundColor(this.isDarkMode?Color.Black:'#F5F5F5')
  3315. .placeholderColor(Color.Grey)
  3316. .placeholderFont({ size: 14, weight: 400 })
  3317. .textFont({ size: 14, weight: 400 })
  3318. .onSubmit((value: string) => {
  3319. console.log('onecold onSubmit ='+value)
  3320. this.searchController.stopEditing()
  3321. if(this.modeType==0){
  3322. this.modeType =1//如果是首页 切换到媒体库搜索
  3323. }
  3324. this.onSearchInput(this.searchText);
  3325. })
  3326. .onChange((value: string) => {
  3327. console.log('onecold onChange ='+value)
  3328. if(this.modeType==0){
  3329. this.modeType =1//如果是首页 切换到媒体库搜索
  3330. }
  3331. this.onSearchInput(value);
  3332. })
  3333. .visibility(this.isSearchMode?Visibility.Visible:Visibility.None)
  3334. .animation({ duration: 300, curve: Curve.Ease })
  3335. //搜索按钮
  3336. if (!this.isSearchMode) {
  3337. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3338. SymbolGlyph($r('sys.symbol.magnifyingglass'))
  3339. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3340. }
  3341. .attributeModifier(new ButtonFancyModifier(40, 40))
  3342. .animation({ duration: 300, curve: Curve.Ease })
  3343. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3344. .attributeModifier(new ShadowModifier())
  3345. .zIndex(0)
  3346. .onClick(()=>{
  3347. this.isSearchMode = true
  3348. })
  3349. //排序按钮
  3350. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3351. SymbolGlyph($r('sys.symbol.list_number'))
  3352. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3353. }
  3354. .attributeModifier(new ButtonFancyModifier(40, 40))
  3355. .animation({ duration: 300, curve: Curve.Ease })
  3356. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3357. .bindMenu((this.modeType==2&&!this.isCanBack)||(this.modeType==3&&!this.isCanBack)
  3358. ?this.SortMenuForArtistAblumBuilder:this.SortMenuBuilder)
  3359. .attributeModifier(new ShadowModifier())
  3360. .zIndex(0)
  3361. //添加按钮
  3362. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3363. SymbolGlyph($r('sys.symbol.plus'))
  3364. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3365. }
  3366. .attributeModifier(new ButtonFancyModifier(40, 40))
  3367. .animation({ duration: 300, curve: Curve.Ease })
  3368. .visibility(this.modeType==0||this.modeType==1?Visibility.Visible:Visibility.None)
  3369. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3370. .bindSheet($$this.showAddSheet, this.addSheet(), {
  3371. height: SheetSize.FIT_CONTENT,
  3372. dragBar: true,
  3373. showClose: true,
  3374. preferType: SheetType.CENTER ,
  3375. title: {
  3376. title: '导入音乐'
  3377. }
  3378. })
  3379. .onClick(() => {
  3380. this.showAddSheet = !this.showAddSheet;
  3381. })
  3382. .attributeModifier(new ShadowModifier())
  3383. .zIndex(0)
  3384. }
  3385. }
  3386. }
  3387. .padding({ top: this.topSafeHeight+10, left: 10, right: 10 })
  3388. .width('100%')
  3389. .visibility(this.isShowTitleBar?Visibility.Visible:
  3390. this.autoHideTitle?Visibility.None:Visibility.Visible)
  3391. .animation({
  3392. duration: 500,
  3393. curve: Curve.Friction // 可选动画曲线
  3394. })
  3395. }
  3396. @Builder
  3397. addSheet() {
  3398. Scroll() {
  3399. Column() {
  3400. Column() {
  3401. Row() {
  3402. SymbolGlyph($r('sys.symbol.info_circle'))
  3403. .fontSize(22)
  3404. .fontColor([this.themeColor])
  3405. .alignSelf(ItemAlign.Center)
  3406. .margin({ left: 8 })
  3407. Text('导入音乐复制到DownLoad目录')
  3408. .margin({ left: 8 })
  3409. .fontSize(14)
  3410. .fontColor($r('app.color.text_color'))
  3411. .fontWeight(480)
  3412. .layoutWeight(1)
  3413. Toggle({ type: ToggleType.Switch, isOn: this.isCopyFileToDownLoad })
  3414. .selectedColor(this.themeColor)
  3415. .switchPointColor(Color.White)
  3416. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  3417. .margin({ right: 2 })
  3418. .onChange((checked: boolean) => {
  3419. this.isCopyFileToDownLoad = checked;
  3420. PreferencesUtil.put(SettingPage.IS_COPYFILE_TO_DOWNLOAD, this.isCopyFileToDownLoad)
  3421. })
  3422. .width(50)
  3423. .height(30);
  3424. }
  3425. .height(72)
  3426. .padding({ left:8,right:8 })
  3427. }
  3428. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3429. .backgroundColor($r('app.color.start_window_background'))
  3430. .borderRadius(15)
  3431. .width('85%')
  3432. .margin({
  3433. top: 10,
  3434. bottom: 10
  3435. })
  3436. .padding(0)
  3437. .border({
  3438. color: Color.White,
  3439. width: 1.8
  3440. })
  3441. Menu() {
  3442. MenuItem({
  3443. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder_badge_plus')),
  3444. content: "新建文件夹"
  3445. })
  3446. .backgroundColor($r('app.color.silvery'))
  3447. .border({
  3448. width: { bottom: 1 },
  3449. color: '#12ec5c87'
  3450. })
  3451. .margin(10)
  3452. .height(60)
  3453. .padding({left:15,right:15})
  3454. .onClick(async () => {
  3455. this.showMkDialog()
  3456. this.showAddSheet = !this.showAddSheet
  3457. })
  3458. MenuItem({
  3459. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder')),
  3460. content: $r('app.string.import_from_files')
  3461. })
  3462. .padding({left:15,right:15})
  3463. .backgroundColor($r('app.color.silvery'))
  3464. .border({
  3465. width: { bottom: 1 },
  3466. color: '#12ec5c87'
  3467. })
  3468. .margin(10)
  3469. .height(60)
  3470. .onClick(async () => {
  3471. this.callFilePickerSelectFile()
  3472. this.showAddSheet = !this.showAddSheet
  3473. })
  3474. MenuItem({
  3475. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square')),
  3476. content: '全选导入'
  3477. // content: '从下载文件夹导入(路径:Download/' +
  3478. // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
  3479. })
  3480. .padding({left:15,right:15})
  3481. .backgroundColor($r('app.color.silvery'))
  3482. .border({
  3483. width: { bottom: 1 },
  3484. color: '#12ec5c87'
  3485. })
  3486. .margin(10)
  3487. .height(60)
  3488. .onClick(async () => {
  3489. this.goSelectMusic()
  3490. this.showAddSheet = !this.showAddSheet
  3491. })
  3492. MenuItem({
  3493. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.save')),
  3494. content: '自动导入教程'
  3495. })
  3496. .padding({left:15,right:15})
  3497. .backgroundColor($r('app.color.silvery'))
  3498. .border({
  3499. width: { bottom: 1 },
  3500. color: '#12ec5c87'
  3501. })
  3502. .margin(10)
  3503. .height(60)
  3504. .onClick(async () => {
  3505. this.showTips()
  3506. this.showAddSheet = !this.showAddSheet
  3507. })
  3508. MenuItem({
  3509. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.questionmark_circle')),
  3510. content: '导入疑问'
  3511. })
  3512. .height(60)
  3513. .padding({left:15,right:15})
  3514. .backgroundColor($r('app.color.silvery'))
  3515. .border({
  3516. width: { bottom: 1 },
  3517. color: '#12ec5c87'
  3518. })
  3519. .margin(10)
  3520. .onClick(async () => {
  3521. this.showProblomTips()
  3522. this.showAddSheet = !this.showAddSheet
  3523. })
  3524. }.attributeModifier(new MenuModifier())
  3525. .margin({bottom:30})
  3526. .width('90%')
  3527. .borderRadius(15)
  3528. }
  3529. .layoutWeight(1)
  3530. }
  3531. }
  3532. async showProblomTips() {
  3533. try {
  3534. this.getUIContext().getPromptAction().showDialog({
  3535. title: '导入疑问',
  3536. message:'为什么有些歌曲导入成功后,内嵌标签或者其他功能不能用?:\n\n1、由于鸿蒙系统的安全策略,文件权限不够,请将文件移动到Download/天天静听目录下。' +
  3537. '这样内嵌标签功能就没有权限问题。\n\n2、导入可以也选择不复制,这样可以省略空间。\n\n',
  3538. buttons: [
  3539. {
  3540. text: '知道了',
  3541. color: '#000000'
  3542. },
  3543. ]
  3544. }, (err, data) => {
  3545. if (err) {
  3546. console.error('showDialog err: ' + err);
  3547. return;
  3548. }
  3549. console.info('showDialog success callback, click button: ' + data.index);
  3550. });
  3551. } catch (error) {
  3552. let message = (error as BusinessError).message;
  3553. let code = (error as BusinessError).code;
  3554. console.error(`showDialog args error code is ${code}, message is ${message}`);
  3555. };
  3556. }
  3557. @Builder
  3558. TagsContentCoverBuilder() {
  3559. Scroll() {
  3560. Column() {
  3561. TagsContentCover(
  3562. {
  3563. selectedFiles:this.selectedFiles,
  3564. isOneKeyTags:this.isOneKeyTags,
  3565. onSeePath:(path:string)=>{
  3566. this.modeType = 0
  3567. this.deleteCache(path)
  3568. this.getSortedFiles(path)
  3569. },
  3570. onTagsResult:(result: boolean,deleteCache_path?:string)=>{
  3571. this.isMultiSelect = false
  3572. if(result){//如果嵌入成功,更新数据
  3573. this.listRefreshKey++
  3574. setTimeout(()=>{
  3575. this.doUpdateData()
  3576. },500)
  3577. }
  3578. console.info('onecold onTagsResult deleteCache_path =' +deleteCache_path)
  3579. if(deleteCache_path){
  3580. this.deleteCache(deleteCache_path)
  3581. }
  3582. }
  3583. }
  3584. )
  3585. }
  3586. }
  3587. .width('100%')
  3588. .height('100%')
  3589. }
  3590. @Builder
  3591. FixMessyViewBuilder() {
  3592. Scroll() {
  3593. Column() {
  3594. FixMessyView(
  3595. {
  3596. selectedFiles:this.selectedFiles,
  3597. isFixMessy:this.isFixMessy,
  3598. onFixResult:(result: boolean)=>{
  3599. this.isMultiSelect = false
  3600. if(result){//如果嵌入成功,更新数据
  3601. this.deleteCache(this.currentPath)
  3602. this.doUpdateData()
  3603. }
  3604. }
  3605. }
  3606. )
  3607. }
  3608. }
  3609. .width('100%')
  3610. .height('100%')
  3611. }
  3612. //剪辑音频
  3613. @Builder
  3614. EditAudioBuilder(item:VideoItem) {
  3615. Scroll() {
  3616. Column() {
  3617. EditAudio(
  3618. {
  3619. mVideoItem:item,
  3620. currentPath:this.currentPath,
  3621. videoUrl:this.videoUrl,
  3622. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3623. currentTime:this.currentTime,
  3624. progressValue:this.progressValue,
  3625. onBack:()=>{
  3626. this.isEditAudio = !this.isEditAudio
  3627. },
  3628. onSeeOutputPath:(outPutPath:string)=>{
  3629. this.isEditAudio = !this.isEditAudio
  3630. this.longItemFilePath = ''
  3631. this.modeType = 0
  3632. this.isShowFileName = true
  3633. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3634. },
  3635. onPlayOrPause:()=>{
  3636. if(this.videoUrl==item.filePath){
  3637. this.playOrPause()
  3638. }else{//如果不是当前播放的,则播放该文件
  3639. this.videoUrl==item.filePath
  3640. this.doPlay(item,0,false,true)
  3641. }
  3642. },
  3643. onSliderChange:(value:number)=>{
  3644. if(this.videoUrl!=item.filePath){
  3645. this.videoUrl==item.filePath
  3646. return
  3647. }
  3648. this.isSeekTo = true;
  3649. this.mDestroyPage = false;
  3650. this.showLoadIng();
  3651. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  3652. let seekValue = value * (this.getActiveDuration() / 100);
  3653. this.seekTo(seekValue + "");
  3654. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  3655. this.isSeekTo = false;
  3656. },
  3657. onResult:(result: boolean,outPath:string)=>{
  3658. if(result){//如果剪辑成功,更新数据
  3659. this.doUpdateData()
  3660. }else{
  3661. ToastUtil.showToast('剪辑失败')
  3662. }
  3663. }
  3664. }
  3665. )
  3666. }
  3667. }
  3668. .width('100%')
  3669. .height('100%')
  3670. }
  3671. //提取伴奏
  3672. @Builder
  3673. ConverterBuilder(item:VideoItem) {
  3674. Scroll() {
  3675. Column() {
  3676. AudioFormatConverter(
  3677. {
  3678. mVideoItem:item,
  3679. videoUrl:this.videoUrl,
  3680. currentPath:this.currentPath,
  3681. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3682. currentTime:this.currentTime,
  3683. progressValue:this.progressValue,
  3684. onBack:()=>{
  3685. this.isConverter = !this.isConverter
  3686. this.longItemFilePath = ''
  3687. },
  3688. onPlayOrPause:()=>{
  3689. if(this.videoUrl==item.filePath){
  3690. this.playOrPause()
  3691. }else{//如果不是当前播放的,则播放该文件
  3692. this.videoUrl==item.filePath
  3693. this.doPlay(item,0,false,true)
  3694. }
  3695. },
  3696. onSeeOutputPath:(outPutPath:string)=>{
  3697. this.isConverter = !this.isConverter
  3698. this.longItemFilePath = ''
  3699. this.modeType = 0
  3700. this.isShowFileName = true
  3701. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3702. },
  3703. onSliderChange:(value:number)=>{
  3704. if(this.videoUrl!=item.filePath){
  3705. this.videoUrl==item.filePath
  3706. return
  3707. }
  3708. this.isSeekTo = true;
  3709. this.mDestroyPage = false;
  3710. this.showLoadIng();
  3711. let seekValue = value * (this.getActiveDuration() / 100);
  3712. this.seekTo(seekValue + "");
  3713. this.isSeekTo = false;
  3714. },
  3715. onResult:(result: boolean,outPath:string)=>{
  3716. if(result){//如果成功,更新数据
  3717. this.doUpdateData()
  3718. }else{
  3719. ToastUtil.showToast('格式转化失败')
  3720. }
  3721. }
  3722. }
  3723. )
  3724. }
  3725. }
  3726. .width('100%')
  3727. .height('100%')
  3728. }
  3729. //提取伴奏
  3730. @Builder
  3731. ExtractAccBuilder(item:VideoItem) {
  3732. Scroll() {
  3733. Column() {
  3734. ExtractAccompaniment(
  3735. {
  3736. mVideoItem:item,
  3737. currentPath:this.currentPath,
  3738. videoUrl:this.videoUrl,
  3739. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3740. currentTime:this.currentTime,
  3741. progressValue:this.progressValue,
  3742. onBack:()=>{
  3743. this.isExtractAcc = !this.isExtractAcc
  3744. this.longItemFilePath = ''
  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. onSeeOutputPath:(outPutPath:string)=>{
  3755. this.isExtractAcc = !this.isExtractAcc
  3756. this.longItemFilePath = ''
  3757. this.modeType = 0
  3758. this.isShowFileName = true
  3759. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3760. },
  3761. onSliderChange:(value:number)=>{
  3762. if(this.videoUrl!=item.filePath){
  3763. this.videoUrl==item.filePath
  3764. return
  3765. }
  3766. this.isSeekTo = true;
  3767. this.mDestroyPage = false;
  3768. this.showLoadIng();
  3769. let seekValue = value * (this.getActiveDuration() / 100);
  3770. this.seekTo(seekValue + "");
  3771. this.isSeekTo = false;
  3772. },
  3773. onResult:(result: boolean,outPath:string)=>{
  3774. if(result){//如果成功,更新数据
  3775. this.doUpdateData()
  3776. }else{
  3777. ToastUtil.showToast('提取伴奏失败')
  3778. }
  3779. }
  3780. }
  3781. )
  3782. }
  3783. }
  3784. .width('100%')
  3785. .height('100%')
  3786. }
  3787. //AI人声分离
  3788. @Builder
  3789. AiBuilder(item:VideoItem) {
  3790. Scroll() {
  3791. Column() {
  3792. AIVoiceSeparation(
  3793. {
  3794. mVideoItem:item,
  3795. videoUrl:this.videoUrl,
  3796. currentPath:this.currentPath,
  3797. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3798. currentTime:this.currentTime,
  3799. progressValue:this.progressValue,
  3800. onBack:()=>{
  3801. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  3802. this.longItemFilePath = ''
  3803. },
  3804. onPlayOrPause:()=>{
  3805. if(this.videoUrl==item.filePath||this.isPlaying){
  3806. this.playOrPause()
  3807. }else{//如果不是当前播放的,则播放该文件
  3808. this.videoUrl==item.filePath
  3809. this.doPlay(item,0,false,true)
  3810. }
  3811. },
  3812. onPlayPath:(path:string)=>{
  3813. this.videoUrl==path
  3814. const itemP = Utility.getItemByFilePath(this.videoLocalList,path)
  3815. if(itemP)
  3816. this.doPlay(itemP,0,false,true)
  3817. },
  3818. onSeeOutputPath:(outPutPath:string)=>{
  3819. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  3820. this.longItemFilePath = ''
  3821. this.modeType = 0
  3822. this.isShowFileName = true
  3823. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3824. },
  3825. onSliderChange:(value:number)=>{
  3826. if(this.videoUrl!=item.filePath){
  3827. this.videoUrl==item.filePath
  3828. return
  3829. }
  3830. this.isSeekTo = true;
  3831. this.mDestroyPage = false;
  3832. this.showLoadIng();
  3833. let seekValue = value * (this.getActiveDuration() / 100);
  3834. this.seekTo(seekValue + "");
  3835. this.isSeekTo = false;
  3836. },
  3837. onResult:(result: boolean,outPath:string)=>{
  3838. if(result){//如果成功,更新数据
  3839. this.doUpdateData()
  3840. }else{
  3841. ToastUtil.showToast('Ai人声分离失败')
  3842. }
  3843. }
  3844. }
  3845. )
  3846. }
  3847. }
  3848. .width('100%')
  3849. .height('100%')
  3850. }
  3851. //变速变调
  3852. @Builder
  3853. ChangeToneBuilder(item:VideoItem) {
  3854. Scroll() {
  3855. Column() {
  3856. ChangeTone(
  3857. {
  3858. mVideoItem:item,
  3859. currentPath:this.currentPath,
  3860. videoUrl:this.videoUrl,
  3861. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3862. currentTime:this.currentTime,
  3863. progressValue:this.progressValue,
  3864. onBack:()=>{
  3865. this.isChangeTone = !this.isChangeTone
  3866. this.longItemFilePath = ''
  3867. },
  3868. onPlayOrPause:()=>{
  3869. if(this.videoUrl==item.filePath){
  3870. this.playOrPause()
  3871. }else{//如果不是当前播放的,则播放该文件
  3872. this.videoUrl==item.filePath
  3873. this.doPlay(item,0,false,true)
  3874. }
  3875. },
  3876. onSeeOutputPath:(outPutPath:string)=>{
  3877. this.isChangeTone = !this.isChangeTone
  3878. this.longItemFilePath = ''
  3879. this.modeType = 0
  3880. this.isShowFileName = true
  3881. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3882. },
  3883. onSliderChange:(value:number)=>{
  3884. if(this.videoUrl!=item.filePath){
  3885. this.videoUrl==item.filePath
  3886. return
  3887. }
  3888. this.isSeekTo = true;
  3889. this.mDestroyPage = false;
  3890. this.showLoadIng();
  3891. let seekValue = value * (this.getActiveDuration() / 100);
  3892. this.seekTo(seekValue + "");
  3893. this.isSeekTo = false;
  3894. },
  3895. onResult:(result: boolean,outPath:string)=>{
  3896. if(result){//如果成功,更新数据
  3897. this.doUpdateData()
  3898. }else{
  3899. ToastUtil.showToast('变速变调失败')
  3900. }
  3901. }
  3902. }
  3903. )
  3904. }
  3905. }
  3906. .width('100%')
  3907. .height('100%')
  3908. }
  3909. //提取视频中的音频
  3910. @Builder
  3911. extractAudioFromVideoBuilder(item:VideoItem) {
  3912. Scroll() {
  3913. Column() {
  3914. ExtractAudioFromVideo(
  3915. {
  3916. mVideoItem:item,
  3917. currentPath:this.currentPath,
  3918. videoUrl:this.videoUrl,
  3919. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3920. currentTime:this.currentTime,
  3921. progressValue:this.progressValue,
  3922. onBack:()=>{
  3923. this.isExtractAudio = !this.isExtractAudio
  3924. this.longItemFilePath = ''
  3925. },
  3926. onPlayOrPause:()=>{
  3927. if(this.videoUrl==item.filePath){
  3928. this.playOrPause()
  3929. }else{//如果不是当前播放的,则播放该文件
  3930. this.videoUrl==item.filePath
  3931. this.doPlay(item,0,false,true)
  3932. }
  3933. },
  3934. onSeeOutputPath:(outPutPath:string)=>{
  3935. this.isExtractAudio = !this.isExtractAudio
  3936. this.longItemFilePath = ''
  3937. this.modeType = 0
  3938. this.isShowFileName = true
  3939. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3940. },
  3941. onSliderChange:(value:number)=>{
  3942. if(this.videoUrl!=item.filePath){
  3943. this.videoUrl==item.filePath
  3944. return
  3945. }
  3946. this.isSeekTo = true;
  3947. this.mDestroyPage = false;
  3948. this.showLoadIng();
  3949. let seekValue = value * (this.getActiveDuration() / 100);
  3950. this.seekTo(seekValue + "");
  3951. this.isSeekTo = false;
  3952. },
  3953. onResult:(result: boolean,outPath:string)=>{
  3954. if(result){//如果成功,更新数据
  3955. this.doUpdateData()
  3956. }else{
  3957. ToastUtil.showToast('提取音频失败')
  3958. }
  3959. }
  3960. }
  3961. )
  3962. }
  3963. }
  3964. .width('100%')
  3965. .height('100%')
  3966. }
  3967. //合并音频
  3968. @Builder
  3969. MergeAudioBuilder() {
  3970. Scroll() {
  3971. Column() {
  3972. MergeAudio(
  3973. {
  3974. videoUrl:this.videoUrl,
  3975. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3976. currentPath:this.currentPath,
  3977. selectedFiles:this.selectedFiles,
  3978. currentTime:this.currentTime,
  3979. progressValue:this.progressValue,
  3980. onBack:()=>{
  3981. this.isMergeAudio = !this.isMergeAudio
  3982. this.longItemFilePath = ''
  3983. },
  3984. // onPlayPath:(path:string)=>{
  3985. // if(this.videoUrl==item.filePath){
  3986. // this.playOrPause()
  3987. // }else{//如果不是当前播放的,则播放该文件
  3988. // this.videoUrl==item.filePath
  3989. // this.doPlay(item,0,false,true)
  3990. // }
  3991. //
  3992. // },
  3993. onSeeOutputPath:(outPutPath:string)=>{
  3994. this.isMergeAudio = !this.isMergeAudio
  3995. this.longItemFilePath = ''
  3996. this.modeType = 0
  3997. this.isShowFileName = true
  3998. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3999. },
  4000. onResult:(result: boolean,outPath:string)=>{
  4001. if(result){//如果成功,更新数据
  4002. this.doUpdateData()
  4003. }else{
  4004. if(this.selectedFiles.length>=3){
  4005. ToastUtil.showToast('合并数量太多导致失败')
  4006. }else{
  4007. ToastUtil.showToast('合并失败')
  4008. }
  4009. }
  4010. }
  4011. }
  4012. )
  4013. }
  4014. }
  4015. .width('100%')
  4016. .height('100%')
  4017. }
  4018. asyncCurrentPathData() {
  4019. if (this.modeType == 0) {
  4020. workerInstance.postMessage({
  4021. code: 1,
  4022. data1: this.context,
  4023. data2: this.currentPath,
  4024. data3: this.lockPath,
  4025. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  4026. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  4027. });
  4028. }
  4029. }
  4030. // 处理文件选择的函数
  4031. handleFileSelection(item: VideoItem, checked: boolean) {
  4032. if (checked) {
  4033. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  4034. this.selectedFiles.push(item);
  4035. }
  4036. } else {
  4037. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  4038. if (index > -1) {
  4039. this.selectedFiles.splice(index, 1);
  4040. }
  4041. }
  4042. }
  4043. private deleteComponentId: number = 0
  4044. //多选删除文件
  4045. showWarnIsDelete(){
  4046. this.getUIContext().getPromptAction().openCustomDialog({
  4047. builder: () => {
  4048. this.deleteComptentBuilder()
  4049. },
  4050. isModal:true,
  4051. showInSubWindow:false,
  4052. maskColor: Color.Transparent,
  4053. dialogTransition: // 设置弹窗内容显示的过渡效果
  4054. TransitionEffect.translate({ x: 0, y: 290, z: 0 })
  4055. .animation({ duration: 600, curve: Curve.Smooth }),
  4056. maskTransition: // 设置蒙层显示的过渡效果
  4057. TransitionEffect.opacity(0)
  4058. .animation({ duration: 600, curve: Curve.Smooth })
  4059. }).then((dialogId: number) => {
  4060. this.deleteComponentId = dialogId
  4061. })
  4062. .catch((error: BusinessError) => {
  4063. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  4064. })
  4065. }
  4066. @Builder
  4067. deleteComptentBuilder(){
  4068. DeleteComptent({
  4069. selectedFiles:this.selectedFiles,
  4070. onCancel:()=>{
  4071. this.isMultiSelect = false
  4072. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  4073. },
  4074. onDeleteResult:(result: boolean)=>{
  4075. this.isMultiSelect = false
  4076. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  4077. if(result){//如果删除成功,更新数据
  4078. this.selectedFiles = [];
  4079. this.isAllSelected = false
  4080. this.cache.delete(this.currentPath);
  4081. this.getSortedFiles(this.currentPath, true);
  4082. }
  4083. }
  4084. })
  4085. }
  4086. //多选移动文件
  4087. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  4088. Logger.info('onecold showCutDialogForMultipleFiles')
  4089. let mList: Array<string> = []
  4090. let rPath = this.rootPath
  4091. if (isCurrent) {
  4092. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  4093. rPath = this.currentPath
  4094. } else {
  4095. mList = Utility.getNameList(this.dirList);
  4096. rPath = this.rootPath
  4097. }
  4098. let dataBean = new BubbleBean();
  4099. dataBean.data = mList;
  4100. dataBean.color = this.themeColor
  4101. dataBean.onItemClick = (i) => {
  4102. const newDirPath = rPath + '/' + mList[i];
  4103. // Logger.info('newDirPath = ' + newDirPath)
  4104. this.selectedFiles.forEach((item) => {
  4105. const newPath = newDirPath + '/' + item.fileName;
  4106. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  4107. ToastUtil.showToast('移动成功');
  4108. this.table.deleteData(item, () => {
  4109. this.cache.delete(this.currentPath); // 删除原路径缓存
  4110. this.cache.delete(newDirPath); // 删除目标路径缓存
  4111. this.getSortedFiles(this.currentPath, true);
  4112. });
  4113. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  4114. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  4115. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  4116. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  4117. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  4118. this.table.insert(newItem, (id: number) => {
  4119. //加入数据库
  4120. });
  4121. }
  4122. }).catch((error: Error) => {
  4123. console.error(error.message);
  4124. });
  4125. });
  4126. this.isMultiSelect = false
  4127. this.selectedFiles = [];
  4128. this.isAllSelected = false
  4129. XPopup.dismissTop();
  4130. };
  4131. let pup: XPopup
  4132. if (this.isDarkMode) {
  4133. pup = XPopup.Builder()
  4134. .setPopupPosition(PopupPosition.TOP)
  4135. .atView(viewId)
  4136. .setBackgroundColor(Color.Black)
  4137. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4138. .show();
  4139. } else {
  4140. pup = XPopup.Builder()
  4141. .setPopupPosition(PopupPosition.TOP)
  4142. .atView(viewId)
  4143. .setBackgroundColor(Color.White)
  4144. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4145. .show();
  4146. }
  4147. }
  4148. /**
  4149. * 加载所有歌单
  4150. */
  4151. async loadAllPlaylists() {
  4152. try {
  4153. this.allPlaylists = await this.playlistTable?.queryAllPlaylists()!
  4154. LogUtil.info('heanup Loaded playlists: ' + this.allPlaylists.length)
  4155. } catch (error) {
  4156. LogUtil.error('heaunp Failed to load playlists: ' + error.message)
  4157. }
  4158. }
  4159. /**
  4160. * 显示添加到歌单对话框
  4161. */
  4162. async openAddToPlaylistDialog(items: VideoItem | VideoItem[]) {
  4163. const songs = Array.isArray(items) ? items : [items]
  4164. const musicItems = songs.filter(song => song.type !== CommonConstants.TYPE_IS_DIR)
  4165. if (musicItems.length === 0) {
  4166. ToastUtil.showToast('请选择要添加的歌曲')
  4167. return
  4168. }
  4169. // 加载最新的歌单列表
  4170. await this.loadAllPlaylists()
  4171. showAddToPlaylistDialog(
  4172. musicItems,
  4173. this.allPlaylists,
  4174. async (playlistId: string) => {
  4175. // 添加歌曲到歌单
  4176. const success = await this.playlistTable?.addSongsToPlaylist(playlistId,
  4177. musicItems.map(song => song.filePath))
  4178. if (success) {
  4179. const count = musicItems.length
  4180. ToastUtil.showToast(count > 1 ? `已添加 ${count} 首歌曲` : '已添加到歌单')
  4181. // 重新加载歌单列表
  4182. await this.loadAllPlaylists()
  4183. } else {
  4184. ToastUtil.showToast(musicItems.length > 1 ? '选中的歌曲已在该歌单中' : '歌曲已在该歌单中')
  4185. }
  4186. this.longItemFilePath = ''
  4187. if (this.isMultiSelect) {
  4188. this.isMultiSelect = false
  4189. this.isAllSelected = false
  4190. this.selectedFiles = []
  4191. }
  4192. },
  4193. () => {
  4194. LogUtil.info('取消添加到歌单')
  4195. },
  4196. () => {
  4197. // 创建新歌单
  4198. showCreatePlaylistDialog(
  4199. async (name: string, description: string, coverPath?: string) => {
  4200. const success = await this.playlistTable?.createPlaylist(name, description, coverPath)
  4201. if (success) {
  4202. ToastUtil.showToast('歌单创建成功')
  4203. // 重新加载歌单列表并打开添加对话框
  4204. await this.loadAllPlaylists()
  4205. await this.openAddToPlaylistDialog(musicItems)
  4206. } else {
  4207. ToastUtil.showToast('歌单创建失败')
  4208. }
  4209. },
  4210. () => {
  4211. // 取消创建歌单
  4212. }
  4213. )
  4214. }
  4215. )
  4216. }
  4217. doFav(item: VideoItem) {
  4218. LogUtil.info('onecold doFav isFav=' + item.isFav)
  4219. let isFav = 0
  4220. if (Utility.getIsFav(this.favList, item)) {
  4221. isFav = 0
  4222. } else {
  4223. isFav = 1
  4224. }
  4225. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  4226. if (result) {
  4227. if (isFav === 1) {
  4228. ToastUtil.showToast('收藏成功');
  4229. } else {
  4230. ToastUtil.showToast('取消收藏成功');
  4231. }
  4232. this.deleteCache(this.currentPath)
  4233. this.getFavList(false)
  4234. if (this.modeType === 0 && !this.isFavMusic) {
  4235. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  4236. this.getSortedFiles(this.currentPath)
  4237. }
  4238. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  4239. workerInstance.postMessage({ code: 3, data: this.context });
  4240. workerInstance.postMessage({ code: 4, data: this.context });
  4241. }
  4242. })
  4243. }
  4244. //多选复制文件
  4245. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  4246. console.log('onecold showCopyDialogForMultipleFiles');
  4247. let mList: Array<string> = []
  4248. let rPath = this.rootPath
  4249. if (isCurrent) {
  4250. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  4251. rPath = this.currentPath
  4252. } else {
  4253. mList = Utility.getNameList(this.dirList);
  4254. rPath = this.rootPath
  4255. }
  4256. let dataBean = new BubbleBean();
  4257. dataBean.data = mList;
  4258. dataBean.isCopy = true
  4259. dataBean.color = this.themeColor
  4260. dataBean.onItemClick = (i) => {
  4261. const newDirPath = rPath + '/' + mList[i];
  4262. // Logger.info('newDirPath = ' + newDirPath)
  4263. this.selectedFiles.forEach((item) => {
  4264. const newPath = newDirPath + '/' + item.fileName;
  4265. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  4266. ToastUtil.showToast('复制成功');
  4267. this.cache.delete(newDirPath); // 删除目标路径缓存
  4268. this.getSortedFiles(this.currentPath);
  4269. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  4270. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  4271. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  4272. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  4273. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  4274. this.table.insert(newItem, (id: number) => {
  4275. //加入数据库
  4276. });
  4277. }
  4278. }).catch((error: Error) => {
  4279. console.error(error.message);
  4280. });
  4281. });
  4282. this.isMultiSelect = false
  4283. this.selectedFiles = [];
  4284. this.isAllSelected = false
  4285. XPopup.dismissTop();
  4286. };
  4287. let pup: XPopup
  4288. if (this.isDarkMode) {
  4289. pup = XPopup.Builder()
  4290. .setPopupPosition(PopupPosition.TOP)
  4291. .atView(viewId)
  4292. .setBackgroundColor(Color.Black)
  4293. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4294. .show();
  4295. } else {
  4296. pup = XPopup.Builder()
  4297. .setPopupPosition(PopupPosition.TOP)
  4298. .atView(viewId)
  4299. .setBackgroundColor(Color.White)
  4300. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4301. .show();
  4302. }
  4303. }
  4304. @Builder
  4305. private DirItem(item: VideoItem, index?: number) {
  4306. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  4307. Row() {
  4308. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
  4309. $r('app.media.music_group'))
  4310. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4311. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4312. .fillColor(this.themeColor)// .fontSize(33)
  4313. .alt($r('app.media.music_group'))
  4314. .borderRadius(this.isCoverRectangle?9:'100%')
  4315. .clip(true)
  4316. .shadow({
  4317. radius: 2,
  4318. type: ShadowType.BLUR,
  4319. color: 'on_primary'
  4320. })
  4321. .sourceSize({width:38, height:38})
  4322. .margin({ left: 20, top: 8, bottom: 8 })
  4323. Column() {
  4324. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  4325. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4326. .maxLines(1)// .width('88%')
  4327. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4328. .animation({
  4329. duration: 555,
  4330. curve: 'ease-in-out',
  4331. })
  4332. .transition({
  4333. type: TransitionType.Insert,
  4334. opacity: 0,
  4335. translate: { x: 160 }
  4336. })
  4337. .margin({ left: 10, right: 20 })
  4338. .fontColor($r('app.color.text_color'))
  4339. Row() {
  4340. Text(`${this.getArtistSongCount(item.name)}首`)
  4341. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4342. .padding({ top: 8 })
  4343. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  4344. .fontColor($r('app.color.text_color'))
  4345. .margin({ left: 10 })
  4346. Text(`${this.getAlbumSongCount(item.name)}首`)
  4347. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4348. .padding({ top: 8 })
  4349. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  4350. .fontColor($r('app.color.text_color'))
  4351. .margin({ left: 10 })
  4352. Blank()
  4353. }
  4354. }
  4355. .height('100%')
  4356. .layoutWeight(1)
  4357. .justifyContent(FlexAlign.Center)
  4358. .alignItems(HorizontalAlign.Start)
  4359. Blank()
  4360. Image($r('app.media.arrow_right'))
  4361. .height(25)
  4362. .alignSelf(ItemAlign.Center)
  4363. .id(item.filePath)
  4364. .visibility(this.isShowAlphaBet?Visibility.None:Visibility.Visible)
  4365. .animation({ duration: 300, curve: Curve.Ease })
  4366. }
  4367. }
  4368. .backgroundColor(Color.Transparent)
  4369. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  4370. .width('98%')
  4371. .reuseId('dir_item')
  4372. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  4373. .opacity(this.opacityItem) // 绑定透明度
  4374. }
  4375. isShowDir(dirName: string) {
  4376. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  4377. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  4378. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  4379. if (dirName === undefined) {
  4380. return true
  4381. }
  4382. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  4383. return this.isShowSimi
  4384. }
  4385. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  4386. return this.isShowFAV
  4387. }
  4388. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  4389. return this.isShowHistory
  4390. }
  4391. return true
  4392. }
  4393. @State opacityItem: number = 1; // 控制透明度的状态变量
  4394. @Builder
  4395. private MusicItem(item: VideoItem, index?: number) {
  4396. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  4397. Row() {
  4398. Stack() {
  4399. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  4400. .fillColor(this.themeColor)
  4401. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4402. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4403. .alt($r('app.media.alt'))
  4404. .borderRadius(this.isCoverRectangle?9:'100%')
  4405. .clip(true)
  4406. .draggable(false)
  4407. .sourceSize({width:38, height:38})
  4408. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4409. // .autoResize(true) // 重采样,可减少内存占用
  4410. .opacity(this.opacityItem)// 绑定透明度
  4411. .margin({ left: 20 })
  4412. .shadow({
  4413. radius: StrUtil.isEmpty(item.pixelMapPath) ?6:14,
  4414. type: ShadowType.BLUR,
  4415. color: 'on_primary'
  4416. })
  4417. .onClick(()=>{
  4418. if (this.isMultiSelect) {
  4419. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  4420. this.handleFileSelection(item, !isChecked);
  4421. } else {
  4422. this.doPlay(item,index)
  4423. this.setShowPlayTrue()
  4424. }
  4425. })
  4426. }
  4427. Column() {
  4428. Column() {
  4429. Text(this.isShowFileName?item.fileName :item.name)
  4430. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4431. .maxLines(1)
  4432. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4433. .animation({
  4434. duration: 555,
  4435. curve: 'Linear',
  4436. })
  4437. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4438. $r('app.color.text_color'))
  4439. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4440. .padding({right:25})
  4441. .bindPopup(this.longItemFilePath === item.filePath, {
  4442. builder: this.MenuBuilder(item,index,item.filePath),
  4443. placement: Placement.Top,
  4444. // autoCancel: true,
  4445. mask: {color:'#33000000'},
  4446. // popupColor: Color.Yellow,
  4447. enableArrow: false,//是否显示箭头
  4448. showInSubWindow: false,
  4449. onStateChange: (e) => {
  4450. if (!e.isVisible) {
  4451. this.longItemFilePath = ''
  4452. this.tempLyricContent = ''
  4453. }
  4454. }
  4455. })
  4456. Row() {
  4457. Column(){
  4458. Text(item.md5Str?.includes('Lossless')?
  4459. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  4460. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  4461. .padding({ top: 3,right:6,left:6,bottom:3 })
  4462. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4463. $r('app.color.text_color'))
  4464. .fontWeight(500)
  4465. .borderRadius(12)
  4466. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  4467. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4468. .backgroundColor('#FFC107')
  4469. }
  4470. .padding({ top: 8 })
  4471. Text(StrUtil.isEmpty(item.artist) ? item.duration
  4472. :this.twoFingerType==2? item.artist +' ' + item.duration
  4473. : item.artist + ' ' + item?.duration)
  4474. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4475. .padding({ top: 8 ,right:25})
  4476. .visibility(this.isShowFileName?Visibility.None:Visibility.Visible)
  4477. .maxLines(1)
  4478. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4479. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4480. Color.Gray)
  4481. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4482. Blank()
  4483. Text(this.isShowFileName?item.duration:item.size)
  4484. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4485. .padding({ top: 8 })
  4486. .maxLines(1)
  4487. .visibility(this.isShowFileName?Visibility.Visible:StrUtil.isEmpty(item.artist)
  4488. ? Visibility.Visible : Visibility.None)
  4489. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4490. Color.Gray)
  4491. .margin({ left: StrUtil.isEmpty(item.artist) ?0:10 })
  4492. }
  4493. }
  4494. .height('100%')
  4495. .width('100%')
  4496. .margin({ right: 10 })
  4497. .justifyContent(FlexAlign.Center)
  4498. .alignItems(HorizontalAlign.Start)
  4499. }
  4500. .height('100%')
  4501. .margin({ left: 5 })
  4502. .layoutWeight(1)
  4503. Column() {
  4504. Checkbox({ name: 'checkbox' + index })
  4505. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  4506. .selectedColor(this.themeColor)
  4507. .shape(CheckBoxShape.CIRCLE)
  4508. .opacity(this.isMultiSelect ? 1 : 0)
  4509. .animation({
  4510. duration: 666,
  4511. curve: 'Smooth' // 可选动画曲线
  4512. })
  4513. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  4514. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  4515. .margin({ left: 20, top: 8, bottom: 8,right:18 })
  4516. .width(22)
  4517. .height(22)
  4518. ImageAnimator()
  4519. .images(this.imagesF)// 动画数组
  4520. .duration(1000)// 持续
  4521. .state(this.animationState)// 动画状态
  4522. .fillMode(FillMode.Forwards)
  4523. .width(18)
  4524. .margin({ right: 20, top: 8, bottom: 8 })
  4525. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  4526. Visibility.None)
  4527. .height(18)
  4528. .iterations(-1) // 播放次数
  4529. }
  4530. }
  4531. }
  4532. .gesture(LongPressGesture()
  4533. .onAction(async () => {
  4534. //如果是专辑和艺术家的首页,不能长按
  4535. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4536. return
  4537. //如果是我的收藏 最近播放等也不能长按
  4538. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4539. item.name === LocalMusic.STR_HISTORY_MUSIC
  4540. )
  4541. return
  4542. this.longItemFilePath = item.filePath
  4543. this.tempLyricContent = await this.getLyricContent(item)
  4544. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  4545. })
  4546. .onActionEnd((event: GestureEvent) => {
  4547. }))
  4548. .backgroundColor(Color.Transparent)
  4549. .width('100%')
  4550. .reuseId('file_item')
  4551. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  4552. }
  4553. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  4554. @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
  4555. buttons: [{ text: '文件夹' }, { text: '媒体库' },{ text: '艺术家' }, { text: '专辑' }],
  4556. direction: Direction.Ltr,
  4557. buttonPadding:{top:12,bottom:12},
  4558. backgroundColor: Color.Transparent,
  4559. fontSize:14,
  4560. selectedFontSize:15,
  4561. selectedFontColor:Color.White,
  4562. selectedBackgroundColor: this.themeColor,
  4563. localizedTextPadding: {
  4564. end: LengthMetrics.vp(20),
  4565. start: LengthMetrics.vp(20)
  4566. }
  4567. })
  4568. @State @Watch('capsuleSelectedIndexesChanged')tabSelectedIndexes: number[] = [0]
  4569. //当胶囊按钮的选择发生变化时调用此函数
  4570. capsuleSelectedIndexesChanged() {
  4571. this.modeType = this.tabSelectedIndexes[0]
  4572. }
  4573. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  4574. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  4575. isShowCoverHeader() {
  4576. if (!this.isShowHeader) {
  4577. return false
  4578. }
  4579. if (this.modeType == 0) {
  4580. if (this.isHistory || this.isFavMusic) {
  4581. return true
  4582. }
  4583. if (this.currentPath != this.rootPath) {
  4584. return true
  4585. }
  4586. }
  4587. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  4588. }
  4589. getCoverTitleBg(): ResourceStr | image.PixelMap {
  4590. if (this.isCustomizeBg) {
  4591. return ('rgba(255,255,255,0.2)')
  4592. }
  4593. if (this.isDarkMode) {
  4594. return $r('app.color.user_center_card_background')
  4595. }
  4596. return this.currentTitleCover
  4597. }
  4598. // 第二步:popup构造器定义弹框内容
  4599. @Builder popupBuilder() {
  4600. Column({ space: 2 }) {
  4601. Text('友情提示:双指缩放可以放大缩小列表')
  4602. .fontSize(12)
  4603. .fontWeight(FontWeight.Regular)
  4604. .fontColor($r('app.color.text_color'))
  4605. }
  4606. .justifyContent(FlexAlign.SpaceAround)
  4607. .width(220)
  4608. .height(55)
  4609. .padding(15)
  4610. }
  4611. //搜索功能的实现
  4612. @State searchText: string = ''; // 用户输入内容
  4613. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  4614. @State isSearchMode: boolean = false
  4615. // 实时搜索逻辑(带防抖)
  4616. private async onSearchInput(value: string): Promise<void> {
  4617. this.searchText = value.trim();
  4618. Logger.info('heanup LocalMusic', `onSearchInput: keyword="${this.searchText}", mode=${this.modeType}`);
  4619. // 新增条件判断:空输入时退出搜索模式
  4620. if (this.searchText === '') {
  4621. this.isSearchMode = false;
  4622. // 重新加载第一页(不带搜索条件)
  4623. await this.resetAndLoadFirstPage();
  4624. return;
  4625. }
  4626. // 进入搜索模式
  4627. if (!this.isSearchMode) {
  4628. this.isSearchMode = true;
  4629. }
  4630. // 使用数据库分页查询(带搜索条件)
  4631. await this.resetAndLoadFirstPage();
  4632. }
  4633. @State dragItem: number = -1
  4634. @State scaleItem: number = -1
  4635. @State neighborItem: number = -1
  4636. @State neighborScale: number = -1
  4637. @State offsetY: number = 0
  4638. private dragRefOffset: number = 0
  4639. private ITEM_INTV: number = 78
  4640. scaleSelect(item: number): number {
  4641. if (this.scaleItem === item) {
  4642. return 1.05
  4643. } else if (this.neighborItem === item) {
  4644. return this.neighborScale
  4645. } else {
  4646. return 1
  4647. }
  4648. }
  4649. itemMove(index: number, newIndex: number): void {
  4650. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  4651. return;
  4652. }
  4653. let tmp = this.videoLocalList.splice(index, 1);
  4654. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  4655. this.dataSource.pushArrayData(this.videoLocalList)
  4656. if(this.modeType==4&&this.playlistTable){
  4657. updateAllSongsSortOrder(this.playlistTable, this.videoLocalList,this.currentSongListID)
  4658. }
  4659. }
  4660. //瀑布流布局 支持双指缩放
  4661. @State columns: number = 2;
  4662. @State waterFlowScale: number = 1;
  4663. @State imageScale: number = 1;
  4664. @State waterFlowOpacity: number = 1;
  4665. @State waterFlowSnapshot: image.PixelMap | undefined = undefined;
  4666. private columnChanged: boolean = false;
  4667. private oldColumn: number = this.columns;
  4668. private pinchTime: number = 0;
  4669. // 根据缩放阈值改变列数,触发WaterFlow重新布局
  4670. changeColumns(scale: number): void {
  4671. if (scale > (this.columns / (this.columns - 0.5)) && this.columns > 1) {
  4672. this.columns--;
  4673. this.columnChanged = true;
  4674. } else if (scale < 1 && this.columns < 4) {
  4675. this.columns++;
  4676. this.columnChanged = true;
  4677. }
  4678. }
  4679. @Builder
  4680. getWaterView(){
  4681. Scroll(this.scroller) {
  4682. Column() {
  4683. Blank().height(this.topSafeHeight + 55)
  4684. WaterFlow({
  4685. scroller:this.waterScroller,
  4686. layoutMode: WaterFlowLayoutMode.SLIDING_WINDOW
  4687. }) {
  4688. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  4689. FlowItem() {
  4690. this.MusicWaterCardItem(item,index)
  4691. }
  4692. .width('100%')
  4693. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  4694. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  4695. {
  4696. preview: MenuPreviewMode.IMAGE,
  4697. previewAnimationOptions: { scale: [0.8, 1.0] },
  4698. })
  4699. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  4700. {
  4701. preview: MenuPreviewMode.IMAGE,
  4702. previewAnimationOptions: { scale: [0.8, 1.0] },
  4703. })
  4704. .transition(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }))
  4705. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  4706. TransitionEffect.scale({ x: 0, y: 0 })))
  4707. .gesture(
  4708. GestureGroup(GestureMode.Exclusive,
  4709. SwipeGesture({ direction: SwipeDirection.Horizontal })
  4710. .onAction((event: GestureEvent) => {
  4711. if (event) {
  4712. // this.sideBarController.openSideBar()
  4713. }
  4714. }),
  4715. TapGesture({ count: 1, fingers: 1 })
  4716. .onAction(async () => {
  4717. })
  4718. )
  4719. )
  4720. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  4721. }
  4722. // .columnsTemplate('repeat(auto-fit, 160)')
  4723. .id('waterflow') // 设置id用于截图
  4724. .columnsTemplate('1fr '.repeat(this.columns)) // 动态生成列模板,如:'1fr 1fr 1fr'表示3列等宽
  4725. .columnsGap(12) // 列间距
  4726. .rowsGap(16) // 行间距
  4727. .cachedCount(6)
  4728. .padding({bottom:this.bottomBarHeight+10})
  4729. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  4730. .animation({ duration: 500, curve: Curve.Ease }))
  4731. .scrollBar(BarState.Off)
  4732. // .fadingEdge(true, { fadingEdgeLength: LengthMetrics.vp(38) })
  4733. // 效果:只有向上或者向下滑动到顶部时才会有弹簧回弹效果
  4734. .edgeEffect(EdgeEffect.Spring, { alwaysEnabled: true })
  4735. .width('90%')
  4736. .height('100%')
  4737. .opacity(this.waterFlowOpacity)
  4738. .scale({
  4739. x: this.waterFlowScale,
  4740. y: this.waterFlowScale,
  4741. centerX: 0,
  4742. centerY: 0
  4743. })
  4744. .onReachEnd(() => {
  4745. if(this.modeType === 4 )
  4746. return;
  4747. // 触底加载下一页
  4748. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  4749. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  4750. return;
  4751. }
  4752. if (this.hasMoreData && !this.isLoadingPage) {
  4753. this.loadNextPage();
  4754. }
  4755. })
  4756. .onAppear(() => {
  4757. this.scroller.scrollEdge(Edge.Top)
  4758. })
  4759. .nestedScroll({
  4760. scrollForward: NestedScrollMode.PARENT_FIRST,
  4761. scrollBackward: NestedScrollMode.SELF_FIRST
  4762. })
  4763. .priorityGesture(
  4764. PinchGesture()
  4765. .onActionStart((event: GestureEvent) => {
  4766. // 双指捏合手势识别成功时截图
  4767. this.pinchTime = event.timestamp;
  4768. this.columnChanged = false;
  4769. this.oldColumn = this.columns;
  4770. this.getUIContext().getComponentSnapshot().get('waterflow', (error: Error, pixmap: image.PixelMap) => {
  4771. if (error) {
  4772. console.info('error:' + JSON.stringify(error));
  4773. return;
  4774. }
  4775. this.waterFlowSnapshot = pixmap;
  4776. if ((this.oldColumn === 1 ) && event.scale > 1|| (this.oldColumn === 4 && event.scale < 1)) {
  4777. console.info("onecold onActionStart oldColumn:" + this.oldColumn)
  4778. if (this.oldColumn ===4) {
  4779. this.twoFingerType =3
  4780. this.isGridMusic = true
  4781. }else if (this.oldColumn ===1) {
  4782. this.twoFingerType =1
  4783. this.isGridMusic = false
  4784. }
  4785. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  4786. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4787. return;
  4788. }
  4789. })
  4790. })
  4791. .onActionUpdate((event: GestureEvent) => {
  4792. // 手势更新:处理缩放逻辑和视觉效果
  4793. // 边界限制:防止超出列数范围时继续缩放
  4794. if ((this.oldColumn === 1 && event.scale > 1) || (this.oldColumn === 4 && event.scale < 1)) {
  4795. return;
  4796. }
  4797. // 节流处理:避免过于频繁的更新,提升性能
  4798. if (event.timestamp - this.pinchTime < 10000000) {
  4799. return;
  4800. }
  4801. this.pinchTime = event.timestamp;
  4802. this.waterFlowScale = event.scale;
  4803. this.imageScale = event.scale;
  4804. // 根据缩放比例设置WaterFlow透明度
  4805. this.waterFlowOpacity = (this.waterFlowScale > 1) ? (this.waterFlowScale - 1) : (1 - this.waterFlowScale);
  4806. this.waterFlowOpacity *= 3;
  4807. if (!this.columnChanged) {
  4808. this.changeColumns(event.scale);
  4809. }
  4810. // 列数改变后的缩放比例调整:避免出现空白区域
  4811. if (this.columnChanged) {
  4812. this.waterFlowScale = this.imageScale * this.columns / this.oldColumn;
  4813. // 限制缩放范围,确保视觉效果自然
  4814. if (event.scale < 1) {
  4815. this.waterFlowScale = this.waterFlowScale > 1 ? this.waterFlowScale : 1;
  4816. } else {
  4817. this.waterFlowScale = this.waterFlowScale < 1 ? this.waterFlowScale : 1;
  4818. }
  4819. }
  4820. })
  4821. .onActionEnd((event: GestureEvent) => {
  4822. // 手势结束:执行归位动画并保存状态
  4823. // 执行归位动画:平滑过渡到正常状态
  4824. this.getUIContext()?.animateTo({ duration: 300 }, () => {
  4825. this.waterFlowScale = 1;
  4826. this.waterFlowOpacity = 1;
  4827. })
  4828. // 持久化保存当前列数:下次启动时恢复
  4829. PreferencesUtil.putSync('lastColumns', this.columns);
  4830. })
  4831. )
  4832. .onScrollFrameBegin((offset: number) => {
  4833. // 获取当前滚动偏移量
  4834. if(this.autoHideTitle){
  4835. const currentOffsetY = this.waterScroller.currentOffset().yOffset;
  4836. // 判断滚动方向
  4837. if (currentOffsetY > this.prevOffsetY) {
  4838. // console.log("onecold 向上滚动");
  4839. this.isShowTitleBar = false
  4840. } else if (currentOffsetY < this.prevOffsetY) {
  4841. // console.log("onecold 向下滚动");
  4842. this.isShowTitleBar = true
  4843. }
  4844. // 更新前一次偏移量
  4845. this.prevOffsetY = currentOffsetY;
  4846. }
  4847. return { offsetRemain: offset };
  4848. })
  4849. }
  4850. }
  4851. .scrollBar(BarState.Off)
  4852. }
  4853. //瀑布流卡片布局
  4854. @Builder
  4855. private MusicWaterCardItem(item: VideoItem, index: number) {
  4856. Button({ type: ButtonType.Normal, stateEffect: false }) {
  4857. Stack() {
  4858. Column() {
  4859. Image(item.pixelMapPath)
  4860. .backgroundImageSize(ImageSize.Auto)
  4861. .borderRadius({
  4862. topLeft: 12,
  4863. topRight : 12,
  4864. bottomLeft: 0,
  4865. bottomRight: 0
  4866. })
  4867. .draggable(false)// 禁止长按手势拖动
  4868. .autoResize(true) // 重采样,可减少内存占用
  4869. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4870. .width('100%')
  4871. .height('auto')
  4872. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  4873. .objectFit(ImageFit.Auto)
  4874. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  4875. height: '99%' ,
  4876. dragBar: true,
  4877. onDisappear: () => {
  4878. this.longItemFilePath = '';
  4879. this.tempLyricContent = ''
  4880. },
  4881. showClose: true,
  4882. preferType: SheetType.CENTER ,
  4883. title: { title: '编辑标签' }
  4884. })
  4885. .draggable(false)
  4886. .opacity(this.opacityItem)// 绑定透明度
  4887. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  4888. // .animation({ duration: 500, curve: Curve.Ease }))
  4889. .animation({
  4890. duration: 666,
  4891. curve: 'ease-in-out' // 可选动画曲线
  4892. })
  4893. .margin({
  4894. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  4895. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  4896. })
  4897. Column() {
  4898. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  4899. .fontSize(this.columns == 4 ||this.columns==3? 12 : this.columns == 2 ? 15 : 18)
  4900. .maxLines(1)
  4901. .fontWeight(FontWeight.Bold)
  4902. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4903. .animation({
  4904. duration: 555,
  4905. curve: 'Linear',
  4906. })
  4907. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  4908. height: '95%',
  4909. dragBar: true,
  4910. showClose: true,
  4911. onDisappear: () => {
  4912. this.longItemFilePathDetail = '';
  4913. },
  4914. blurStyle:BlurStyle.Thin,
  4915. backgroundColor:Color.Transparent,
  4916. preferType: SheetType.CENTER ,
  4917. title: { title: '详情' }
  4918. })
  4919. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4920. $r('app.color.text_color'))
  4921. Column() {
  4922. Text(`${this.getArtistSongCount(item.name)}首`)
  4923. .fontSize(11)
  4924. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  4925. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4926. .fontColor($r('app.color.text_color'))
  4927. Text(`${this.getAlbumSongCount(item.name)}首`)
  4928. .fontSize(11)
  4929. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  4930. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4931. .fontColor($r('app.color.text_color'))
  4932. Row(){
  4933. Column(){
  4934. Text(item.md5Str?.includes('Lossless')?
  4935. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  4936. .fontSize(this.columns == 4 ||this.columns==3? 8 : this.columns == 2 ? 9 : 11)
  4937. .padding({ top: 3,right:6,left:6,bottom:3 })
  4938. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4939. $r('app.color.text_color'))
  4940. .fontWeight(500)
  4941. .borderRadius(12)
  4942. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4943. .backgroundColor('#FFC107')
  4944. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  4945. }
  4946. .margin({ top: 2 ,right:6})
  4947. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  4948. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  4949. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  4950. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 13)
  4951. .maxLines(1)
  4952. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4953. .margin({ top: 2})
  4954. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  4955. || item.type == CommonConstants.TYPE_IS_ALBUM
  4956. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4957. .fontWeight(FontWeight.Medium)
  4958. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4959. $r('app.color.text_color'))
  4960. }
  4961. }
  4962. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  4963. }
  4964. .height(this.columns == 4 ||this.columns==3? item.type==CommonConstants.TYPE_IS_DIR?30:40
  4965. : this.columns == 2 ? (item.type==CommonConstants.TYPE_IS_DIR?38:48) :
  4966. (item.type==CommonConstants.TYPE_IS_DIR?48:58))
  4967. .width('100%')
  4968. .justifyContent(FlexAlign.Center)
  4969. .margin({
  4970. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  4971. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  4972. })
  4973. }
  4974. .width('100%')
  4975. .borderRadius(12)
  4976. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  4977. .backgroundImageSize({ height: '100%', width: '100%' })
  4978. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  4979. .animation({ curve: Curve.Sharp, duration: 300 })
  4980. Checkbox({ name: 'checkbox' + index })
  4981. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  4982. .selectedColor(this.themeColor)
  4983. .shape(CheckBoxShape.CIRCLE)
  4984. .opacity(this.isMultiSelect ? 1 : 0)
  4985. .animation({
  4986. duration: 666,
  4987. curve: 'Smooth' // 可选动画曲线
  4988. })
  4989. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  4990. Visibility.None)
  4991. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  4992. .margin({ left: 20, top: 8, bottom: 8 })
  4993. .width(38)
  4994. .height(38)
  4995. }
  4996. }
  4997. .backgroundColor(Color.Transparent)
  4998. .width('100%')
  4999. .height('auto')
  5000. .padding({top:2})
  5001. .shadow({
  5002. radius: 10,
  5003. type: ShadowType.BLUR,
  5004. color: 'on_primary'
  5005. })
  5006. .reuseId('card_item')
  5007. .onClick(() => {
  5008. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5009. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5010. this.handleFileSelection(item, !isChecked);
  5011. } else {
  5012. this.doPlay(item, index)
  5013. }
  5014. })
  5015. }
  5016. // Grid布局的开始
  5017. private dragRefOffSetX: number = 0;
  5018. private dragRefOffSetY: number = 0;
  5019. private FIX_VP_X: number = 180;
  5020. private FIX_VP_Y: number = 84;
  5021. isDraggable(index: number): boolean {
  5022. return index >= 0;
  5023. }
  5024. getRowEnd(item: number) {
  5025. if (item.toString() === '0') {
  5026. return 1;
  5027. } else {
  5028. return 0;
  5029. }
  5030. }
  5031. isInLeft(index: number) {
  5032. return index % 2 == 0;
  5033. }
  5034. down(index: number): void {
  5035. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  5036. return;
  5037. }
  5038. this.offsetY -= this.FIX_VP_Y;
  5039. this.dragRefOffSetY += this.FIX_VP_Y;
  5040. this.itemMove(index, index + 1);
  5041. }
  5042. up(index: number): void {
  5043. if (!this.isDraggable(index - 2)) {
  5044. return;
  5045. }
  5046. this.offsetY += this.FIX_VP_Y;
  5047. this.dragRefOffSetY -= this.FIX_VP_Y;
  5048. this.itemMove(index, index - 1);
  5049. }
  5050. left(index: number): void {
  5051. if (this.isInLeft(index)) {
  5052. return;
  5053. }
  5054. if (!this.isDraggable(index - 1)) {
  5055. return;
  5056. }
  5057. this.offsetX += this.FIX_VP_X;
  5058. this.dragRefOffSetX -= this.FIX_VP_X;
  5059. this.itemMove(index, index - 1)
  5060. }
  5061. right(index: number): void {
  5062. if (!this.isInLeft(index)) {
  5063. return;
  5064. }
  5065. if (!this.isDraggable(index + 1)) {
  5066. return;
  5067. }
  5068. this.offsetX -= this.FIX_VP_X;
  5069. this.dragRefOffSetX += this.FIX_VP_X;
  5070. this.itemMove(index, index + 1)
  5071. }
  5072. private scroller: Scroller = new Scroller();
  5073. private waterScroller: Scroller = new Scroller();
  5074. @State startIndex: number = 0
  5075. @State endIndex: number = 0
  5076. @State scaleValue: number = 1
  5077. @State pinchValue: number = 1
  5078. layoutOptionsForHeader: GridLayoutOptions = {
  5079. regularSize: [1, 1], // 只支持[1, 1]
  5080. irregularIndexes: [0], // 索引为0的GridItem占用一行
  5081. };
  5082. @Builder
  5083. getGridView() {
  5084. Grid(this.scroller, this.layoutOptionsForHeader) {
  5085. GridItem() {
  5086. Column(){
  5087. Blank().height(this.topSafeHeight + 45)
  5088. }
  5089. }
  5090. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5091. GridItem() {
  5092. Stack({ alignContent: Alignment.Center }) {
  5093. this.MusicItemGrid(item, index)
  5094. }
  5095. }
  5096. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  5097. {
  5098. preview: MenuPreviewMode.IMAGE,
  5099. previewAnimationOptions: { scale: [0.8, 1.0] },
  5100. })
  5101. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  5102. {
  5103. preview: MenuPreviewMode.IMAGE,
  5104. previewAnimationOptions: { scale: [0.8, 1.0] },
  5105. })
  5106. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  5107. TransitionEffect.scale({ x: 0, y: 0 })))
  5108. .clickEffect({ level: ClickEffectLevel.LIGHT })
  5109. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  5110. .zIndex(this.dragItem === index ? 1 : 0)
  5111. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  5112. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5113. }
  5114. .width('94%')
  5115. .height('100%')
  5116. .editMode(true)
  5117. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  5118. .animation({ duration: 500, curve: Curve.Ease }))
  5119. .padding({bottom:this.bottomBarHeight+this.bottomSafeHeight+10})
  5120. .reuseId('grid_item')
  5121. .layoutWeight(1)
  5122. .scrollBar(BarState.Off)
  5123. .supportAnimation(true)
  5124. .onReachEnd(() => {
  5125. if(this.modeType === 4 )
  5126. return;
  5127. // 触底加载下一页
  5128. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  5129. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  5130. return;
  5131. }
  5132. if (this.hasMoreData && !this.isLoadingPage) {
  5133. this.loadNextPage();
  5134. }
  5135. })
  5136. .cachedCount(this.twoFingerType==1?5:this.twoFingerType==2?4:3)
  5137. .columnsTemplate(
  5138. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  5139. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  5140. )
  5141. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  5142. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  5143. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  5144. .gesture(PinchGesture({ fingers: 2 })
  5145. .onActionEnd((event: GestureEvent) => {
  5146. this.setGridTwoFingers()
  5147. })
  5148. .onActionUpdate(e => {
  5149. this.scaleValue = this.pinchValue * e.scale
  5150. })
  5151. .onActionStart(e => {
  5152. }))
  5153. .enableScrollInteraction(true)
  5154. .onScrollIndex((start: number, end: number) => {
  5155. this.startIndex = start
  5156. this.endIndex = end
  5157. })
  5158. .onScrollFrameBegin((offset: number) => {
  5159. if(this.autoHideTitle){
  5160. const currentOffsetY = this.scroller.currentOffset().yOffset;
  5161. // 判断滚动方向
  5162. if (currentOffsetY > this.prevOffsetY) {
  5163. // console.log("onecold 向上滚动");
  5164. this.isShowTitleBar = false
  5165. } else if (currentOffsetY < this.prevOffsetY) {
  5166. // console.log("onecold 向下滚动");
  5167. this.isShowTitleBar = true
  5168. }
  5169. // 更新前一次偏移量
  5170. this.prevOffsetY = currentOffsetY;
  5171. }
  5172. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  5173. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  5174. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  5175. if (this.isScrollHide) {
  5176. this.setBarHeightHide2(offset)
  5177. } else {
  5178. this.setBarHeightNormal()
  5179. }
  5180. } else {
  5181. this.setBarHeightHide(offset)
  5182. }
  5183. return { offsetRemain: offset };
  5184. })
  5185. }
  5186. @State targetFile: string = '';
  5187. setGridTwoFingers() {
  5188. this.pinchValue = this.scaleValue;
  5189. Logger.info('this.pinchValue = ' + this.pinchValue);
  5190. if (this.pinchValue >= 1) {
  5191. this.twoFingerType++
  5192. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  5193. if(this.twoFingerType >= 4){
  5194. this.twoFingerType = 4//切换成瀑布流
  5195. this.columns = 4
  5196. }
  5197. } else {
  5198. this.twoFingerType--
  5199. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  5200. if (this.twoFingerType < 1) {
  5201. this.twoFingerType = 3
  5202. this.isGridMusic = false
  5203. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5204. }
  5205. }
  5206. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  5207. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5208. this.pinchValue = 1;
  5209. this.scaleValue = 1;
  5210. }
  5211. @State longItemFilePath: string = ''
  5212. @State tempLyricContent: string = ''
  5213. @State editingItem: VideoItem | null = null
  5214. @Builder
  5215. private MusicItemGrid(item: VideoItem, index: number) {
  5216. Button({ type: ButtonType.Normal, stateEffect: false }) {
  5217. Stack() {
  5218. Column() {
  5219. Image(item.pixelMapPath)
  5220. .height(this.getGridHeight())
  5221. .width(this.getGridWight())
  5222. .draggable(false)
  5223. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  5224. .autoResize(true) // 重采样,可减少内存占用
  5225. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  5226. .clip(true)
  5227. .borderRadius({
  5228. topLeft: 12,
  5229. topRight: 12,
  5230. bottomLeft: 0,
  5231. bottomRight: 0
  5232. })
  5233. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  5234. height: '99%' ,
  5235. dragBar: true,
  5236. onDisappear: () => {
  5237. this.longItemFilePath = '';
  5238. this.tempLyricContent = ''
  5239. },
  5240. showClose: true,
  5241. preferType: SheetType.CENTER ,
  5242. title: { title: '编辑标签' }
  5243. })
  5244. .draggable(false)
  5245. .opacity(this.opacityItem)// 绑定透明度
  5246. .animation({
  5247. duration: 666,
  5248. curve: 'ease-in-out' // 可选动画曲线
  5249. })
  5250. .margin({
  5251. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5252. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5253. })
  5254. Column() {
  5255. Text(this.isShowFileName&&item.type!=CommonConstants.TYPE_IS_DIR?item.fileName :item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  5256. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5257. .maxLines(1)
  5258. .fontWeight(FontWeight.Bold)
  5259. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5260. .animation({
  5261. duration: 555,
  5262. curve: 'Linear',
  5263. })
  5264. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  5265. height: '100%',
  5266. dragBar: true,
  5267. showClose: true,
  5268. onDisappear: () => {
  5269. this.longItemFilePathDetail = '';
  5270. },
  5271. blurStyle:BlurStyle.Thin,
  5272. backgroundColor:Color.Transparent,
  5273. preferType: SheetType.CENTER ,
  5274. title: { title: '详情' }
  5275. })
  5276. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5277. $r('app.color.text_color'))
  5278. Column() {
  5279. Text(`${this.getArtistSongCount(item.name)}首`)
  5280. .fontSize(11)
  5281. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  5282. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5283. .fontColor($r('app.color.text_color'))
  5284. Text(`${this.getAlbumSongCount(item.name)}首`)
  5285. .fontSize(11)
  5286. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  5287. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5288. .fontColor($r('app.color.text_color'))
  5289. Row(){
  5290. Column(){
  5291. Text(item.md5Str?.includes('Lossless')?
  5292. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5293. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  5294. .padding({ top: 3,right:6,left:6,bottom:3 })
  5295. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5296. $r('app.color.text_color'))
  5297. .fontWeight(500)
  5298. .borderRadius(12)
  5299. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5300. .backgroundColor('#FFC107')
  5301. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  5302. }
  5303. .margin({ top: 2 ,right:6})
  5304. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  5305. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  5306. Text(this.isShowFileName?item.duration:StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  5307. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  5308. .maxLines(1)
  5309. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5310. .margin({ top: 2})
  5311. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  5312. || item.type == CommonConstants.TYPE_IS_ALBUM
  5313. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5314. .fontWeight(FontWeight.Medium)
  5315. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5316. $r('app.color.text_color'))
  5317. }
  5318. }
  5319. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  5320. }
  5321. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  5322. .width(this.getGridWight())
  5323. .justifyContent(FlexAlign.Center)
  5324. .margin({
  5325. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5326. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5327. })
  5328. }
  5329. .width(this.getGridWight())
  5330. .borderRadius(12)
  5331. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath)?$r('app.media.alt'):item.pixelMapPath)
  5332. .backgroundImageSize({ height: '100%', width: '100%' })
  5333. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  5334. .animation({ curve: Curve.Sharp, duration: 300 })
  5335. Checkbox({ name: 'checkbox' + index })
  5336. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  5337. .selectedColor(this.themeColor)
  5338. .shape(CheckBoxShape.CIRCLE)
  5339. .opacity(this.isMultiSelect ? 1 : 0)
  5340. .animation({
  5341. duration: 666,
  5342. curve: 'Smooth' // 可选动画曲线
  5343. })
  5344. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  5345. Visibility.None)
  5346. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5347. .margin({ left: 20, top: 8, bottom: 8 })
  5348. .width(38)
  5349. .height(38)
  5350. }
  5351. }
  5352. .backgroundColor(Color.Transparent)
  5353. .width('100%')
  5354. .padding({ top: 15 })
  5355. .height(this.getGridAllHeight())
  5356. .onClick(() => {
  5357. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5358. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5359. this.handleFileSelection(item, !isChecked);
  5360. } else {
  5361. this.doPlay(item, index)
  5362. }
  5363. })
  5364. }
  5365. getGridAllHeight() {
  5366. let heightG = 222
  5367. switch (this.twoFingerType) {
  5368. case 1:
  5369. heightG = 143
  5370. break;
  5371. case 2:
  5372. heightG = 178
  5373. break;
  5374. case 3:
  5375. heightG = 222
  5376. break;
  5377. }
  5378. return heightG
  5379. }
  5380. getGridHeight() {
  5381. let heightG = 150
  5382. switch (this.twoFingerType) {
  5383. case 1:
  5384. heightG = 80
  5385. break;
  5386. case 2:
  5387. heightG = 110
  5388. break;
  5389. case 3:
  5390. heightG = 150
  5391. break;
  5392. }
  5393. return heightG
  5394. }
  5395. getGridWight() {
  5396. let wightG = 158
  5397. switch (this.twoFingerType) {
  5398. case 1:
  5399. wightG = 80
  5400. break;
  5401. case 2:
  5402. wightG = 110
  5403. break;
  5404. case 3:
  5405. wightG = 158
  5406. break;
  5407. }
  5408. return wightG
  5409. }
  5410. @State isShowDetail:boolean = false
  5411. @State longItemFilePathDetail:string =''
  5412. @Builder
  5413. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  5414. if(
  5415. ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  5416. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5417. item.name === LocalMusic.STR_HISTORY_MUSIC)
  5418. ){
  5419. //如果是专辑和艺术家的首页,不能长按
  5420. //如果是我的收藏 最近播放等也不能长按
  5421. }else{
  5422. Scroll() {
  5423. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  5424. Menu() {
  5425. MenuItem({
  5426. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  5427. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  5428. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  5429. })
  5430. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5431. .onClick(() => {
  5432. if (item) {
  5433. this.doFav(item)
  5434. }
  5435. this.longItemFilePath = ''
  5436. })
  5437. MenuItem({
  5438. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  5439. content: '下一首播放'
  5440. })
  5441. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5442. .onClick(() => {
  5443. this.addToNextPlay(item);
  5444. this.longItemFilePath = ''
  5445. })
  5446. MenuItem({
  5447. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  5448. content: '添加到歌单'
  5449. })
  5450. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5451. .onClick(async () => {
  5452. this.longItemFilePath = ''
  5453. await this.openAddToPlaylistDialog(item)
  5454. })
  5455. MenuItem({
  5456. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  5457. content: '编辑标签'
  5458. })
  5459. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  5460. height: '99%',
  5461. dragBar: true,
  5462. showClose: true,
  5463. preferType: SheetType.CENTER ,
  5464. title: { title: '编辑标签' }
  5465. })
  5466. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5467. .onClick(async() => {
  5468. this.initEditFields(item)
  5469. this.tempLyricContent = await this.getLyricContent(item);
  5470. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  5471. this.lyricConStr = this.tempLyricContent
  5472. }
  5473. if(this.isGridMusic||this.twoFingerType==4){
  5474. this.longItemFilePath = item.filePath
  5475. }else{
  5476. this.isShowEdit = !this.isShowEdit;
  5477. }
  5478. })
  5479. MenuItem({
  5480. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  5481. content: $r('app.string.select_all')
  5482. })
  5483. .onClick(() => {
  5484. this.isMultiSelect = !this.isMultiSelect
  5485. this.longItemFilePath = ''
  5486. this.selectedFiles.push(item)
  5487. })
  5488. MenuItem({
  5489. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.cut')),
  5490. content: $r('app.string.edit_audio')
  5491. })
  5492. .bindContentCover($$this.isEditAudio, this.EditAudioBuilder(item), {
  5493. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5494. })
  5495. .onClick(() => {
  5496. this.isEditAudio = !this.isEditAudio
  5497. })
  5498. MenuItem({
  5499. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  5500. content: $r('app.string.extract_accompaniment')
  5501. })
  5502. .bindContentCover($$this.isExtractAcc, this.ExtractAccBuilder(item), {
  5503. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5504. })
  5505. .onClick(() => {
  5506. if (!Utility.isNoble()) {
  5507. this.showVipDialog()
  5508. return
  5509. }
  5510. this.isExtractAcc = !this.isExtractAcc
  5511. })
  5512. MenuItem({
  5513. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.repeat')),
  5514. content: $r('app.string.converter_audio')
  5515. })
  5516. .bindContentCover($$this.isConverter, this.ConverterBuilder(item), {
  5517. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5518. })
  5519. .onClick(() => {
  5520. if (!Utility.isNoble()) {
  5521. this.showVipDialog()
  5522. return
  5523. }
  5524. this.isConverter = !this.isConverter
  5525. })
  5526. MenuItem({
  5527. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.ai_edit')),
  5528. content: $r('app.string.vocal_separation')
  5529. })
  5530. .bindContentCover($$this.isAIVoiceSeparation, this.AiBuilder(item), {
  5531. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5532. })
  5533. .onClick(() => {
  5534. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  5535. })
  5536. MenuItem({
  5537. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_counterclockwise_clock')),
  5538. content: $r('app.string.change_tone')
  5539. })
  5540. .bindContentCover($$this.isChangeTone, this.ChangeToneBuilder(item), {
  5541. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5542. })
  5543. .onClick(() => {
  5544. this.isChangeTone = !this.isChangeTone
  5545. })
  5546. if(Utility.isVideoByExtension(item.filePath)){
  5547. MenuItem({
  5548. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.identify_song')),
  5549. content: $r('app.string.extract_audio')
  5550. })
  5551. .bindContentCover($$this.isExtractAudio, this.extractAudioFromVideoBuilder(item), {
  5552. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5553. })
  5554. .onClick(() => {
  5555. this.isExtractAudio = !this.isExtractAudio
  5556. })
  5557. }
  5558. MenuItem({
  5559. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.phone')),
  5560. content: $r('app.string.set_ring')
  5561. })
  5562. .onClick(async () => {
  5563. await PermissionUtil.activatePermission(item.filePath)
  5564. // if(item.filePath.includes(this.packName)){
  5565. setRingTone(this.context, item.filePath,item.name)
  5566. // }else{
  5567. // ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限设置铃声')
  5568. // }
  5569. this.longItemFilePath = ''
  5570. })
  5571. MenuItem({
  5572. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  5573. content: $r('app.string.rename')
  5574. })
  5575. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  5576. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5577. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  5578. .onClick(() => {
  5579. this.showReNameDialog(item, index + '', filePath)
  5580. this.longItemFilePath = ''
  5581. })
  5582. MenuItem({
  5583. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  5584. content: $r('app.string.delete')
  5585. })
  5586. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  5587. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5588. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  5589. .onClick(() => {
  5590. this.selectedFiles.push(item)
  5591. this.showWarnIsDelete()
  5592. this.longItemFilePath = ''
  5593. })
  5594. MenuItem({
  5595. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  5596. content: $r('app.string.detail')
  5597. })
  5598. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  5599. height:'100%',
  5600. dragBar: true,
  5601. showClose: true,
  5602. blurStyle:BlurStyle.Thin,
  5603. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  5604. backgroundColor:Color.Transparent,
  5605. title: { title: '详情信息' }
  5606. })
  5607. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5608. .onClick(() => {
  5609. if(this.isGridMusic||this.twoFingerType==4){
  5610. this.longItemFilePathDetail = item.filePath
  5611. }else{
  5612. this.isShowDetail = !this.isShowDetail
  5613. }
  5614. })
  5615. MenuItem({
  5616. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  5617. content: $r('app.string.share')
  5618. })
  5619. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5620. .onClick(() => {
  5621. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  5622. this.longItemFilePath = ''
  5623. })
  5624. }
  5625. .font({ size: 14, weight: FontWeight.Normal })
  5626. }
  5627. .width(180)
  5628. }
  5629. .height('auto')
  5630. .enableScrollInteraction(true)
  5631. .scrollBar(this.isGridMusic?BarState.On:BarState.Off)
  5632. }
  5633. }
  5634. private listMaxScrollOffsetY: number = 0
  5635. @State selectedIndex: number = -1
  5636. setlistTwoFingers() {
  5637. this.pinchValue = this.scaleValue;
  5638. Logger.info('this.pinchValue = ' + this.pinchValue);
  5639. if (this.pinchValue >= 1) {
  5640. this.twoFingerType++
  5641. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  5642. if (this.twoFingerType > 3) {
  5643. this.twoFingerType = 1
  5644. this.isGridMusic = true
  5645. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5646. }
  5647. } else {
  5648. this.twoFingerType--
  5649. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  5650. if (this.twoFingerType < 1) {
  5651. this.twoFingerType = 4
  5652. this.columns = 1
  5653. }
  5654. }
  5655. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  5656. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5657. this.pinchValue = 1;
  5658. this.scaleValue = 1;
  5659. }
  5660. @Builder
  5661. getList(){
  5662. Stack() {
  5663. Refresh({ refreshing: $$this.isRefreshing, refreshingContent: this.contentNode }) {
  5664. this.getListView()
  5665. }
  5666. .pullDownRatio(this.ratioL)
  5667. .pullToRefresh(true)
  5668. .refreshOffset(0)
  5669. .onOffsetChange((offset: number) => {
  5670. // 越接近最大距离,下拉跟手系数越小。
  5671. this.ratioL = 1 - Math.pow((offset / this.maxRefreshingHeight), 3);
  5672. })
  5673. .onStateChange((refreshStatus: RefreshStatus) => {
  5674. console.info('onecold Refresh onStatueChange state is ' + refreshStatus);
  5675. })
  5676. .onRefreshing(async () => {
  5677. if(this.modeType==0){
  5678. this.getHistoryList(false)
  5679. this.asyncCurrentPathOnlyFile()
  5680. }else if(this.modeType == 1){
  5681. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  5682. }else if(this.modeType == 2){
  5683. workerInstance.postMessage({ code: 3, data: this.context });
  5684. }else if(this.modeType == 3){
  5685. workerInstance.postMessage({ code: 4, data: this.context });
  5686. }else if(this.modeType == 4){
  5687. this.doSongListTask()
  5688. }
  5689. console.log('onRefreshing test');
  5690. })
  5691. }
  5692. }
  5693. // 扫描当前目录下的文件,不扫描子目录
  5694. asyncCurrentPathOnlyFile(){
  5695. if(this.modeType==0){
  5696. const task = new taskpool.Task(scanCurrentDirectoryTask, getContext(this), this.currentPath,
  5697. this.lockPath,PreferencesUtil.getStringSync('COVER_API',''));
  5698. taskpool.execute(task, taskpool.Priority.HIGH).then(()=>{
  5699. if(this.modeType==0){
  5700. setTimeout(()=>{
  5701. this.isRefreshing =false
  5702. this.deleteCache(this.currentPath)
  5703. this.getSortedFiles(this.currentPath)
  5704. },500)
  5705. }
  5706. }).catch((e:object)=>{
  5707. this.isRefreshing =false
  5708. console.info("onecold task1 catch e: " + e);
  5709. })
  5710. }
  5711. }
  5712. @Builder
  5713. getListView() {
  5714. List({ scroller: this.listScroller }) {
  5715. // ListItemGroup({ header: this.coverHeader() }) {
  5716. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5717. ListItem() {
  5718. Column() {
  5719. if (item.type === CommonConstants.TYPE_IS_DIR
  5720. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  5721. this.DirItem(item, index)
  5722. } else {
  5723. this.MusicItem(item, index)
  5724. }
  5725. }
  5726. .animation({ curve: Curve.Sharp, duration: 300 })
  5727. }
  5728. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.9, y: 0.9 })
  5729. .animation({ duration: 500 }),
  5730. TransitionEffect.scale({ x: 0, y: 0 })))
  5731. .clickEffect({ level: ClickEffectLevel.LIGHT })
  5732. .swipeAction((
  5733. (this.isSwipe&&this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack))
  5734. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  5735. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath),
  5736. start:null,edgeEffect: SwipeEdgeEffect.None } : {}) //左滑
  5737. .onClick(() => {
  5738. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5739. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5740. this.handleFileSelection(item, !isChecked);
  5741. } else {
  5742. this.doPlay(item, index)
  5743. }
  5744. })
  5745. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5746. // 加载中指示器
  5747. if (this.isLoadingPage) {
  5748. ListItem() {
  5749. Row() {
  5750. LoadingProgress()
  5751. .width(30)
  5752. .height(30)
  5753. .color(this.themeColor)
  5754. Text('加载中...')
  5755. .margin({ left: 10 })
  5756. .fontSize(14)
  5757. .fontColor($r('app.color.text_color'))
  5758. }
  5759. .width('100%')
  5760. .justifyContent(FlexAlign.Center)
  5761. .padding(20)
  5762. }
  5763. }
  5764. }
  5765. .onScrollStart(() => {
  5766. this.isScrolling = true
  5767. this.showAlphabetIndex()
  5768. })
  5769. .onScrollIndex((start: number,center:number,end:number) => {
  5770. this.selectedIndex = start
  5771. if(start >= 0 && start < this.videoLocalList.length){
  5772. this.selectAlphaBetIndex = this.findAlphaBetIndex(this.videoLocalList[start])
  5773. }
  5774. })
  5775. .onScrollStop(() => {
  5776. if(this.isScrolling){
  5777. this.isScrolling = false
  5778. }
  5779. this.hideAlphabetIndexAfterDelay(1500)
  5780. })
  5781. .onReachEnd(() => {
  5782. if(this.modeType === 4 )//歌单不能加载下一页
  5783. return;
  5784. // 触底加载下一页
  5785. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  5786. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  5787. return;
  5788. }
  5789. if (this.hasMoreData && !this.isLoadingPage) {
  5790. this.loadNextPage();
  5791. }
  5792. })
  5793. .scrollBar(BarState.Off)
  5794. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  5795. .gesture(PinchGesture({ fingers: 2 })
  5796. .onActionEnd((event: GestureEvent) => {
  5797. this.setlistTwoFingers()
  5798. })
  5799. .onActionUpdate(e => {
  5800. this.scaleValue = this.pinchValue * e.scale
  5801. })
  5802. .onActionStart(e => {
  5803. }))
  5804. .contentStartOffset(this.topSafeHeight + 55)
  5805. .scrollBar(BarState.Off)
  5806. .contentEndOffset(this.bottomBarHeight+this.bottomSafeHeight)
  5807. .cachedCount(10)
  5808. // .reuseId('list_item')
  5809. .borderRadius(20)
  5810. .layoutWeight(1)
  5811. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  5812. .lanes(
  5813. new BreakpointType<number>({
  5814. sm: 1,
  5815. md: 2,
  5816. lg: 2,
  5817. xl: 3,
  5818. xxl: 4
  5819. }).getValue(this.currentBreakpoint),
  5820. new BreakpointType<number>({
  5821. sm: 0,
  5822. md: 12,
  5823. lg: 12,
  5824. xl: 16,
  5825. xxl: 20
  5826. }).getValue(this.currentBreakpoint)
  5827. )
  5828. .onAreaChange((oldValue: Area, newValue: Area) => {
  5829. this.listArea = newValue
  5830. if (this.twoFingerType == 3) {
  5831. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  5832. } else if (this.twoFingerType == 2) {
  5833. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  5834. } else if (this.twoFingerType == 1) {
  5835. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  5836. }
  5837. })
  5838. .onScrollFrameBegin((offset: number) => {
  5839. // 获取当前滚动偏移量
  5840. if(this.autoHideTitle){
  5841. const currentOffsetY = this.listScroller.currentOffset().yOffset;
  5842. // 判断滚动方向
  5843. if (currentOffsetY > this.prevOffsetY) {
  5844. // console.log("onecold 向上滚动");
  5845. this.isShowTitleBar = false
  5846. } else if (currentOffsetY < this.prevOffsetY) {
  5847. // console.log("onecold 向下滚动");
  5848. this.isShowTitleBar = true
  5849. }
  5850. // 更新前一次偏移量
  5851. this.prevOffsetY = currentOffsetY;
  5852. }
  5853. return { offsetRemain: offset };
  5854. })
  5855. }
  5856. setBarHeightNormal() {
  5857. this.hideDone = false;
  5858. this.getUIContext().animateTo({
  5859. duration: 300
  5860. }, () => {
  5861. this.bottomBarHeight = 68 + 0;
  5862. this.topBarHeight = 50 + 0;
  5863. this.barOpacity = 1;
  5864. this.barBottomOpacity = 1
  5865. this.currentYOffset = 0;
  5866. this.isHiding = false;
  5867. });
  5868. }
  5869. setBarHeightHide(offset: number) {
  5870. if (offset > 0 && !this.hideDone) {
  5871. this.currentYOffset += offset;
  5872. if (this.currentYOffset <= 100) {
  5873. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  5874. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  5875. this.barOpacity = 1 - this.currentYOffset / 100;
  5876. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  5877. } else {
  5878. this.topBarHeight = 0;
  5879. this.bottomBarHeight = 0;
  5880. this.barBottomOpacity = 0
  5881. this.barOpacity = 0;
  5882. this.hideDone = true;
  5883. }
  5884. this.isHiding = true;
  5885. }
  5886. if (offset < 0 && this.isHiding) {
  5887. this.hideDone = false;
  5888. this.getUIContext().animateTo({
  5889. duration: 300
  5890. }, () => {
  5891. this.bottomBarHeight = 68 + 0;
  5892. this.topBarHeight = 50 + 0;
  5893. this.barOpacity = 1;
  5894. this.barBottomOpacity = 1
  5895. this.currentYOffset = 0;
  5896. this.isHiding = false;
  5897. });
  5898. }
  5899. }
  5900. //这个方法没隐藏bottomBar,只隐藏topbar
  5901. setBarHeightHide2(offset: number) {
  5902. if (offset > 0 && !this.hideDone) {
  5903. this.currentYOffset += offset;
  5904. if (this.currentYOffset <= 100) {
  5905. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  5906. this.barOpacity = 1 - this.currentYOffset / 100;
  5907. } else {
  5908. this.topBarHeight = 0;
  5909. this.barOpacity = 0;
  5910. this.hideDone = true;
  5911. }
  5912. this.isHiding = true;
  5913. }
  5914. if (offset < 0 && this.isHiding) {
  5915. this.hideDone = false;
  5916. this.getUIContext().animateTo({
  5917. duration: 300
  5918. }, () => {
  5919. this.topBarHeight = 50 + 0;
  5920. this.barOpacity = 1;
  5921. this.currentYOffset = 0;
  5922. this.isHiding = false;
  5923. });
  5924. }
  5925. }
  5926. private async doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean,isOpen?:boolean) {
  5927. Logger.info(`heanup doPlay被调用 - 歌曲: ${item.name}, 文件路径: ${item.filePath}, 索引: ${index}, 类型: ${item.type}, isFromSonPlayList: ${isFromSonPlayList}`)
  5928. switch (item.type) {
  5929. case CommonConstants.TYPE_IS_DIR:
  5930. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  5931. let offsetB = 0
  5932. if(this.twoFingerType==4){
  5933. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  5934. let cur = this.waterScroller.currentOffset()
  5935. if (cur && typeof cur.yOffset === 'number') {
  5936. offsetB = cur.yOffset
  5937. }
  5938. }
  5939. this.mScrollMap.set('lastWaterDirScrollOffset', offsetB)
  5940. }else
  5941. if (this.isGridMusic) {
  5942. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  5943. let cur = this.scroller.currentOffset()
  5944. if (cur && typeof cur.yOffset === 'number') {
  5945. offsetB = cur.yOffset
  5946. }
  5947. }
  5948. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  5949. } else {
  5950. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  5951. let cur = this.listScroller.currentOffset()
  5952. if (cur && typeof cur.yOffset === 'number') {
  5953. offsetB = cur.yOffset
  5954. }
  5955. }
  5956. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  5957. }
  5958. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  5959. this.showVerifyDialog()
  5960. this.currentTitleName = '私密音频'
  5961. this.currentTitleCover = $r('app.media.alt')
  5962. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  5963. this.titleName = '最近播放'
  5964. this.currentTitleCover = $r('app.media.alt')
  5965. this.currentTitleName = '最近播放'
  5966. //加载动画效果
  5967. this.updateListData(this.historyList, true)
  5968. // this.videoLocalList = this.historyList
  5969. if (ArrayUtil.isEmpty(this.historyList)) {
  5970. ToastUtil.showToast('最近播放记录空空如也')
  5971. } else {
  5972. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  5973. }
  5974. this.isHistory = true
  5975. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  5976. this.titleName = '我的收藏'
  5977. this.currentTitleName = '我的收藏'
  5978. this.currentTitleCover = $r('app.media.alt')
  5979. //加载动画效果
  5980. this.updateListData(this.favList, true)
  5981. if (ArrayUtil.isEmpty(this.favList)) {
  5982. ToastUtil.showToast('无音乐收藏记录')
  5983. } else {
  5984. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  5985. }
  5986. this.isFavMusic = true
  5987. } else {
  5988. this.currentTitleName = item.name
  5989. this.currentPath = item.filePath
  5990. this.currentTitleCover = $r('app.media.alt')
  5991. this.getSortedFiles(this.currentPath)
  5992. }
  5993. //进入歌单的时候的滚动位置在顶部
  5994. if(this.twoFingerType==4){
  5995. setTimeout(() => {
  5996. this.waterScroller.scrollEdge(Edge.Top)
  5997. this.scroller.scrollEdge(Edge.Top)
  5998. }, 200)
  5999. }else{
  6000. if (this.isGridMusic) {
  6001. this.scroller.scrollToIndex(0,false)
  6002. }else{
  6003. this.listScroller.scrollToIndex(0,false)
  6004. }
  6005. }
  6006. this.rightTopImage = $r('sys.symbol.chevron_left')
  6007. break;
  6008. case CommonConstants.TYPE_IS_ARTIST:
  6009. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  6010. let offsetA = 0
  6011. if(this.twoFingerType==4){
  6012. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6013. let cur = this.waterScroller.currentOffset()
  6014. if (cur && typeof cur.yOffset === 'number') {
  6015. offsetA = cur.yOffset
  6016. }
  6017. }
  6018. this.mScrollMap.set('lastWaterArtistScrollOffset', offsetA)
  6019. }else
  6020. if (this.isGridMusic) {
  6021. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6022. let cur = this.scroller.currentOffset()
  6023. if (cur && typeof cur.yOffset === 'number') {
  6024. offsetA = cur.yOffset
  6025. }
  6026. }
  6027. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  6028. } else {
  6029. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6030. let cur = this.listScroller.currentOffset()
  6031. if (cur && typeof cur.yOffset === 'number') {
  6032. offsetA = cur.yOffset
  6033. }
  6034. }
  6035. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  6036. }
  6037. let mList = this.artistMap.get(item.name)
  6038. if (mList === undefined || ArrayUtil.isEmpty(mList)) {
  6039. mList = await this.table.querySongsByArtist(item.name, this.sortType, this.isShowFileName);
  6040. if (ArrayUtil.isNotEmpty(mList)) {
  6041. this.artistMap.set(item.name, mList);
  6042. }
  6043. }
  6044. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  6045. Utility.doSortListAscending(mList)
  6046. const nextArtistCountMap = new Map(this.artistSongCountMap);
  6047. nextArtistCountMap.set(item.name, mList.length);
  6048. this.artistSongCountMap = nextArtistCountMap;
  6049. this.isCanBack = true
  6050. this.hasMoreData = false
  6051. this.isLoadingPage = false
  6052. this.pageCache.clear()
  6053. this.totalCount = mList.length
  6054. this.titleName = item.name
  6055. this.currentTitleName = '艺术家:' + item.name
  6056. if (item.pixelMapPath) {
  6057. this.currentTitleCover = item.pixelMapPath
  6058. }
  6059. this.updateListData(mList)
  6060. } else {
  6061. ToastUtil.showToast('未找到该艺术家的歌曲');
  6062. return;
  6063. }
  6064. this.rightTopImage = $r('sys.symbol.chevron_left')
  6065. //进入歌单的时候的滚动位置在顶部
  6066. if(this.twoFingerType==4){
  6067. setTimeout(() => {
  6068. this.waterScroller.scrollEdge(Edge.Top)
  6069. this.scroller.scrollEdge(Edge.Top)
  6070. }, 380)
  6071. }else{
  6072. if (this.isGridMusic) {
  6073. this.scroller.scrollEdge(Edge.Top)
  6074. }else{
  6075. this.listScroller.scrollEdge(Edge.Top)
  6076. }
  6077. }
  6078. break;
  6079. case CommonConstants.TYPE_IS_ALBUM:
  6080. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  6081. let offset = 0
  6082. if(this.twoFingerType==4){
  6083. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6084. let cur = this.waterScroller.currentOffset()
  6085. if (cur && typeof cur.yOffset === 'number') {
  6086. offset = cur.yOffset
  6087. }
  6088. }
  6089. this.mScrollMap.set('lastWaterAlBumScrollOffset', offset)
  6090. }else
  6091. if (this.isGridMusic) {
  6092. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6093. let cur = this.scroller.currentOffset()
  6094. if (cur && typeof cur.yOffset === 'number') {
  6095. offset = cur.yOffset
  6096. }
  6097. }
  6098. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  6099. } else {
  6100. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6101. let cur = this.listScroller.currentOffset()
  6102. if (cur && typeof cur.yOffset === 'number') {
  6103. offset = cur.yOffset
  6104. }
  6105. }
  6106. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  6107. }
  6108. let albumList = this.albumMap.get(item.name)
  6109. if (albumList === undefined || ArrayUtil.isEmpty(albumList)) {
  6110. albumList = await this.table.querySongsByAlbum(item.name, this.sortType, this.isShowFileName);
  6111. if (ArrayUtil.isNotEmpty(albumList)) {
  6112. this.albumMap.set(item.name, albumList);
  6113. }
  6114. }
  6115. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  6116. Utility.doSortListAscending(albumList)
  6117. const nextAlbumCountMap = new Map(this.albumSongCountMap);
  6118. nextAlbumCountMap.set(item.name, albumList.length);
  6119. this.albumSongCountMap = nextAlbumCountMap;
  6120. this.isCanBack = true
  6121. this.hasMoreData = false
  6122. this.isLoadingPage = false
  6123. this.pageCache.clear()
  6124. this.totalCount = albumList.length
  6125. this.titleName = item.name
  6126. this.currentTitleName = '专辑:' + item.name
  6127. if (item.pixelMapPath) {
  6128. this.currentTitleCover = item.pixelMapPath
  6129. }
  6130. this.updateListData(albumList)
  6131. this.mScrollMap.set(item.name, this.selectedIndex)
  6132. this.rightTopImage = $r('sys.symbol.chevron_left')
  6133. } else {
  6134. ToastUtil.showToast('未找到该专辑的歌曲');
  6135. return;
  6136. }
  6137. //进入歌单的时候的滚动位置在顶部
  6138. if(this.twoFingerType==4){
  6139. setTimeout(() => {
  6140. this.waterScroller.scrollEdge(Edge.Top)
  6141. this.scroller.scrollEdge(Edge.Top)
  6142. }, 380)
  6143. }else{
  6144. if (this.isGridMusic) {
  6145. this.scroller.scrollEdge(Edge.Top)
  6146. }else{
  6147. this.listScroller.scrollEdge(Edge.Top)
  6148. }
  6149. }
  6150. break;
  6151. case CommonConstants.TYPE_IS_CSJAD:
  6152. return
  6153. break;
  6154. case CommonConstants.TYPE_LOCAL:
  6155. if(item&&item.filePath.toLowerCase().endsWith('.cue')){
  6156. const cueinfo:CueInfo = await parseCueFile(item.filePath)
  6157. const cueTracks:CueTrack[] = cueinfo.tracks
  6158. console.log('onecold cue cueTracks =', JSON.stringify(cueTracks));
  6159. if(ArrayUtil.isNotEmpty(cueTracks)){
  6160. this.showCueDialog(cueTracks,cueinfo)
  6161. }
  6162. // this.showCueSheet = !this.showCueSheet
  6163. return
  6164. }
  6165. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6166. this.stop();
  6167. }
  6168. if (isOpen) {
  6169. this.currentSong = item
  6170. if (index !== undefined) {
  6171. this.curIndex = index
  6172. }
  6173. this.songList = []
  6174. this.songList.push(item)
  6175. this.sonDataSource.pushArrayData(this.songList)
  6176. this.playQueueScope = 'single'
  6177. }else if(isFromSonPlayList){ //点击来自右下角的播放列表
  6178. this.currentSong = item
  6179. if (index !== undefined) {
  6180. this.curIndex = index
  6181. }
  6182. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  6183. Logger.info(`heanup isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  6184. this.playQueueScope = 'playlist'
  6185. }else {
  6186. const globalVideoList = this.buildPlayQueueFromView();
  6187. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  6188. if (this.curIndex < 0) {
  6189. globalVideoList.push(item);
  6190. this.curIndex = globalVideoList.length - 1;
  6191. }
  6192. this.songList = globalVideoList
  6193. this.sonDataSource.pushArrayData(this.songList)
  6194. this.currentSong = this.songList[this.curIndex]
  6195. Logger.info(`heanup doPlay设置播放列表 - 总歌曲数: ${this.songList.length}, 当前索引: ${this.curIndex}, 当前歌曲: ${this.currentSong?.name}`)
  6196. }
  6197. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  6198. this.videoUrl = this.currentSong.filePath
  6199. this.name = this.currentSong.name
  6200. this.cover = this.currentSong.pixelMapPath
  6201. this.artist = this.currentSong.artist
  6202. LogUtil.info('onecold this.currentSong.cover =' + this.currentSong.pixelMapPath)
  6203. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  6204. this.startPlayOrResumePlay()
  6205. break;
  6206. case CommonConstants.TYPE_WEBDAV:
  6207. case CommonConstants.TYPE_SMB:
  6208. case CommonConstants.TYPE_NAVIDROME:
  6209. case CommonConstants.TYPE_FTP:
  6210. case CommonConstants.TYPE_BAIDU:
  6211. case CommonConstants.TYPE_JELLYFIN:
  6212. case CommonConstants.TYPE_EMBY:
  6213. case CommonConstants.TYPE_AUDIOSTATION:
  6214. case CommonConstants.TYPE_PLEX:
  6215. // 处理网络音频播放(WebDAV/SMB/Navidrome/Jellyfin/Emby/AudioStation/Plex/Baidu)
  6216. Logger.info(`heanup 处理云端音频播放: ${item.name}, URL: ${item.filePath}`)
  6217. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6218. this.stop();
  6219. }
  6220. if (isOpen) {
  6221. this.currentSong = item
  6222. if (index !== undefined) {
  6223. this.curIndex = index
  6224. }
  6225. this.songList = []
  6226. this.songList.push(item)
  6227. this.sonDataSource.pushArrayData(this.songList)
  6228. } else if (isFromSonPlayList) {
  6229. // 点击来自右下角的播放列表
  6230. this.currentSong = item
  6231. if (index !== undefined) {
  6232. this.curIndex = index
  6233. }
  6234. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  6235. Logger.info(`heanup 网络音频 isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  6236. } else {
  6237. // 从全局网络音频列表中查找
  6238. let globalVideoList = this.videoLocalList.filter(video => isRemoteCloudType(video.type)) as VideoItem[];
  6239. this.curIndex = globalVideoList.findIndex(video => video.filePath === item.filePath);
  6240. if (this.curIndex === -1 && index !== undefined) {
  6241. this.curIndex = index;
  6242. }
  6243. this.songList = globalVideoList.length > 0 ? globalVideoList : [item];
  6244. this.currentSong = this.songList[this.curIndex];
  6245. this.sonDataSource.pushArrayData(this.songList)
  6246. }
  6247. await this.hydrateRemoteSongFromDb(this.currentSong);
  6248. await this.hydrateRemoteSongFromDb(this.currentSong);
  6249. AppStorage.setOrCreate('currentSong', this.currentSong);
  6250. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  6251. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  6252. context: this.context,
  6253. autoParseMusicName: this.autoParseMusicName
  6254. });
  6255. Logger.info(TAG, `WebDAV URL同步构建完成(分支2): ${this.videoUrl}`);
  6256. this.name = this.currentSong.name
  6257. this.cover = this.currentSong.pixelMapPath
  6258. this.artist = this.currentSong.artist
  6259. Logger.info(`heanup 准备播放网络音频 - 歌名: ${this.name}, 艺术家: ${this.artist}, 完整URL: ${this.videoUrl}`)
  6260. this.startPlayOrResumePlay()
  6261. break;
  6262. }
  6263. }
  6264. private cueComponentId: number = 0
  6265. //显示cue分轨列表对话框
  6266. showCueDialog(cueTracks:CueTrack[],cueinfo:CueInfo){
  6267. this.getUIContext().getPromptAction().openCustomDialog({
  6268. builder: () => {
  6269. this.cueComptentBuilder(cueTracks,cueinfo)
  6270. },
  6271. isModal:true,
  6272. showInSubWindow:false,
  6273. maskColor: Color.Transparent,
  6274. dialogTransition: // 设置弹窗内容显示的过渡效果
  6275. TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  6276. .animation({ duration: 600, curve: Curve.Smooth }),
  6277. maskTransition: // 设置蒙层显示的过渡效果
  6278. TransitionEffect.opacity(0.5)
  6279. .animation({ duration: 600, curve: Curve.Smooth })
  6280. }).then((dialogId: number) => {
  6281. this.cueComponentId = dialogId
  6282. })
  6283. .catch((error: BusinessError) => {
  6284. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  6285. })
  6286. }
  6287. @Builder
  6288. cueComptentBuilder(cueTracks:CueTrack[]=[],cueinfo:CueInfo){
  6289. CueComptent({
  6290. title:cueinfo.title,
  6291. cueTracks:cueTracks,
  6292. isLongNameRoLL:this.isLongNameRoLL,
  6293. onCancel:()=>{
  6294. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId)
  6295. },
  6296. onDoItemClick: async (item: CueTrack, index: number)=>{
  6297. //获取cueinfo对应的filePath
  6298. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  6299. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, cueinfo.filePath)
  6300. this.currentSong = Utility.getItemByFilePath(globalVideoList, cueinfo.filePath)
  6301. console.info('onecold cueinfo.filePath=', cueinfo.filePath)
  6302. console.info('onecold this.currentSong =', JSON.stringify(this.currentSong))
  6303. if (this.currentSong){
  6304. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6305. this.stop();//播放之前先停止之前播放。
  6306. }
  6307. this.songList = globalVideoList
  6308. this.sonDataSource.pushArrayData(this.songList)
  6309. if (this.currentSong) {
  6310. try {
  6311. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  6312. context: this.context,
  6313. autoParseMusicName: this.autoParseMusicName
  6314. });
  6315. } catch (error) {
  6316. Logger.error(TAG, `CUE 点播构建播放地址失败: ${(error as Error).message}`);
  6317. this.videoUrl = this.currentSong.filePath;
  6318. }
  6319. }
  6320. this.name = item.title||this.currentSong.name
  6321. this.cover = this.currentSong.pixelMapPath
  6322. this.artist = item.performer||this.currentSong.artist
  6323. this.currentSong.name = this.name
  6324. this.currentSong.artist = this.artist
  6325. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  6326. this.startPlayOrResumePlay(item.startOffset)//从cue的某个位置开始播放
  6327. }
  6328. }
  6329. })
  6330. }
  6331. @State isFrontWhite: boolean = false
  6332. setShowPlayTrue(){
  6333. this.getUIContext()?.animateTo({
  6334. duration: 500,
  6335. curve: Curve.Friction
  6336. }, () => {
  6337. this.isShowPlay = true;
  6338. });
  6339. }
  6340. setShowPlayFalse(){
  6341. this.getUIContext()?.animateTo({
  6342. duration: 500,
  6343. curve: Curve.Friction
  6344. }, () => {
  6345. this.isShowPlay = false;
  6346. });
  6347. }
  6348. //打开播放页
  6349. showPlayerView() {
  6350. console.info('onecold showPlayerView this.songList'+ JSON.stringify(this.songList))
  6351. if (ArrayUtil.isNotEmpty(this.songList)) {
  6352. // this.setShowPlayTrue()
  6353. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
  6354. this.initLyric(lyricPath);
  6355. this.startAutoHide();
  6356. } else {
  6357. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  6358. }
  6359. }
  6360. //打开播放列表
  6361. openPlayList(){
  6362. if (ArrayUtil.isNotEmpty(this.songList)) {
  6363. this.isShowSheet = !this.isShowSheet;
  6364. this.isFrontWhite = false
  6365. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  6366. this.scrollIndex()
  6367. void this.hydrateFullMediaPlayListIfNeeded();
  6368. } else {
  6369. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  6370. }
  6371. }
  6372. scrollIndex(){
  6373. try {
  6374. setTimeout(() => {
  6375. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  6376. if(this.curIndex>60){
  6377. this.playListScroller.scrollToIndex(this.curIndex,false, ScrollAlign.CENTER)
  6378. }else{
  6379. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  6380. }
  6381. })
  6382. }, 123)
  6383. }catch (error) {
  6384. console.error(`onecold scrollIndex出错: ${error}`);
  6385. }
  6386. }
  6387. scrollIndexMain(dialogId?:string){
  6388. try {
  6389. setTimeout(() => {
  6390. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  6391. console.info('heanup scrollIndexMain this.curIndex='+this.curIndex)
  6392. if(dialogId)
  6393. DialogHelper.closeDialog(dialogId)
  6394. let isAni:boolean = false
  6395. if(this.curIndex<50){
  6396. isAni = true
  6397. }
  6398. if(this.twoFingerType==4){
  6399. this.waterScroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  6400. }else{
  6401. if(this.isGridMusic){
  6402. this.scroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  6403. }else{
  6404. this.listScroller.scrollToIndex(this.curIndex,isAni, ScrollAlign.CENTER)
  6405. }
  6406. }
  6407. })
  6408. }, 123)
  6409. }catch (error) {
  6410. console.error(`onecold scrollIndexMain出错: ${error}`);
  6411. }
  6412. }
  6413. // 智能定位当前播放歌曲,如果当前页没有则加载完整列表
  6414. async locateCurrentSong(): Promise<void> {
  6415. if (!this.currentSong) {
  6416. console.warn("heanup locateCurrentSong: 当前没有播放的歌曲");
  6417. return;
  6418. }
  6419. // 检查当前播放歌曲是否在已加载的列表中
  6420. const targetIndex = Utility.getIndexFromList(this.videoLocalList, this.currentSong.filePath);
  6421. if (targetIndex > 0) {
  6422. // 歌曲在当前列表中,直接滚动
  6423. console.info("heanup locateCurrentSong: 找到歌曲,索引=" + targetIndex);
  6424. this.curIndex = targetIndex;
  6425. this.scrollIndexMain();
  6426. } else {
  6427. // 歌曲不在当前列表中,加载当前歌曲再第几页完整列表后再定位
  6428. console.info("heanup locateCurrentSong: 歌曲不在当前列表,开始加载完整列表");
  6429. const dialogID = DialogHelper.showLoadingDialog()
  6430. await this.hydrateFullMediaPlayListIfNeeded(false);
  6431. this.curIndex = Utility.getIndexFromList(this.videoLocalList, this.currentSong.filePath);
  6432. this.scrollIndexMain(dialogID);
  6433. }
  6434. }
  6435. //播放列表布局
  6436. @Builder
  6437. PlayListSheet() {
  6438. Column() {
  6439. this.PlayList()
  6440. }
  6441. .width('100%')
  6442. .height('100%')
  6443. }
  6444. @State titleStr: string = ''
  6445. @State ablumStr: string = ''
  6446. @State artistStr: string = ''
  6447. @State lyricConStr: string = ''
  6448. @State currentEditItem: string = ''
  6449. @State yearStr: string = ''
  6450. @State trackStr: string = ''
  6451. @State genreStr: string = ''
  6452. @State imagePathStr: string = ''
  6453. @State albumArtistStr: string = ''
  6454. @State composerStr: string = ''
  6455. @State lyricistStr: string = ''
  6456. @State commentStr: string = ''
  6457. @State discStr: string = ''
  6458. doUpdateData() {
  6459. setTimeout(async () => {
  6460. if (this.modeType === 0) {
  6461. this.deleteCache(this.currentPath)
  6462. await this.resetAndLoadFirstPage();
  6463. }else if (this.modeType === 1){
  6464. await this.resetAndLoadFirstPage();
  6465. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6466. }
  6467. }, 500)
  6468. }
  6469. doAllUpdateData() {
  6470. setTimeout(async () => {
  6471. if (this.modeType === 0) {
  6472. this.deleteCache(this.currentPath)
  6473. await this.resetAndLoadFirstPage();
  6474. }else{
  6475. await this.resetAndLoadFirstPage();
  6476. }
  6477. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6478. workerInstance.postMessage({ code: 3, data: this.context });
  6479. workerInstance.postMessage({ code: 4, data: this.context });
  6480. }, 999)
  6481. }
  6482. /**
  6483. * 加载指定页的数据
  6484. */
  6485. private async loadPage(pageIndex: number, append: boolean = true): Promise<void> {
  6486. try {
  6487. // 1. 检查缓存
  6488. if (this.pageCache.has(pageIndex)) {
  6489. Logger.info('heanup LocalMusic', `loadPage: 从缓存加载 page=${pageIndex}`);
  6490. const cachedData = this.pageCache.get(pageIndex)!;
  6491. if (append) {
  6492. this.videoLocalList = [...this.videoLocalList, ...cachedData];
  6493. } else {
  6494. this.videoLocalList = cachedData;
  6495. }
  6496. this.dataSource.pushArrayData(this.videoLocalList);
  6497. return;
  6498. }
  6499. this.isLoadingPage = true;
  6500. Logger.info('heanup LocalMusic', `loadPage: 开始加载 page=${pageIndex}, size=${this.pageSize}, mode=${this.modeType}`);
  6501. // 2. 构造查询参数
  6502. const options: PageQueryOptions = {
  6503. pageIndex: pageIndex,
  6504. pageSize: this.pageSize,
  6505. sortType: this.sortType,
  6506. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  6507. isShowFileName: this.isShowFileName
  6508. };
  6509. // 根据 modeType 补充查询条件
  6510. if (this.modeType === 0) {
  6511. options.parentPath = this.currentPath;
  6512. }
  6513. // 3. 执行查询
  6514. let result: PageQueryResult = { items: [], totalCount: 0, hasMore: false };
  6515. switch (this.modeType) {
  6516. case 0:
  6517. result = await this.table.queryByParentPathPaged(options);
  6518. // modeType=0时,第一页需要添加文件夹列表
  6519. if (pageIndex === 0 && !this.isSearchMode) {
  6520. const directories: VideoItem[] = await this.loadDirectories(this.currentPath);
  6521. result.items = [...directories, ...result.items];
  6522. result.totalCount += directories.length;
  6523. }
  6524. break;
  6525. case 1:
  6526. result = await this.table.queryMediaLibraryPaged(options);
  6527. break;
  6528. case 2:
  6529. result = await this.table.queryArtistsPaged(options);
  6530. break;
  6531. case 3:
  6532. result = await this.table.queryAlbumsPaged(options);
  6533. break;
  6534. default:
  6535. result = await this.table.queryMediaLibraryPaged(options);
  6536. break;
  6537. }
  6538. if (!result || result.items.length === 0) {
  6539. Logger.info('heanup LocalMusic', 'loadPage: 查询结果为空');
  6540. this.isLoadingPage = false;
  6541. this.hasMoreData = false;
  6542. // 即使为空也要更新UI,显示空状态
  6543. this.totalCount = 0;
  6544. this.videoLocalList = [];
  6545. this.dataSource.pushArrayData(this.videoLocalList);
  6546. this.setButtonStatus();
  6547. return;
  6548. }
  6549. // 4. 更新状态和缓存
  6550. this.totalCount = result.totalCount;
  6551. this.hasMoreData = result.hasMore;
  6552. if (this.modeType === 1) {
  6553. this.mediaKuCount = result.totalCount;
  6554. }
  6555. if (this.modeType === 2 && result.countMap) {
  6556. this.mergeArtistCountMap(result.countMap);
  6557. } else if (this.modeType === 3 && result.countMap) {
  6558. this.mergeAlbumCountMap(result.countMap);
  6559. }
  6560. Logger.info('heanup LocalMusic', `loadPage: 查询完成 items=${result.items.length}, total=${result.totalCount}, hasMore=${result.hasMore}`);
  6561. // 缓存管理 - 只保留最近3页
  6562. this.pageCache.set(pageIndex, result.items);
  6563. this.cleanOldCache(pageIndex);
  6564. // 5. 更新显示列表
  6565. if (append) {
  6566. this.videoLocalList = [...this.videoLocalList, ...result.items];
  6567. } else {
  6568. this.videoLocalList = result.items;
  6569. }
  6570. this.dataSource.pushArrayData(this.videoLocalList);
  6571. this.setButtonStatus();
  6572. this.setAlphaBet();
  6573. void this.prefetchNextPage(pageIndex + 1);
  6574. this.isLoadingPage = false;
  6575. } catch (err) {
  6576. const error = err as Error;
  6577. Logger.error('heanup LocalMusic', `loadPage error: ${error.message}`);
  6578. ToastUtil.showToast('加载数据失败');
  6579. this.isLoadingPage = false;
  6580. this.hasMoreData = false;
  6581. }
  6582. }
  6583. /**
  6584. * 清理旧缓存 - 只保留当前页前后各1页
  6585. */
  6586. private cleanOldCache(currentPage: number): void {
  6587. const pagesToKeep = new Set([currentPage - 1, currentPage, currentPage + 1]);
  6588. const keysToDelete: number[] = [];
  6589. this.pageCache.forEach((_, page) => {
  6590. if (!pagesToKeep.has(page)) {
  6591. keysToDelete.push(page);
  6592. }
  6593. });
  6594. keysToDelete.forEach(page => this.pageCache.delete(page));
  6595. if (keysToDelete.length > 0) {
  6596. Logger.info('heanup LocalMusic', `cleanOldCache: 清理了 ${keysToDelete.length} 页缓存`);
  6597. }
  6598. }
  6599. private async prefetchNextPage(nextPage: number): Promise<void> {
  6600. if (this.modeType !== 2 && this.modeType !== 3) {
  6601. return;
  6602. }
  6603. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  6604. return;
  6605. }
  6606. if (!this.hasMoreData || this.pageCache.has(nextPage) || this.prefetchingPages.has(nextPage)) {
  6607. return;
  6608. }
  6609. this.prefetchingPages.add(nextPage);
  6610. try {
  6611. const options: PageQueryOptions = {
  6612. pageIndex: nextPage,
  6613. pageSize: this.pageSize,
  6614. sortType: this.sortType,
  6615. searchKeyword: this.isSearchMode ? this.searchText : undefined,
  6616. isShowFileName: this.isShowFileName
  6617. };
  6618. let result: PageQueryResult = { items: [], totalCount: 0, hasMore: false };
  6619. if (this.modeType === 2) {
  6620. result = await this.table.queryArtistsPaged(options);
  6621. if (result.countMap) {
  6622. this.mergeArtistCountMap(result.countMap);
  6623. }
  6624. } else if (this.modeType === 3) {
  6625. result = await this.table.queryAlbumsPaged(options);
  6626. if (result.countMap) {
  6627. this.mergeAlbumCountMap(result.countMap);
  6628. }
  6629. }
  6630. if (result.items.length > 0) {
  6631. this.pageCache.set(nextPage, result.items);
  6632. this.cleanOldCache(nextPage);
  6633. }
  6634. } catch (err) {
  6635. const error = err as Error;
  6636. Logger.warn('heanup LocalMusic', `prefetchNextPage error: ${error.message}`);
  6637. } finally {
  6638. this.prefetchingPages.delete(nextPage);
  6639. }
  6640. }
  6641. private mergeArtistCountMap(countMap: Map<string, number>): void {
  6642. const nextMap = new Map(this.artistSongCountMap);
  6643. countMap.forEach((count, artist) => {
  6644. nextMap.set(artist, count);
  6645. });
  6646. this.artistSongCountMap = nextMap;
  6647. }
  6648. private mergeAlbumCountMap(countMap: Map<string, number>): void {
  6649. const nextMap = new Map(this.albumSongCountMap);
  6650. countMap.forEach((count, album) => {
  6651. nextMap.set(album, count);
  6652. });
  6653. this.albumSongCountMap = nextMap;
  6654. }
  6655. private getArtistSongCount(artist: string): number {
  6656. return this.artistSongCountMap.get(artist) ?? this.artistMap.get(artist)?.length ?? 0;
  6657. }
  6658. private getAlbumSongCount(album: string): number {
  6659. return this.albumSongCountMap.get(album) ?? this.albumMap.get(album)?.length ?? 0;
  6660. }
  6661. /**
  6662. * 加载文件夹列表(仅用于modeType=0的首页模式)
  6663. */
  6664. private async loadDirectories(curPath: string): Promise<VideoItem[]> {
  6665. try {
  6666. Logger.info('heanup LocalMusic', `loadDirectories: 开始加载文件夹 path=${curPath}`);
  6667. // 检查缓存
  6668. const cacheKey = curPath + "_dirList";
  6669. const cachedDirList = this.findCache(cacheKey);
  6670. if (cachedDirList !== undefined && Array.isArray(cachedDirList)) {
  6671. Logger.info('heanup LocalMusic', `loadDirectories: 从缓存加载 count=${cachedDirList.length}`);
  6672. return cachedDirList as VideoItem[];
  6673. }
  6674. // 从文件系统读取
  6675. const fileList = FileUtil.listFileSync(curPath);
  6676. const directories: VideoItem[] = [];
  6677. for (let i = 0; i < fileList.length; i++) {
  6678. const path = curPath + '/' + fileList[i];
  6679. if (FileUtil.isDirectory(path)) {
  6680. const item: VideoItem = new VideoItem(
  6681. fileList[i].toString(),
  6682. fileList[i].toString(),
  6683. path,
  6684. CommonConstants.TYPE_IS_DIR,
  6685. 0,
  6686. ''
  6687. );
  6688. if (this.isShowDir(item.name)) {
  6689. directories.push(item);
  6690. }
  6691. }
  6692. }
  6693. // 排序
  6694. Utility.doSortListAscending(directories);
  6695. // 缓存文件夹列表
  6696. if (curPath === this.rootPath) {
  6697. this.dirList = directories;
  6698. this.addCache(cacheKey, directories);
  6699. }
  6700. Logger.info('heanup LocalMusic', `loadDirectories: 加载完成 count=${directories.length}`);
  6701. return directories;
  6702. } catch (err) {
  6703. const error = err as Error;
  6704. Logger.error('heanup LocalMusic', `loadDirectories error: ${error.message}`);
  6705. return [];
  6706. }
  6707. }
  6708. /**
  6709. * 构建播放队列(避免一次性加载全量)
  6710. */
  6711. private buildPlayQueueFromView(): Array<VideoItem> {
  6712. if (this.modeType === 4) {
  6713. this.playQueueScope = 'playlist';
  6714. return this.currentSongList;
  6715. }
  6716. if (this.isHistory) {
  6717. this.playQueueScope = 'history';
  6718. return this.historyList;
  6719. }
  6720. if (this.isFavMusic) {
  6721. this.playQueueScope = 'fav';
  6722. return this.favList;
  6723. }
  6724. this.playQueueScope = 'view';
  6725. return this.videoLocalList.filter((item: VideoItem) => item.type === CommonConstants.TYPE_LOCAL);
  6726. }
  6727. private async tryLoadNextPageForPlayback(): Promise<void> {
  6728. if (this.playQueueScope !== 'view') {
  6729. return;
  6730. }
  6731. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  6732. return;
  6733. }
  6734. if (!this.hasMoreData || this.isLoadingPage) {
  6735. return;
  6736. }
  6737. await this.loadNextPage();
  6738. const nextList = this.videoLocalList.filter((item: VideoItem) => item.type === CommonConstants.TYPE_LOCAL);
  6739. if (nextList.length > this.songList.length) {
  6740. this.songList = nextList;
  6741. this.sonDataSource.pushArrayData(this.songList);
  6742. }
  6743. }
  6744. /**
  6745. * 重置分页状态并加载首页
  6746. */
  6747. private async resetAndLoadFirstPage(): Promise<void> {
  6748. Logger.info('heanup LocalMusic', 'resetAndLoadFirstPage: 重置分页状态');
  6749. this.currentPage = 0;
  6750. this.videoLocalList = [];
  6751. this.pageCache.clear();
  6752. this.hasMoreData = true;
  6753. this.totalCount = 0;
  6754. if (this.modeType === 2) {
  6755. this.artistSongCountMap = new Map();
  6756. } else if (this.modeType === 3) {
  6757. this.albumSongCountMap = new Map();
  6758. }
  6759. await this.loadPage(0, false);
  6760. }
  6761. /**
  6762. * 加载下一页
  6763. */
  6764. private async loadNextPage(): Promise<void> {
  6765. if (this.hasMoreData && !this.isLoadingPage) {
  6766. this.currentPage++;
  6767. Logger.info('heanup LocalMusic', `loadNextPage: 加载第 ${this.currentPage} 页`);
  6768. await this.loadPage(this.currentPage, true);
  6769. }
  6770. }
  6771. //编辑信息
  6772. async doEdit(item: VideoItem) {
  6773. if (!item) {
  6774. return
  6775. }
  6776. if (StrUtil.isEmpty(this.titleStr)) {
  6777. ToastUtil.showToast('标题不能为空')
  6778. return
  6779. }
  6780. //内嵌音乐标签不能开启监听
  6781. // this.deletionWatcher?.stop();
  6782. this.loadingDialogId = DialogHelper.showLoadingDialog()
  6783. await PermissionUtil.activatePermission(item.filePath)
  6784. let tempOutPath = ''
  6785. // 如果不是 packName 包下的文件,则直接路径用this.currentPath
  6786. if(!item.filePath.toLowerCase().includes(this.packName)){
  6787. tempOutPath = this.currentPath + '/' + item.fileName
  6788. }
  6789. console.info('onecold tempOutPath ='+tempOutPath)
  6790. //用户更改了封面,那就内嵌下封面
  6791. if(StrUtil.isNotEmpty(this.imagePathStr)){
  6792. const resultCover:boolean = await changeMusicCover(this.context,
  6793. item.filePath,this.imagePathStr,true,tempOutPath);
  6794. this.imagePathStr = ''
  6795. if(resultCover){
  6796. ToastUtil.showToast('内嵌封面成功')
  6797. }
  6798. }
  6799. const metadata:FFMpegTags = {
  6800. title: this.titleStr,
  6801. artist: this.artistStr,
  6802. album: this.ablumStr,
  6803. TYER:this.yearStr,
  6804. genre:this.genreStr,
  6805. track:this.trackStr,
  6806. album_artist:this.albumArtistStr,
  6807. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  6808. COMPOSER:this.composerStr,
  6809. lyricist:this.lyricistStr,
  6810. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  6811. comment:this.commentStr,
  6812. disc:this.discStr,
  6813. };
  6814. let newInput = item.filePath
  6815. //内嵌标签歌路径如果不是包含包名,输入newInput要赋值tempOutPath,然后tempOutPath为空
  6816. if(!item.filePath.toLowerCase().includes(this.packName)&&FileUtil.accessSync(tempOutPath)){
  6817. newInput = tempOutPath
  6818. tempOutPath = ''
  6819. }
  6820. const isWav:boolean = newInput.toLowerCase().endsWith('.wav');
  6821. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  6822. const result:boolean = await repairAudioMetadata(
  6823. newInput,
  6824. this.lyricConStr,
  6825. metadata,
  6826. true,
  6827. tempOutPath
  6828. );
  6829. if (result||isWav) {
  6830. if(!item.filePath.includes(this.packName)){
  6831. //内嵌成功的歌路径如果不是包含包名,则要入库
  6832. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newInput,
  6833. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  6834. this.table.insert(newItem, (id: number) => {
  6835. //加入数据库
  6836. if(this.modeType==0){
  6837. this.deleteCache(this.currentPath)
  6838. this.getSortedFiles(this.currentPath)
  6839. }
  6840. });
  6841. }
  6842. const task = new taskpool.Task(
  6843. updateInfoDb,
  6844. this.context,
  6845. item.filePath,
  6846. this.titleStr,
  6847. this.artistStr,
  6848. this.ablumStr,
  6849. this.lyricConStr,
  6850. this.yearStr,this.genreStr,
  6851. this.trackStr,this.albumArtistStr,
  6852. this.composerStr, this.lyricistStr,
  6853. this.commentStr,this.discStr
  6854. );
  6855. taskpool.execute(task, taskpool.Priority.HIGH).then((result) => {
  6856. if (result) {
  6857. console.log(" onecold 编辑信息成功,数据库已同步");
  6858. if(isWav){
  6859. ToastUtil.showToast('wav格式有可能内嵌失败,但是编辑信息成功')
  6860. }else{
  6861. ToastUtil.showToast('内嵌音乐标签成功')
  6862. }
  6863. this.isShowMoreView = false
  6864. this.name = this.titleStr
  6865. this.syncEditedFields(item)
  6866. if (item.filePath == this.currentSong?.filePath) {
  6867. this.currentSong.name = this.titleStr
  6868. this.artist = this.artistStr
  6869. this.currentSong.artist = this.artistStr
  6870. this.currentSong.album = this.ablumStr
  6871. this.currentSong.year = this.yearStr
  6872. this.currentSong.genre = this.genreStr
  6873. this.currentSong.track = this.trackStr
  6874. this.currentSong.lyricContent = this.lyricConStr
  6875. this.currentSong.ALBUMARTIST = this.albumArtistStr
  6876. this.currentSong.COMPOSER = this.composerStr
  6877. this.currentSong.LYRICIST = this.lyricistStr
  6878. this.currentSong.COMMENT = this.commentStr
  6879. }
  6880. this.syncListsAfterEdit(item.filePath)
  6881. this.doUpateEditedFields(item)
  6882. //this.doUpdateData()
  6883. } else {
  6884. // ToastUtil.showToast('保存失败' + error?.toString())
  6885. console.error(" onecold 编辑信息数据库失败 ");
  6886. }
  6887. // 关闭进度条
  6888. DialogHelper.closeDialog(this.loadingDialogId)
  6889. }).catch((error: Error) => {
  6890. // 关闭进度条
  6891. DialogHelper.closeDialog(this.loadingDialogId)
  6892. console.error('onecold Subtitle sync failed:', error);
  6893. });
  6894. console.log(' onecold 元数据标签更新成功,');
  6895. } else {
  6896. // 关闭进度条
  6897. DialogHelper.closeDialog(this.loadingDialogId)
  6898. ToastUtil.showToast('内嵌音乐标签失败')
  6899. console.log('onecold 内嵌音乐标签失败');
  6900. }
  6901. this.longItemFilePath = ''
  6902. this.tempLyricContent = ''
  6903. this.isShowEdit = false
  6904. }
  6905. // 内嵌标签更新当前内嵌的Item
  6906. async doUpateEditedFields(item: VideoItem) {
  6907. // 找到当前项在 videoLocalList 中的索引
  6908. const index = this.videoLocalList.findIndex(video => video.filePath === item.filePath);
  6909. if (index !== -1) {
  6910. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  6911. const updatedItem = await this.table.queryVideoByFilePath(item.filePath)
  6912. // 只有当查询结果不为 null 时才更新列表
  6913. if (updatedItem !== null) {
  6914. // 更新 videoLocalList 中的项(通过创建新数组触发响应式更新)
  6915. this.videoLocalList = [
  6916. ...this.videoLocalList.slice(0, index),
  6917. updatedItem,
  6918. ...this.videoLocalList.slice(index + 1)
  6919. ];
  6920. // 同步更新 LazyDataSource
  6921. this.dataSource.pushArrayData(this.videoLocalList)
  6922. } else {
  6923. ToastUtil.showToast('未找到更新的数据');
  6924. }
  6925. }
  6926. DialogHelper.closeDialog(this.loadingDialogId)
  6927. }
  6928. @Builder
  6929. editSheet(item: VideoItem) {
  6930. Scroll() {
  6931. Column() {
  6932. this.editDetail(item)
  6933. }
  6934. }
  6935. .width('100%')
  6936. .height('100%')
  6937. }
  6938. @Builder
  6939. editDetail(item: VideoItem) {
  6940. Column() {
  6941. if (item) {
  6942. Row() {
  6943. Stack() {
  6944. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  6945. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  6946. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
  6947. item.pixelMapPath)
  6948. .fillColor(this.themeColor)
  6949. .height(88)
  6950. .width(88)
  6951. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  6952. .borderRadius(12)
  6953. .clip(true)
  6954. .opacity(this.opacityItem)// 绑定透明度
  6955. .margin({ left: 25 })
  6956. }
  6957. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  6958. .onClick(async () => {
  6959. const imagePath:string | undefined = await this.goSelectImage(item);
  6960. if (imagePath) {
  6961. //用户更改过图片
  6962. this.imagePathStr = imagePath
  6963. }
  6964. })
  6965. .width('28%')
  6966. Row() {
  6967. Column() {
  6968. Text(item.name)
  6969. .fontSize(17)
  6970. .maxLines(1)
  6971. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6972. .animation({
  6973. duration: 555,
  6974. curve: 'Linear',
  6975. })
  6976. .fontColor(this.themeColor)
  6977. .margin({ left: 8 })
  6978. Row() {
  6979. Text(item.artist)
  6980. .fontSize(14)
  6981. .maxLines(1)
  6982. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6983. .padding({ top: 8 })
  6984. .fontColor(this.themeColor)
  6985. .margin({ left: 8 })
  6986. }
  6987. }
  6988. .height('100%')
  6989. .width(100)
  6990. .layoutWeight(1)
  6991. .justifyContent(FlexAlign.Center)
  6992. .alignItems(HorizontalAlign.Start)
  6993. Column() {
  6994. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6995. Row(){
  6996. SymbolGlyph($r('sys.symbol.picture'))
  6997. .fontSize(18)
  6998. .fontColor([Color.White])
  6999. Text('获取封面')
  7000. .margin({ left: 4 })
  7001. .fontSize(11)
  7002. .fontColor(Color.White)
  7003. .fontWeight(480)
  7004. .textAlign(TextAlign.Center)
  7005. }
  7006. .justifyContent(FlexAlign.Center)
  7007. }
  7008. .height(38)
  7009. .width(100)
  7010. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7011. .backgroundColor(this.themeColor)
  7012. .stateEffect(true)
  7013. .margin({ right: 35 })
  7014. .onClick(async () => {
  7015. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  7016. this.showTipsDialog();
  7017. return; // Return empty string when no API is configured
  7018. }
  7019. const imagePath:string | undefined = await this.doSearchCover(item,
  7020. this.titleStr,this.artistStr);
  7021. console.info('onecold imagePath = '+imagePath)
  7022. if (StrUtil.isNotEmpty(imagePath)) {
  7023. //用户更改过图片
  7024. this.imagePathStr = imagePath
  7025. ToastUtil.showToast('获取封面成功')
  7026. }else{
  7027. ToastUtil.showToast('获取封面失败,请重试')
  7028. }
  7029. })
  7030. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7031. Row(){
  7032. SymbolGlyph($r('sys.symbol.input_mode'))
  7033. .fontSize(18)
  7034. .fontColor([Color.White])
  7035. Text('获取歌词')
  7036. .margin({ left: 4 })
  7037. .fontSize(11)
  7038. .fontColor(Color.White)
  7039. .fontWeight(480)
  7040. .textAlign(TextAlign.Center)
  7041. }
  7042. .justifyContent(FlexAlign.Center)
  7043. }
  7044. .height(38)
  7045. .width(100)
  7046. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7047. .backgroundColor(this.themeColor)
  7048. .stateEffect(true)
  7049. .margin({ top: 9, right: 35 })
  7050. .onClick(async () => {
  7051. //判断有没有设置api
  7052. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  7053. if (StrUtil.isEmpty(apiUrl)) {
  7054. this.isLyricSetting = false
  7055. this.showTipsDialog()
  7056. return
  7057. }
  7058. let res: string | undefined = await getApiLyric(apiUrl,
  7059. this.titleStr, this.artistStr, false);
  7060. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  7061. this.lyricConStr = res;
  7062. ToastUtil.showToast('获取歌词成功')
  7063. }else{
  7064. ToastUtil.showToast('获取歌词失败,请重试')
  7065. }
  7066. })
  7067. }
  7068. .justifyContent(FlexAlign.Start)
  7069. }
  7070. .height('100%')
  7071. .justifyContent(FlexAlign.Start)
  7072. .layoutWeight(1)
  7073. }
  7074. .width('100%')
  7075. .height(98)
  7076. Row() {
  7077. Text('标题:')
  7078. .fontSize(14)
  7079. .fontColor($r('app.color.text_color'))
  7080. .margin({ left: 22 })
  7081. TextInput({ text: this.titleStr })
  7082. .height(40)
  7083. .maxLines(1)
  7084. .fontSize(14)
  7085. .layoutWeight(1)
  7086. .fontColor($r('app.color.text_color'))
  7087. .margin({ right: 15, left: 10 })
  7088. .onChange((val: string) => {
  7089. this.titleStr = val
  7090. })
  7091. Button('修复乱码',{ type: ButtonType.Capsule, stateEffect: true})
  7092. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7093. .backgroundColor(this.themeColor)
  7094. .fontSize(10)
  7095. .margin({ right: 20})
  7096. .onClick(async () => {
  7097. let hwTags = await extractHwMediaMetadata(item.filePath)
  7098. let artist = hwTags?.artist|| '';
  7099. let title = hwTags?.title|| '';
  7100. let album = hwTags?.album|| '';
  7101. console.info('onecold 乱码修正 artist='+artist);
  7102. console.info('onecold 乱码修正 title='+title);
  7103. console.info('onecold 乱码修正 album='+album);
  7104. this.titleStr = title;
  7105. this.artistStr = artist;
  7106. this.ablumStr = album;
  7107. })
  7108. }
  7109. .width('100%')
  7110. .margin({ top: 10, bottom: 10 })
  7111. .justifyContent(FlexAlign.Start)
  7112. Row() {
  7113. Text('艺术家:')
  7114. .fontSize(14)
  7115. .fontColor($r('app.color.text_color'))
  7116. .margin({ left: 22 })
  7117. TextInput({ text: this.artistStr })
  7118. .height(40)
  7119. .maxLines(1)
  7120. .fontSize(14)
  7121. .layoutWeight(1)
  7122. .fontColor($r('app.color.text_color'))
  7123. .margin({ right: 20, left: 10 })
  7124. .onChange((val: string) => {
  7125. this.artistStr = val
  7126. })
  7127. }
  7128. .width('100%')
  7129. .margin({ top: 10, bottom: 10 })
  7130. .justifyContent(FlexAlign.Start)
  7131. Row() {
  7132. Text('专辑名:')
  7133. .fontSize(14)
  7134. .fontColor($r('app.color.text_color'))
  7135. .margin({ left: 22 })
  7136. TextInput({ text: this.ablumStr})
  7137. .height(40)
  7138. .maxLines(1)
  7139. .fontSize(14)
  7140. .layoutWeight(1)
  7141. .fontColor($r('app.color.text_color'))
  7142. .margin({ right: 20, left: 10 })
  7143. .onChange((val: string) => {
  7144. this.ablumStr = val
  7145. })
  7146. }
  7147. .width('100%')
  7148. .margin({ top: 10, bottom: 10 })
  7149. .justifyContent(FlexAlign.Start)
  7150. Row() {
  7151. Column(){
  7152. Column(){
  7153. Text('歌词:')
  7154. .fontSize(14)
  7155. .fontColor($r('app.color.text_color'))
  7156. .margin({ top:9,left: 22 })
  7157. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7158. SymbolGlyph($r('sys.symbol.trash_fill'))
  7159. .fontSize(25)
  7160. .alignSelf(ItemAlign.Center)
  7161. .margin({ left: 22,top:25})
  7162. }
  7163. .backgroundColor(Color.Transparent)
  7164. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  7165. Visibility.None:Visibility.Visible)
  7166. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7167. .onClick(()=>{
  7168. this.lyricConStr = ''
  7169. this.lyricContent = ''
  7170. this.tempLyricContent = ''
  7171. })
  7172. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7173. SymbolGlyph($r('sys.symbol.plus'))
  7174. .fontSize(25)
  7175. .alignSelf(ItemAlign.Center)
  7176. .margin({ left: 22,top:25})
  7177. }
  7178. .backgroundColor(Color.Transparent)
  7179. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7180. .onClick( ()=>{
  7181. this.callFilePickerSelectFileForLyric()
  7182. })
  7183. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7184. SymbolGlyph($r('sys.symbol.traditional_square'))
  7185. .fontSize(25)
  7186. .alignSelf(ItemAlign.Center)
  7187. .margin({ left: 22,top:25})
  7188. }
  7189. .backgroundColor(Color.Transparent)
  7190. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  7191. Visibility.None:Visibility.Visible)
  7192. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7193. .onClick( ()=>{
  7194. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  7195. this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
  7196. })
  7197. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7198. Image($r('app.media.jianti'))
  7199. .height(25)
  7200. .fillColor($r('app.color.text_color'))
  7201. .alignSelf(ItemAlign.Center)
  7202. .margin({ left: 22,top:25})
  7203. }
  7204. .backgroundColor(Color.Transparent)
  7205. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  7206. Visibility.None:Visibility.Visible)
  7207. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7208. .onClick( ()=>{
  7209. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  7210. this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
  7211. })
  7212. }
  7213. .layoutWeight(1)
  7214. }
  7215. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  7216. this.tempLyricContent })
  7217. .type(TextAreaType.NORMAL)
  7218. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
  7219. .fontSize(14)
  7220. .layoutWeight(1)
  7221. .fontColor($r('app.color.text_color'))
  7222. .margin({ right: 20, left: 10 })
  7223. .onChange((val: string) => {
  7224. this.lyricConStr = val
  7225. })
  7226. }
  7227. .width('100%')
  7228. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
  7229. .margin({ top: 10, bottom: 10 })
  7230. .justifyContent(FlexAlign.Start)
  7231. Row() {
  7232. Text('年份:')
  7233. .fontSize(14)
  7234. .fontColor($r('app.color.text_color'))
  7235. .margin({ left: 22 })
  7236. TextInput({ text: item.year })
  7237. .height(40)
  7238. .maxLines(1)
  7239. .fontSize(14)
  7240. .type(InputType.Number)
  7241. .layoutWeight(1)
  7242. .fontColor($r('app.color.text_color'))
  7243. .margin({ right: 20, left: 10 })
  7244. .onChange((val: string) => {
  7245. this.yearStr = val
  7246. })
  7247. }
  7248. .width('100%')
  7249. .margin({ top: 10, bottom: 10 })
  7250. .justifyContent(FlexAlign.Start)
  7251. Row() {
  7252. Text('音轨号:')
  7253. .fontSize(14)
  7254. .fontColor($r('app.color.text_color'))
  7255. .margin({ left: 22 })
  7256. TextInput({ text:item.track=='未知'?'': item.track })
  7257. .height(40)
  7258. .maxLines(1)
  7259. .fontSize(14)
  7260. .type(InputType.Number)
  7261. .layoutWeight(1)
  7262. .fontColor($r('app.color.text_color'))
  7263. .margin({ right: 20, left: 10 })
  7264. .onChange((val: string) => {
  7265. this.trackStr = val
  7266. })
  7267. }
  7268. .width('100%')
  7269. .margin({ top: 10, bottom: 10 })
  7270. .justifyContent(FlexAlign.Start)
  7271. Row() {
  7272. Text('碟号:')
  7273. .fontSize(14)
  7274. .fontColor($r('app.color.text_color'))
  7275. .margin({ left: 22 })
  7276. TextInput({ text:item.disc })
  7277. .height(40)
  7278. .maxLines(1)
  7279. .fontSize(14)
  7280. .type(InputType.Number)
  7281. .layoutWeight(1)
  7282. .fontColor($r('app.color.text_color'))
  7283. .margin({ right: 20, left: 10 })
  7284. .onChange((val: string) => {
  7285. this.discStr = val
  7286. })
  7287. }
  7288. .width('100%')
  7289. .margin({ top: 10, bottom: 10 })
  7290. .justifyContent(FlexAlign.Start)
  7291. Row() {
  7292. Text('风格:')
  7293. .fontSize(14)
  7294. .fontColor($r('app.color.text_color'))
  7295. .margin({ left: 22 })
  7296. TextInput({ text: item.genre })
  7297. .height(40)
  7298. .maxLines(1)
  7299. .fontSize(14)
  7300. .layoutWeight(1)
  7301. .fontColor($r('app.color.text_color'))
  7302. .margin({ right: 20, left: 10 })
  7303. .onChange((val: string) => {
  7304. this.genreStr = val
  7305. })
  7306. }
  7307. .width('100%')
  7308. .margin({ top: 10, bottom: 10 })
  7309. .justifyContent(FlexAlign.Start)
  7310. Row() {
  7311. Text('专辑艺术家:')
  7312. .fontSize(14)
  7313. .fontColor($r('app.color.text_color'))
  7314. .margin({ left: 22 })
  7315. TextInput({ text: item.ALBUMARTIST })
  7316. .height(40)
  7317. .maxLines(1)
  7318. .fontSize(14)
  7319. .layoutWeight(1)
  7320. .fontColor($r('app.color.text_color'))
  7321. .margin({ right: 20, left: 10 })
  7322. .onChange((val: string) => {
  7323. this.albumArtistStr = val
  7324. })
  7325. }
  7326. .width('100%')
  7327. .margin({ top: 10, bottom: 10 })
  7328. .justifyContent(FlexAlign.Start)
  7329. Row() {
  7330. Text('作曲:')
  7331. .fontSize(14)
  7332. .fontColor($r('app.color.text_color'))
  7333. .margin({ left: 22 })
  7334. TextInput({ text: item.COMPOSER })
  7335. .height(40)
  7336. .maxLines(1)
  7337. .fontSize(14)
  7338. .layoutWeight(1)
  7339. .fontColor($r('app.color.text_color'))
  7340. .margin({ right: 20, left: 10 })
  7341. .onChange((val: string) => {
  7342. this.composerStr = val
  7343. })
  7344. }
  7345. .width('100%')
  7346. .margin({ top: 10, bottom: 10 })
  7347. .justifyContent(FlexAlign.Start)
  7348. Row() {
  7349. Text('作词:')
  7350. .fontSize(14)
  7351. .fontColor($r('app.color.text_color'))
  7352. .margin({ left: 22 })
  7353. TextInput({ text: item.LYRICIST })
  7354. .height(40)
  7355. .maxLines(1)
  7356. .fontSize(14)
  7357. .layoutWeight(1)
  7358. .fontColor($r('app.color.text_color'))
  7359. .margin({ right: 20, left: 10 })
  7360. .onChange((val: string) => {
  7361. this.lyricistStr = val
  7362. })
  7363. }
  7364. .width('100%')
  7365. .margin({ top: 10, bottom: 10 })
  7366. .justifyContent(FlexAlign.Start)
  7367. Row() {
  7368. Text('注释:')
  7369. .fontSize(14)
  7370. .fontColor($r('app.color.text_color'))
  7371. .margin({ left: 22 })
  7372. TextInput({ text: item.COMMENT })
  7373. .height(40)
  7374. .maxLines(1)
  7375. .fontSize(14)
  7376. .layoutWeight(1)
  7377. .fontColor($r('app.color.text_color'))
  7378. .margin({ right: 20, left: 10 })
  7379. .onChange((val: string) => {
  7380. this.commentStr = val
  7381. })
  7382. }
  7383. .width('100%')
  7384. .margin({ top: 10, bottom: 10 })
  7385. .justifyContent(FlexAlign.Start)
  7386. Row() {
  7387. Button('保存')
  7388. .fontColor(Color.White)
  7389. .layoutWeight(1)
  7390. .height(50)
  7391. .width(100)
  7392. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7393. .backgroundColor(this.themeColor)
  7394. .stateEffect(true)
  7395. .margin({ right: 20, bottom: 20 })
  7396. .onClick(async () => {
  7397. this.doEdit(item)
  7398. })
  7399. Button('取消')
  7400. .fontColor(Color.White)
  7401. .layoutWeight(1)
  7402. .height(50)
  7403. .width(100)
  7404. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7405. .backgroundColor(this.themeColor)
  7406. .stateEffect(true)
  7407. .margin({ left: 20, bottom: 20 })
  7408. .onClick(async () => {
  7409. if(this.isGridMusic){
  7410. this.longItemFilePath =''
  7411. }else{
  7412. this.isShowEdit = false
  7413. }
  7414. this.setEditStrEmpty()
  7415. if(this.isShowPlay){
  7416. this.isShowEdit = false
  7417. }
  7418. })
  7419. }
  7420. .margin({
  7421. left: 38,
  7422. right: 38,
  7423. top: 10,
  7424. bottom: 10
  7425. })
  7426. .width(250)
  7427. .height(60)
  7428. }
  7429. }
  7430. .margin({ bottom: 20 })
  7431. }
  7432. setEditStrEmpty(){
  7433. this.imagePathStr = ''
  7434. this.lyricConStr = ''
  7435. this.artistStr = ''
  7436. this.titleStr = ''
  7437. this.ablumStr = ''
  7438. this.genreStr = ''
  7439. this.yearStr = ''
  7440. this.trackStr = ''
  7441. this.albumArtistStr = ''
  7442. this.composerStr = ''
  7443. this.lyricistStr = ''
  7444. this.commentStr = ''
  7445. this.discStr = ''
  7446. }
  7447. initEditFields(item?: VideoItem) {
  7448. if (!item) {
  7449. this.setEditStrEmpty()
  7450. return
  7451. }
  7452. this.imagePathStr = ''
  7453. this.titleStr = item.name ?? ''
  7454. this.artistStr = item.artist ?? ''
  7455. this.ablumStr = item.album ?? ''
  7456. this.genreStr = item.genre ?? ''
  7457. this.yearStr = item.year ?? ''
  7458. this.trackStr = item.track ?? ''
  7459. this.albumArtistStr = item.ALBUMARTIST ?? ''
  7460. this.composerStr = item.COMPOSER ?? ''
  7461. this.lyricistStr = item.LYRICIST ?? ''
  7462. this.commentStr = item.COMMENT ?? ''
  7463. this.discStr = item.disc ?? ''
  7464. this.lyricConStr = item.lyricContent ?? ''
  7465. }
  7466. private syncEditedFields(target?: VideoItem) {
  7467. if (!target) {
  7468. return
  7469. }
  7470. target.name = this.titleStr
  7471. target.artist = this.artistStr
  7472. target.album = this.ablumStr
  7473. target.lyricContent = this.lyricConStr
  7474. target.year = this.yearStr
  7475. target.genre = this.genreStr
  7476. target.track = this.trackStr
  7477. target.ALBUMARTIST = this.albumArtistStr
  7478. target.COMPOSER = this.composerStr
  7479. target.LYRICIST = this.lyricistStr
  7480. target.COMMENT = this.commentStr
  7481. target.disc = this.discStr
  7482. }
  7483. private replaceItemInList(list: Array<VideoItem> | undefined, filePath: string,
  7484. apply?: (next: Array<VideoItem>) => void) {
  7485. if (!list || ArrayUtil.isEmpty(list)) {
  7486. return
  7487. }
  7488. const index = list.findIndex((video: VideoItem) => video.filePath === filePath)
  7489. if (index < 0) {
  7490. return
  7491. }
  7492. const nextList = [...list]
  7493. this.syncEditedFields(nextList[index])
  7494. apply?.(nextList)
  7495. }
  7496. private syncListsAfterEdit(filePath: string) {
  7497. this.replaceItemInList(this.videoLocalList, filePath, (next: Array<VideoItem>) => {
  7498. this.videoLocalList = next
  7499. this.dataSource.pushArrayData(next)
  7500. })
  7501. this.replaceItemInList(this.songList, filePath, (next: Array<VideoItem>) => {
  7502. this.songList = next
  7503. this.sonDataSource.pushArrayData(next)
  7504. })
  7505. this.replaceItemInList(this.favList, filePath, (next: Array<VideoItem>) => {
  7506. this.favList = next
  7507. })
  7508. this.replaceItemInList(this.historyList, filePath, (next: Array<VideoItem>) => {
  7509. this.historyList = next
  7510. })
  7511. this.replaceItemInList(this.currentSongList, filePath, (next: Array<VideoItem>) => {
  7512. this.currentSongList = next
  7513. })
  7514. this.replaceItemInList(this.mediaKuList, filePath, (next: Array<VideoItem>) => {
  7515. this.mediaKuList = next
  7516. })
  7517. this.replaceItemInList(this.filteredList, filePath, (next: Array<VideoItem>) => {
  7518. this.filteredList = next
  7519. })
  7520. this.replaceItemInList(this.artistList, filePath, (next: Array<VideoItem>) => {
  7521. this.artistList = next
  7522. })
  7523. this.replaceItemInList(this.albumList, filePath, (next: Array<VideoItem>) => {
  7524. this.albumList = next
  7525. })
  7526. this.listRefreshKey++
  7527. }
  7528. private refreshLazyListViews(mainListUpdated: boolean, playlistUpdated: boolean): void {
  7529. if (!mainListUpdated && !playlistUpdated) {
  7530. return;
  7531. }
  7532. this.listRefreshKey++;
  7533. if (mainListUpdated) {
  7534. this.dataSource.notifyDataReload();
  7535. }
  7536. if (playlistUpdated) {
  7537. this.sonDataSource.notifyDataReload();
  7538. }
  7539. }
  7540. @Builder
  7541. detailSheet(item:VideoItem) {
  7542. Scroll() {
  7543. Column() {
  7544. this.songDetail(item)
  7545. }
  7546. }
  7547. .width('100%')
  7548. .height('100%')
  7549. }
  7550. @Builder
  7551. songDetail(currentItem:VideoItem) {
  7552. Column() {
  7553. if (currentItem) {
  7554. Row() {
  7555. Stack() {
  7556. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.alt') :
  7557. currentItem.pixelMapPath)
  7558. .fillColor(this.themeColor)
  7559. .height(80)
  7560. .width(80)
  7561. .borderRadius(10)
  7562. .opacity(this.opacityItem)// 绑定透明度
  7563. .margin({ left: 22 })
  7564. }
  7565. Column() {
  7566. Column() {
  7567. Text(currentItem.name)
  7568. .fontSize(16)
  7569. .maxLines(1)
  7570. .animation({
  7571. duration: 555,
  7572. curve: 'Linear',
  7573. })
  7574. .fontColor($r('app.color.text_color'))
  7575. .margin({ left: 15 })
  7576. }
  7577. .height('100%')
  7578. .width('100%')
  7579. .justifyContent(FlexAlign.Center)
  7580. .alignItems(HorizontalAlign.Start)
  7581. }
  7582. .height('100%')
  7583. }
  7584. .width('100%')
  7585. .height(90)
  7586. .justifyContent(FlexAlign.SpaceBetween)
  7587. Row() {
  7588. Text('艺术家:')
  7589. .fontSize(14)
  7590. .fontColor($r('app.color.text_color'))
  7591. .margin({ left: 22 })
  7592. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  7593. .fontSize(14)
  7594. .fontColor($r('app.color.text_color'))
  7595. .margin({ left: 10 })
  7596. .layoutWeight(1)
  7597. }
  7598. .width('100%')
  7599. .margin({ top: 10, bottom: 10 })
  7600. .justifyContent(FlexAlign.Start)
  7601. Row() {
  7602. Text('专辑名:')
  7603. .fontSize(14)
  7604. .fontColor($r('app.color.text_color'))
  7605. .margin({ left: 22 })
  7606. Text(currentItem?.album ?currentItem.album : '未知专辑')
  7607. .fontSize(14)
  7608. .margin({ left: 10 })
  7609. .fontColor($r('app.color.text_color'))
  7610. .layoutWeight(1)
  7611. }
  7612. .width('100%')
  7613. .margin({ top: 10, bottom: 10 })
  7614. .justifyContent(FlexAlign.Start)
  7615. Row() {
  7616. Text('时长:')
  7617. .fontSize(14)
  7618. .fontColor($r('app.color.text_color'))
  7619. .margin({ left: 22 })
  7620. Text(StrUtil.isEmpty(currentItem.duration)?
  7621. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  7622. .fontSize(14)
  7623. .margin({ left: 10 })
  7624. .fontColor($r('app.color.text_color'))
  7625. .layoutWeight(1)
  7626. }
  7627. .width('100%')
  7628. .margin({ top: 10, bottom: 10 })
  7629. .justifyContent(FlexAlign.Start)
  7630. Row() {
  7631. Text('采样率:')
  7632. .fontSize(14)
  7633. .fontColor($r('app.color.text_color'))
  7634. .margin({ left: 22 })
  7635. Text(Utility.convertToKHz(currentItem.sampleRate))
  7636. .fontSize(14)
  7637. .margin({ left: 10 })
  7638. .fontColor($r('app.color.text_color'))
  7639. .layoutWeight(1)
  7640. }
  7641. .width('100%')
  7642. .margin({ top: 10, bottom: 10 })
  7643. .justifyContent(FlexAlign.Start)
  7644. Row() {
  7645. Text('比特率:')
  7646. .fontSize(14)
  7647. .fontColor($r('app.color.text_color'))
  7648. .margin({ left: 22 })
  7649. Text(currentItem.bit_rate)
  7650. .fontSize(14)
  7651. .margin({ left: 10 })
  7652. .fontColor($r('app.color.text_color'))
  7653. .layoutWeight(1)
  7654. }
  7655. .width('100%')
  7656. .margin({ top: 10, bottom: 10 })
  7657. .justifyContent(FlexAlign.Start)
  7658. Row() {
  7659. Text('位深:')
  7660. .fontSize(14)
  7661. .fontColor($r('app.color.text_color'))
  7662. .margin({ left: 22 })
  7663. Text(`${currentItem.bits_per_raw_sample} bits`)
  7664. .fontSize(14)
  7665. .margin({ left: 10 })
  7666. .fontColor($r('app.color.text_color'))
  7667. .layoutWeight(1)
  7668. }
  7669. .width('100%')
  7670. .margin({ top: 10, bottom: 10 })
  7671. .justifyContent(FlexAlign.Start)
  7672. Row() {
  7673. Text('声道:')
  7674. .fontSize(14)
  7675. .fontColor($r('app.color.text_color'))
  7676. .margin({ left: 22 })
  7677. Text(`${currentItem.channels}`)
  7678. .fontSize(14)
  7679. .margin({ left: 10 })
  7680. .fontColor($r('app.color.text_color'))
  7681. .layoutWeight(1)
  7682. }
  7683. .width('100%')
  7684. .margin({ top: 10, bottom: 10 })
  7685. .justifyContent(FlexAlign.Start)
  7686. Row() {
  7687. Text('声道布局:')
  7688. .fontSize(14)
  7689. .fontColor($r('app.color.text_color'))
  7690. .margin({ left: 22 })
  7691. Text(`${currentItem.channel_layout}`)
  7692. .fontSize(14)
  7693. .margin({ left: 10 })
  7694. .fontColor($r('app.color.text_color'))
  7695. .layoutWeight(1)
  7696. }
  7697. .width('100%')
  7698. .margin({ top: 10, bottom: 10 })
  7699. .justifyContent(FlexAlign.Start)
  7700. Row() {
  7701. Text('起始播放点:')
  7702. .fontSize(14)
  7703. .fontColor($r('app.color.text_color'))
  7704. .margin({ left: 22 })
  7705. Text(`${currentItem.start_time}`)
  7706. .fontSize(14)
  7707. .margin({ left: 10 })
  7708. .fontColor($r('app.color.text_color'))
  7709. .layoutWeight(1)
  7710. }
  7711. .width('100%')
  7712. .margin({ top: 10, bottom: 10 })
  7713. .justifyContent(FlexAlign.Start)
  7714. Row() {
  7715. Text('风格:')
  7716. .fontSize(14)
  7717. .fontColor($r('app.color.text_color'))
  7718. .margin({ left: 22 })
  7719. Text(currentItem.genre)
  7720. .fontSize(14)
  7721. .margin({ left: 10 })
  7722. .fontColor($r('app.color.text_color'))
  7723. .layoutWeight(1)
  7724. }
  7725. .width('100%')
  7726. .margin({ top: 10, bottom: 10 })
  7727. .justifyContent(FlexAlign.Start)
  7728. Row() {
  7729. Text('发行时间:')
  7730. .fontSize(14)
  7731. .fontColor($r('app.color.text_color'))
  7732. .margin({ left: 22 })
  7733. Text(currentItem.year)
  7734. .fontSize(14)
  7735. .margin({ left: 10 })
  7736. .fontColor($r('app.color.text_color'))
  7737. .layoutWeight(1)
  7738. }
  7739. .width('100%')
  7740. .margin({ top: 10, bottom: 10 })
  7741. .justifyContent(FlexAlign.Start)
  7742. Row() {
  7743. Text('质量评分:')
  7744. .fontSize(14)
  7745. .fontColor($r('app.color.text_color'))
  7746. .margin({ left: 22 })
  7747. Text(currentItem.probe_score+"")
  7748. .fontSize(14)
  7749. .margin({ left: 10 })
  7750. .fontColor($r('app.color.text_color'))
  7751. .layoutWeight(1)
  7752. }
  7753. .width('100%')
  7754. .margin({ top: 10, bottom: 10 })
  7755. .justifyContent(FlexAlign.Start)
  7756. Row() {
  7757. Text('音轨号:')
  7758. .fontSize(14)
  7759. .fontColor($r('app.color.text_color'))
  7760. .margin({ left: 22 })
  7761. Text(currentItem.track)
  7762. .fontSize(14)
  7763. .margin({ left: 10 })
  7764. .fontColor($r('app.color.text_color'))
  7765. .layoutWeight(1)
  7766. }
  7767. .width('100%')
  7768. .margin({ top: 10, bottom: 10 })
  7769. .justifyContent(FlexAlign.Start)
  7770. Row() {
  7771. Text('碟号:')
  7772. .fontSize(14)
  7773. .fontColor($r('app.color.text_color'))
  7774. .margin({ left: 22 })
  7775. Text(currentItem.disc)
  7776. .fontSize(14)
  7777. .margin({ left: 10 })
  7778. .fontColor($r('app.color.text_color'))
  7779. .layoutWeight(1)
  7780. }
  7781. .width('100%')
  7782. .margin({ top: 10, bottom: 10 })
  7783. .justifyContent(FlexAlign.Start)
  7784. Row() {
  7785. Text('专辑艺术家:')
  7786. .fontSize(14)
  7787. .fontColor($r('app.color.text_color'))
  7788. .margin({ left: 22 })
  7789. Text(currentItem.ALBUMARTIST)
  7790. .fontSize(14)
  7791. .margin({ left: 10 })
  7792. .fontColor($r('app.color.text_color'))
  7793. .layoutWeight(1)
  7794. }
  7795. .width('100%')
  7796. .margin({ top: 10, bottom: 10 })
  7797. .justifyContent(FlexAlign.Start)
  7798. Row() {
  7799. Text('作曲家:')
  7800. .fontSize(14)
  7801. .fontColor($r('app.color.text_color'))
  7802. .margin({ left: 22 })
  7803. Text(currentItem.COMPOSER)
  7804. .fontSize(14)
  7805. .margin({ left: 10 })
  7806. .fontColor($r('app.color.text_color'))
  7807. .layoutWeight(1)
  7808. }
  7809. .width('100%')
  7810. .margin({ top: 10, bottom: 10 })
  7811. .justifyContent(FlexAlign.Start)
  7812. Row() {
  7813. Text('作词家:')
  7814. .fontSize(14)
  7815. .fontColor($r('app.color.text_color'))
  7816. .margin({ left: 22 })
  7817. Text(currentItem.LYRICIST)
  7818. .fontSize(14)
  7819. .margin({ left: 10 })
  7820. .fontColor($r('app.color.text_color'))
  7821. .layoutWeight(1)
  7822. }
  7823. .width('100%')
  7824. .margin({ top: 10, bottom: 10 })
  7825. .justifyContent(FlexAlign.Start)
  7826. Row() {
  7827. Text('注释:')
  7828. .fontSize(14)
  7829. .fontColor($r('app.color.text_color'))
  7830. .margin({ left: 22 })
  7831. Text(currentItem.COMMENT)
  7832. .fontSize(14)
  7833. .margin({ left: 10 })
  7834. .fontColor($r('app.color.text_color'))
  7835. .layoutWeight(1)
  7836. }
  7837. .width('100%')
  7838. .margin({ top: 10, bottom: 10 })
  7839. .justifyContent(FlexAlign.Start)
  7840. Row() {
  7841. Text('格式:')
  7842. .fontSize(14)
  7843. .fontColor($r('app.color.text_color'))
  7844. .margin({ left: 22 })
  7845. Text(Utility.formatMimeType(currentItem.mimeType))
  7846. .fontSize(14)
  7847. .margin({ left: 10 })
  7848. .fontColor($r('app.color.text_color'))
  7849. .layoutWeight(1)
  7850. }
  7851. .width('100%')
  7852. .margin({ top: 10, bottom: 10 })
  7853. .justifyContent(FlexAlign.Start)
  7854. Row() {
  7855. Text('播放次数:')
  7856. .fontSize(14)
  7857. .fontColor($r('app.color.text_color'))
  7858. .margin({ left: 22 })
  7859. Text(currentItem.playCount?.toString())
  7860. .fontSize(14)
  7861. .margin({ left: 10 })
  7862. .fontColor($r('app.color.text_color'))
  7863. .layoutWeight(1)
  7864. }
  7865. .width('100%')
  7866. .margin({ top: 10, bottom: 10 })
  7867. .justifyContent(FlexAlign.Start)
  7868. Row() {
  7869. Text('流数量:')
  7870. .fontSize(14)
  7871. .fontColor($r('app.color.text_color'))
  7872. .margin({ left: 22 })
  7873. Text(currentItem.nb_streams?.toString())
  7874. .fontSize(14)
  7875. .margin({ left: 10 })
  7876. .fontColor($r('app.color.text_color'))
  7877. .layoutWeight(1)
  7878. }
  7879. .width('100%')
  7880. .margin({ top: 10, bottom: 10 })
  7881. .justifyContent(FlexAlign.Start)
  7882. Row() {
  7883. Text('文件大小:')
  7884. .fontSize(14)
  7885. .fontColor($r('app.color.text_color'))
  7886. .margin({ left: 22 })
  7887. Text(currentItem.size)
  7888. .fontSize(14)
  7889. .margin({ left: 10 })
  7890. .fontColor($r('app.color.text_color'))
  7891. .layoutWeight(1)
  7892. }
  7893. .width('100%')
  7894. .margin({ top: 10, bottom: 10 })
  7895. .justifyContent(FlexAlign.Start)
  7896. Row() {
  7897. Text('文件名:')
  7898. .fontSize(14)
  7899. .fontColor($r('app.color.text_color'))
  7900. .margin({ left: 22 })
  7901. Text(currentItem.fileName)
  7902. .fontSize(14)
  7903. .margin({ left: 10 })
  7904. .fontColor($r('app.color.text_color'))
  7905. .layoutWeight(1)
  7906. }
  7907. .width('100%')
  7908. .margin({ top: 10, bottom: 10 })
  7909. .justifyContent(FlexAlign.Start)
  7910. Row() {
  7911. Text('修改时间:')
  7912. .fontSize(14)
  7913. .fontColor($r('app.color.text_color'))
  7914. .margin({ left: 22 })
  7915. Text(currentItem.cTime)
  7916. .fontSize(14)
  7917. .margin({ left: 10 })
  7918. .fontColor($r('app.color.text_color'))
  7919. .layoutWeight(1)
  7920. }
  7921. .width('100%')
  7922. .margin({ top: 10, bottom: 10 })
  7923. .justifyContent(FlexAlign.Start)
  7924. Row() {
  7925. Text('存放目录:')
  7926. .fontSize(14)
  7927. .fontColor($r('app.color.text_color'))
  7928. .margin({ left: 22 })
  7929. Text(currentItem.filePath)
  7930. .fontSize(12)
  7931. .margin({ left: 10 })
  7932. .fontColor($r('app.color.text_color'))
  7933. .layoutWeight(1)
  7934. }
  7935. .margin({ top: 10, bottom: 10 })
  7936. .width('100%')
  7937. .justifyContent(FlexAlign.Start)
  7938. Row() {
  7939. Text('内嵌歌词:')
  7940. .fontSize(14)
  7941. .fontColor($r('app.color.text_color'))
  7942. .margin({ left: 22 })
  7943. Text(currentItem.lyricContent)
  7944. .fontSize(12)
  7945. .copyOption(CopyOptions.InApp)
  7946. .margin({ left: 10 })
  7947. .fontColor($r('app.color.text_color'))
  7948. .layoutWeight(1)
  7949. }
  7950. .margin({ top: 10, bottom: 10 })
  7951. .width('100%')
  7952. .justifyContent(FlexAlign.Start)
  7953. }
  7954. }
  7955. .margin({ bottom: 20 })
  7956. }
  7957. //定时关闭布局
  7958. @Builder
  7959. TimeCloseSheet() {
  7960. Scroll() {
  7961. Column() {
  7962. this.TimeClose()
  7963. }
  7964. }
  7965. .width('100%')
  7966. .height('100%')
  7967. }
  7968. //倒计时关闭音乐,退出App功能实现。
  7969. @State selectedMinutes: number = 0 // 0表示未开启
  7970. @State remainingSeconds: number = 0
  7971. // 预设时间选项
  7972. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  7973. private formatTime(seconds: number): string {
  7974. const mins = Math.floor(seconds / 60)
  7975. const secs = seconds % 60
  7976. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  7977. }
  7978. // 开始倒计时
  7979. private handleTimeSelect(minutes: number) {
  7980. if (minutes === this.selectedMinutes) {
  7981. this.stopCountdown();
  7982. this.selectedMinutes = 0;
  7983. return;
  7984. }
  7985. this.selectedMinutes = minutes;
  7986. this.remainingSeconds = minutes * 60;
  7987. this.startCountdown(); // 新增调用
  7988. }
  7989. @Builder
  7990. TimeClose() {
  7991. Column() {
  7992. // 倒计时显示区域
  7993. Text(this.selectedMinutes > 0 ?
  7994. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  7995. "定时关闭未开启")
  7996. .fontSize(17)
  7997. .fontColor($r('app.color.text_color'))
  7998. .margin({ top: 2, bottom: 8 });
  7999. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  8000. ForEach(this.presetTimes, (minutes: number, index: number) => {
  8001. // 单行时间选项容器
  8002. Row() {
  8003. // 文字描述区域
  8004. Text(this.getDisplayText(minutes))
  8005. .fontSize(15)
  8006. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  8007. $r('app.color.text_color'))// 选中态颜色变化
  8008. .textAlign(TextAlign.Start)
  8009. .layoutWeight(1); // 占据剩余空间
  8010. // 复选框样式的选择器
  8011. Row() {
  8012. if (minutes === this.selectedMinutes) {
  8013. // 选中状态 - 带勾号的圆形复选框
  8014. Row() {
  8015. // 使用系统内置的勾号图标
  8016. Image($r('sys.media.ohos_ic_public_ok'))
  8017. .width(14)
  8018. .height(14)
  8019. .fillColor(Color.White)
  8020. }
  8021. .width(24)
  8022. .height(24)
  8023. .borderRadius(12)
  8024. .backgroundColor(this.themeColor)
  8025. .justifyContent(FlexAlign.Center)
  8026. .alignItems(VerticalAlign.Center)
  8027. } else {
  8028. // 未选中状态的圆形边框
  8029. Row()
  8030. .width(24)
  8031. .height(24)
  8032. .borderRadius(12)
  8033. .border({
  8034. width: 2,
  8035. color: $r('app.color.text_color'),
  8036. style: BorderStyle.Solid
  8037. })
  8038. .backgroundColor(Color.Transparent)
  8039. }
  8040. }
  8041. .width(24)
  8042. .height(24)
  8043. .margin({ left: 20 })
  8044. .justifyContent(FlexAlign.Center)
  8045. .alignItems(VerticalAlign.Center)
  8046. }
  8047. .width('100%')
  8048. .padding({
  8049. top: 18,
  8050. bottom: 18,
  8051. left: 18,
  8052. right: 18
  8053. })
  8054. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  8055. $r('app.color.bottom_control_background')) // 选中背景高亮
  8056. .borderRadius(12)
  8057. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8058. .margin({ bottom: 18 })
  8059. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  8060. });
  8061. }
  8062. .width('100%')
  8063. .padding(16)
  8064. }
  8065. }
  8066. // 获取显示文本
  8067. private getDisplayText(minutes: number): string {
  8068. if (minutes === -1) {
  8069. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  8070. }
  8071. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  8072. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  8073. }
  8074. // 处理选择事件
  8075. private handleSelect(minutes: number): void {
  8076. if (minutes === -1) { // 自定义
  8077. // 弹出自定义时间对话框
  8078. DialogHelper.showTextInputDialog({
  8079. title: '自定义时间',
  8080. maskColor: Color.Transparent,
  8081. inputType: InputType.Number,
  8082. text: '',
  8083. onChange: (text) => {
  8084. console.error("onChange: " + text);
  8085. },
  8086. onAction: (action, dialogId, content) => {
  8087. if (action == DialogAction.TWO) {
  8088. const customMinutes = Number(content);
  8089. if (customMinutes > 0) {
  8090. this.handleTimeSelect(customMinutes); // 设置自定义时间
  8091. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  8092. }
  8093. }
  8094. }
  8095. });
  8096. } else {
  8097. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  8098. }
  8099. }
  8100. // 添加定时器引用
  8101. private timerId: number = -1;
  8102. // 启动/重置倒计时
  8103. private startCountdown() {
  8104. // 清除旧定时器
  8105. if (this.timerId !== -1) {
  8106. clearInterval(this.timerId);
  8107. }
  8108. // 创建新定时器
  8109. if (this.selectedMinutes > 0) {
  8110. this.timerId = setInterval(() => {
  8111. if (this.remainingSeconds === 15) {
  8112. this.showConfirmationDialog();
  8113. }
  8114. if (this.remainingSeconds > 0) {
  8115. this.remainingSeconds -= 1;
  8116. } else {
  8117. this.stopCountdown();
  8118. this.handleTimeout();
  8119. }
  8120. }, 1000);
  8121. }
  8122. }
  8123. // 15倒计时后再次提示显示确认是否关闭App对话框
  8124. private showConfirmationDialog() {
  8125. DialogHelper.showAlertDialog({
  8126. backgroundColor: $r('app.color.btn_green'),
  8127. title: '确认关闭',
  8128. maskColor: Color.Transparent,
  8129. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  8130. borderStyle: BorderStyle.Dashed,
  8131. primaryButton: '暂不关闭',
  8132. secondaryButton: '确定',
  8133. onAction: (action) => {
  8134. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  8135. this.stopCountdown();
  8136. this.selectedMinutes = 0
  8137. } else if (action == DialogAction.TWO) {
  8138. }
  8139. }
  8140. })
  8141. }
  8142. // 停止倒计时
  8143. private stopCountdown() {
  8144. if (this.timerId !== -1) {
  8145. clearInterval(this.timerId);
  8146. this.timerId = -1;
  8147. }
  8148. }
  8149. // 超时处理
  8150. private handleTimeout() {
  8151. // 执行播放器关闭逻辑
  8152. this.selectedMinutes = 0;
  8153. ToastUtil.showToast(" 定时关闭已完成");
  8154. this.stop(); // 假设存在的播放器实例
  8155. //退出APP
  8156. const mContext = getContext(this) as common.UIAbilityContext
  8157. mContext.terminateSelf();
  8158. AvSessionController.getInstance(true).unregisterSessionListener()
  8159. }
  8160. //倒计时关闭音乐,退出App功能实现结束。
  8161. //播放列表的拖动List 重新排序
  8162. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  8163. //左滑操作 移动文件 重命名 删除等操作
  8164. @Builder
  8165. sonButton(item: VideoItem, index: number, filePath: string) {
  8166. Row() {
  8167. //加入下一首播放
  8168. Button() {
  8169. Image($r('app.media.next_to_play'))
  8170. .fillColor(Color.White)
  8171. .width(20)
  8172. }
  8173. .width(40)
  8174. .height(40)
  8175. .type(ButtonType.Circle)
  8176. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  8177. .backgroundColor(this.themeColor)
  8178. .margin(5)
  8179. .onClick(() => {
  8180. this.addToNextPlay(item);
  8181. })
  8182. Button() {
  8183. Image($r('app.media.close'))
  8184. .fillColor(Color.White)
  8185. .width(20)
  8186. }
  8187. .width(40)
  8188. .height(40)
  8189. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  8190. .type(ButtonType.Circle)
  8191. .backgroundColor(this.themeColor)
  8192. .margin(5)
  8193. .onClick(() => {
  8194. this.songList.splice(Number(index), 1)
  8195. this.sonDataSource.pushArrayData(this.songList)
  8196. })
  8197. Button() {
  8198. Image($r('app.media.share2'))
  8199. .fillColor(Color.White)
  8200. .width(20)
  8201. }
  8202. .width(40)
  8203. .height(40)
  8204. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  8205. .type(ButtonType.Circle)
  8206. .backgroundColor(this.themeColor)
  8207. .margin(5)
  8208. .onClick(() => {
  8209. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  8210. })
  8211. }
  8212. }
  8213. itemMoveSon(index: number, newIndex: number): void {
  8214. if (newIndex < 0 || newIndex >= this.songList.length) {
  8215. return;
  8216. }
  8217. let tmp = this.songList.splice(index, 1);
  8218. this.songList.splice(newIndex, 0, tmp[0]);
  8219. this.sonDataSource.pushArrayData(this.songList)
  8220. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  8221. if(this.modeType==4&&this.playlistTable){
  8222. updateAllSongsSortOrder(this.playlistTable, this.songList,this.currentSongListID)
  8223. }
  8224. }
  8225. @Builder
  8226. PlayList() {
  8227. List({ scroller: this.playListScroller }) {
  8228. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  8229. ListItem() {
  8230. this.MusicItemSon(item, index)
  8231. }
  8232. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  8233. .animation({
  8234. duration: 666,
  8235. curve: 'ease-in-out' // 可选动画曲线
  8236. })
  8237. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 600 }),
  8238. TransitionEffect.scale({ x: 0, y: 0 })))
  8239. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  8240. //拖动List关键代码开始
  8241. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  8242. .zIndex(this.dragItem === index ? 1 : 0)
  8243. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  8244. .gesture(
  8245. GestureGroup(GestureMode.Sequence,
  8246. LongPressGesture({ repeat: true })
  8247. .onAction((event?: GestureEvent) => {
  8248. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  8249. this.scaleItem = index
  8250. })
  8251. })
  8252. .onActionEnd(() => {
  8253. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  8254. this.scaleItem = -1
  8255. })
  8256. }),
  8257. PanGesture({ fingers: 1, direction: null, distance: 0 })
  8258. .onActionStart(() => {
  8259. this.dragItem = index // 记录当前拖动项索引
  8260. this.dragRefOffset = 0 // 重置偏移基准
  8261. })
  8262. .onActionUpdate((event: GestureEvent) => {
  8263. this.offsetY = event.offsetY - this.dragRefOffset;
  8264. this.neighborItem = -1;
  8265. let indexA = this.songList.indexOf(item);
  8266. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  8267. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  8268. let value: number = 0;
  8269. if (this.offsetY < 0) {
  8270. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  8271. this.neighborItem = indexA - 1;
  8272. this.neighborScale = 1 - value / 20;
  8273. } else if (this.offsetY > 0) {
  8274. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  8275. this.neighborItem = indexA + 1;
  8276. this.neighborScale = 1 - value / 20;
  8277. }
  8278. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  8279. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8280. this.offsetY -= this.ITEM_INTV;
  8281. this.dragRefOffset += this.ITEM_INTV;
  8282. this.itemMoveSon(indexA, indexA + 1);
  8283. });
  8284. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  8285. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8286. this.offsetY += this.ITEM_INTV;
  8287. this.dragRefOffset -= this.ITEM_INTV;
  8288. this.itemMoveSon(indexA, indexA - 1);
  8289. });
  8290. }
  8291. })
  8292. .onActionEnd((event: GestureEvent) => {
  8293. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8294. this.dragItem = -1
  8295. this.neighborItem = -1
  8296. })
  8297. animateTo({
  8298. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  8299. }, () => {
  8300. this.scaleItem = -1
  8301. })
  8302. })
  8303. )
  8304. .onCancel(() => {
  8305. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8306. this.dragItem = -1
  8307. this.neighborItem = -1
  8308. })
  8309. animateTo({
  8310. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  8311. }, () => {
  8312. this.scaleItem = -1
  8313. })
  8314. })
  8315. ) //拖动List关键代码结束
  8316. .onClick(() => {
  8317. this.doPlay(item, index, true)
  8318. })
  8319. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  8320. }
  8321. .width('100%')
  8322. .height('100%')
  8323. .onReachEnd(() => {
  8324. if(this.modeType === 4 )
  8325. return;
  8326. void this.tryLoadNextPageForPlayback();
  8327. })
  8328. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  8329. // .animation({ duration: 500, curve: Curve.Ease }))
  8330. .cachedCount(10)
  8331. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  8332. .gesture(PinchGesture({ fingers: 2 })
  8333. .onActionEnd((event: GestureEvent) => {
  8334. this.setSonListTwoFingers()
  8335. })
  8336. .onActionUpdate(e => {
  8337. this.scaleValue = this.pinchValue * e.scale
  8338. })
  8339. .onActionStart(e => {
  8340. }))
  8341. .padding({
  8342. bottom: 0
  8343. })
  8344. }
  8345. setSonListTwoFingers() {
  8346. this.pinchValue = this.scaleValue;
  8347. Logger.info('this.pinchValue = ' + this.pinchValue);
  8348. if (this.pinchValue >= 1) {
  8349. this.sonTwoFingerType++
  8350. Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
  8351. if (this.sonTwoFingerType > 3) {
  8352. this.sonTwoFingerType = 1
  8353. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  8354. }
  8355. } else {
  8356. this.sonTwoFingerType--
  8357. Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
  8358. if (this.sonTwoFingerType < 1) {
  8359. this.sonTwoFingerType = 1
  8360. }
  8361. }
  8362. PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
  8363. this.pinchValue = 1;
  8364. this.scaleValue = 1;
  8365. }
  8366. @State sonTwoFingerType:number = 3
  8367. @Builder
  8368. private MusicItemSon(item: VideoItem, index?: number) {
  8369. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8370. Row() {
  8371. Stack() {
  8372. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  8373. .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  8374. .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  8375. .alt($r('app.media.alt'))
  8376. .fillColor(this.themeColor)
  8377. .borderRadius(this.isCoverRectangle?11:'100%')
  8378. .clip(true)
  8379. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  8380. .draggable(false)// 禁止长按手势拖动
  8381. .autoResize(true) // 重采样,可减少内存占用
  8382. .margin({ left: 20 })
  8383. }
  8384. .width('15%')
  8385. Column() {
  8386. Column() {
  8387. Text(this.isShowFileName?item.fileName :item.name)
  8388. .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
  8389. .fontColor(this.curIndex === index ? this.themeColor :
  8390. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  8391. .maxLines(1)
  8392. .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
  8393. Row() {
  8394. Column(){
  8395. Text(item.md5Str?.includes('Lossless')?
  8396. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  8397. .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
  8398. .padding({ top: 3,right:6,left:6,bottom:3 })
  8399. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  8400. $r('app.color.text_color'))
  8401. .fontWeight(500)
  8402. .borderRadius(12)
  8403. .visibility(StrUtil.isEmpty(item.md5Str) ? Visibility.None : Visibility.Visible)
  8404. .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
  8405. .backgroundColor('#FFC107')
  8406. }
  8407. .padding({ top: 8 })
  8408. Text(StrUtil.isEmpty(item.artist) ? item.duration :
  8409. item.artist + ' ' + item?.duration)
  8410. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  8411. .padding({ top: 8 })
  8412. .maxLines(1)
  8413. .fontColor(this.curIndex === index ? this.themeColor :
  8414. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  8415. .margin({ left: StrUtil.isEmpty(item.md5Str)? 12 :this.sonTwoFingerType == 3 ? 5 : 3 })
  8416. Blank()
  8417. Text(item.size)
  8418. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  8419. .padding({ top: 8 })
  8420. .maxLines(1)
  8421. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  8422. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  8423. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  8424. .margin({ left: 10 })
  8425. }
  8426. }
  8427. .height('100%')
  8428. .width('100%')
  8429. .justifyContent(FlexAlign.Center)
  8430. .alignItems(HorizontalAlign.Start)
  8431. }
  8432. .height('100%')
  8433. .width('65%')
  8434. Column() {
  8435. ImageAnimator()
  8436. .images(this.imagesF)// 动画数组
  8437. .duration(1000)// 持续
  8438. .state(this.animationState)// 动画状态
  8439. .fillMode(FillMode.Forwards)
  8440. .width(18)
  8441. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  8442. Visibility.None)
  8443. .height(18)
  8444. .iterations(-1) // 播放次数
  8445. }
  8446. .width('20%')
  8447. }
  8448. }
  8449. .backgroundColor(Color.Transparent)
  8450. .width('100%')
  8451. .reuseId('son_item')
  8452. .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
  8453. .shadow(this.scaleItem === index ? {
  8454. radius: 70,
  8455. color: '#15000000',
  8456. offsetX: 0,
  8457. offsetY: 0
  8458. } :
  8459. {
  8460. radius: 0,
  8461. color: '#15000000',
  8462. offsetX: 0,
  8463. offsetY: 0
  8464. })
  8465. .animation({ curve: Curve.Sharp, duration: 300 })
  8466. }
  8467. @Builder
  8468. MusicPlayBuilder() {
  8469. Column() {
  8470. this.IjkMusicPlayerView()
  8471. }
  8472. .transition(TransitionEffect.asymmetric(
  8473. TransitionEffect.opacity(1),
  8474. TransitionEffect.OPACITY
  8475. ))
  8476. .visualEffect(deviceInfo.sdkApiVersion>=20&&this.bgController?
  8477. new hdsEffect.HdsEffectBuilder()
  8478. .shaderEffect({
  8479. effectType: hdsEffect.EffectType.UV_BACKGROUND_FLOW_LIGHT,
  8480. animation: {
  8481. duration: 10000,
  8482. iterations: -1,
  8483. autoPlay: true,
  8484. onFinish: ()=> {
  8485. console.info('Succeeded in finishing');
  8486. }
  8487. },
  8488. controller: this.bgController,
  8489. })
  8490. .buildEffect():null)
  8491. .height('100%')
  8492. .width('100%')
  8493. .onDisAppear(() => {
  8494. this.translateY = 0;
  8495. })
  8496. .translate({ y: this.translateY })
  8497. .gesture(
  8498. PanGesture(this.panOption)
  8499. .onActionUpdate((event?: GestureEvent) => {
  8500. if (event) {
  8501. // 只允许向下滑动,向上滑动时限制为0
  8502. this.translateY = Math.max(0, event.offsetY);
  8503. this.getUIContext().animateTo({
  8504. duration: 500,
  8505. curve: Curve.Sharp
  8506. }, () => {
  8507. this.scaleValueImage = Math.min(1, Math.max(0.38, 1 - event.offsetY / 500));
  8508. console.info('onecold scaleValueImage:', this.scaleValueImage)
  8509. this.scaleValueText =Math.min(1, Math.max(0.6, 1 - event.offsetY / 700));
  8510. })
  8511. }
  8512. })
  8513. .onActionEnd((event?: GestureEvent) => {
  8514. // 使用更低的阈值和滑动速度判断
  8515. const minDistance = 300; // 最小滑动距离 100vp
  8516. const minVelocity = 500; // 最小滑动速度
  8517. // 获取滑动速度(如果可用)
  8518. const velocity = event?.velocityY || 0;
  8519. // 判断是否应该关闭:距离足够 或者 速度足够快
  8520. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  8521. if (shouldClose) {
  8522. // 添加关闭动画
  8523. this.getUIContext().animateTo({
  8524. duration: 600,
  8525. curve: Curve.Friction
  8526. }, () => {
  8527. this.isShowPlay = false;
  8528. this.scaleValueImage = 1
  8529. this.scaleValueText = 1
  8530. this.translateY = 0;
  8531. })
  8532. } else {
  8533. // 回弹动画
  8534. this.getUIContext().animateTo({
  8535. duration: 600,
  8536. curve: Curve.Friction
  8537. }, () => {
  8538. this.scaleValueImage = 1
  8539. this.scaleValueText = 1
  8540. this.translateY = 0;
  8541. })
  8542. }
  8543. })
  8544. )
  8545. }
  8546. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  8547. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  8548. HeightBreakpoint.HEIGHT_LG;
  8549. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  8550. @State topBarHeight: number = 50
  8551. @State barOpacity: number = 1
  8552. @State barBottomOpacity: number = 1
  8553. private hideDone: boolean = false;
  8554. @State currentYOffset: number = 0;
  8555. @State bottomBarHeight: number = 68;
  8556. private isHiding: boolean = false;
  8557. //是否是Pura X外屏,或者小屏幕
  8558. isPuraWP() {
  8559. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  8560. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  8561. }
  8562. //是否是Pura X外屏,或者小屏幕,手机横屏
  8563. /**
  8564. * 是否是Pura X外屏,或者小屏幕,手机横屏
  8565. * @returns
  8566. */
  8567. isCoverOpacity() {
  8568. if (this.isPuraWP()) {
  8569. return true
  8570. }
  8571. if (this.isPhoneLan()) {
  8572. return true
  8573. }
  8574. if (deviceInfo.marketName.includes('Pura X')
  8575. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  8576. return true
  8577. }
  8578. return false
  8579. }
  8580. //是不是手机横屏
  8581. isPhoneLan() {
  8582. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  8583. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  8584. logHiCarWindow(`isPhoneLan width=${this.windowWidth}`);
  8585. logHiCarWindow(`isPhoneLan height=${this.windowHeight}`);
  8586. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarStatus=${this.isHiCarStatus}`);
  8587. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, curDisplayIsHiCar=${this.curDisplayIsHiCar}`);
  8588. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall=${this.isHiCarSmall()}`);
  8589. if (this.isHiCarKuanBianPing()) {
  8590. return true
  8591. }
  8592. if (this.isHiCar()) {
  8593. return false
  8594. }
  8595. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8596. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  8597. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  8598. return true
  8599. }
  8600. return false
  8601. }
  8602. //是不是1920x720的hicar的屏幕分辨率
  8603. isHiCarKuanBianPing(){
  8604. // if(!this.isHiCar()){
  8605. // return false
  8606. // }
  8607. const hiCarAspectRatios: HiCarAspectRatio[] = [
  8608. { ratio: 1920 / 720, name: "1920x720" },
  8609. ];
  8610. const currentRatio: number = this.windowWidth / this.windowHeight;
  8611. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  8612. logHiCarWindow(`HiCarKuanBianPing currentRatio=${currentRatio}`)
  8613. for (const hiCarRatio of hiCarAspectRatios) {
  8614. logHiCarWindow(`HiCarKuanBianPing hiCarRatio=${hiCarRatio.ratio}`)
  8615. logHiCarWindow(`HiCarKuanBianPing diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  8616. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  8617. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  8618. //宽扁平的尺寸设置列表展示
  8619. this.twoFingerType ==3
  8620. this.isGridMusic = false
  8621. return true;
  8622. }
  8623. }
  8624. return false;
  8625. }
  8626. //是不是hicar的屏幕分辨率
  8627. isHiCarSmall() {
  8628. if(!this.isHiCar()){
  8629. return false
  8630. }
  8631. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  8632. {
  8633. this.columns = 6
  8634. return false
  8635. }
  8636. const hiCarAspectRatios: HiCarAspectRatio[] = [
  8637. { ratio: 800 / 480, name: "800x480" },
  8638. { ratio: 1280 / 720, name: "1280x720" },
  8639. { ratio: 1920 / 1080, name: "1920x1080" },
  8640. ];
  8641. const currentRatio: number = this.windowWidth / this.windowHeight;
  8642. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  8643. logHiCarWindow(`HiCarSmall currentRatio=${currentRatio}`)
  8644. for (const hiCarRatio of hiCarAspectRatios) {
  8645. logHiCarWindow(`HiCarSmall hiCarRatio=${hiCarRatio.ratio}`)
  8646. logHiCarWindow(`HiCarSmall diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  8647. logHiCarWindow(`HiCarSmall isHiCarStatus=${this.isHiCarStatus}`);
  8648. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  8649. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  8650. //宽扁平的尺寸设置列表展示
  8651. return true;
  8652. }
  8653. }
  8654. return false;
  8655. }
  8656. isHiCar() {
  8657. return this.curDisplayIsHiCar;
  8658. }
  8659. //是不是正常的手机竖屏
  8660. isPhonePortrait() {
  8661. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  8662. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  8663. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  8664. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8665. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  8666. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  8667. return true
  8668. }
  8669. return false
  8670. }
  8671. @State showSpeedDialog: boolean = false
  8672. @State longPressSpeed: number = 3 //长按默认倍数
  8673. @Builder
  8674. SpeedDialog() {
  8675. Stack() {
  8676. Column() {
  8677. Text('已切换至' + this.longPressSpeed + '倍速播放')
  8678. .fontColor(Color.White)
  8679. .visibility(Visibility.Hidden)
  8680. }
  8681. .backgroundColor(Color.Black)
  8682. .borderRadius(20)
  8683. .padding({
  8684. top: 10,
  8685. right: 20,
  8686. left: 15,
  8687. bottom: 20
  8688. })
  8689. .opacity(0.6)
  8690. Text('已切换至' + this.longPressSpeed + '倍速播放')
  8691. .fontColor(Color.White)
  8692. }
  8693. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  8694. .zIndex(5)
  8695. .margin({ top: 80 })
  8696. }
  8697. @Builder
  8698. IjkMusicPlayerView() {
  8699. Stack() {
  8700. if(canIUse("SystemCapability.UIDesign.HDSComponent.Core")
  8701. &&deviceInfo.sdkApiVersion>=20&&this.sceneBgController){
  8702. HdsVisualComponent()
  8703. .scene(HdsSceneType.DUAL_EDGE_FLOW_LIGHT_WITH_BACKGROUND_MASK, this.sceneBgController, () => {
  8704. console.info('Succeeded in finishing');
  8705. })
  8706. .width('100%')
  8707. .height('100%')
  8708. .visibility(this.isShowBgLiuGUANG?Visibility.Visible:Visibility.None)
  8709. }
  8710. Column() {
  8711. Column() {
  8712. //播放标题
  8713. Column() {
  8714. this.PlayTitle()
  8715. }
  8716. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  8717. .width('100%')
  8718. .margin({ top: 0 })
  8719. .height(PlayConstants.HEIGHT)
  8720. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  8721. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  8722. if (this.showSpeedDialog) {
  8723. this.SpeedDialog()
  8724. }
  8725. Stack() {
  8726. //手势拖动快进
  8727. Column()
  8728. .width(CommonConstants.FULL_PERCENT)
  8729. .height('100%')
  8730. .gesture(
  8731. GestureGroup(GestureMode.Parallel,
  8732. // 长按屏幕倍数播放
  8733. LongPressGesture({ repeat: true })
  8734. .onAction(() => {
  8735. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8736. this.showSpeedDialog = true;
  8737. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  8738. }
  8739. })
  8740. .onActionEnd(() => {
  8741. this.showSpeedDialog = false;
  8742. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  8743. }),
  8744. //双击屏幕暂停或者播放
  8745. TapGesture({ count: 2 })
  8746. .onAction((event: GestureEvent) => {
  8747. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8748. ToastUtil.showToast('已暂停')
  8749. }
  8750. console.info('onecold playOrPause 6693')
  8751. this.playOrPause()
  8752. })
  8753. )
  8754. )
  8755. }
  8756. .height('65%')
  8757. Swiper() {
  8758. this.CoverInfo()
  8759. this.PlayerLyrics()
  8760. }
  8761. .onChange((index: number) => {
  8762. this.currentSwiperIndex = index
  8763. })
  8764. .indicator(false)
  8765. .displayCount(new BreakpointType({
  8766. sm: 1,
  8767. md: 2,
  8768. lg: 2,
  8769. xl: 2,
  8770. xxl: 2
  8771. }).getValue(this.currentBreakpoint))
  8772. .clip(false)
  8773. .loop(false)
  8774. .autoPlay(false)
  8775. // .interval(8000)
  8776. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  8777. .height('100%')
  8778. .hitTestBehavior(HitTestMode.Transparent)
  8779. Image($r('app.media.icon_replay'))
  8780. .objectFit(ImageFit.Auto)
  8781. .width('120px')
  8782. .height('120px')
  8783. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  8784. .border({ width: 0 })
  8785. .visibility(Visibility.None)
  8786. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  8787. .onClick(() => {
  8788. console.info('onecold startPlayOrResumePlay 6744')
  8789. this.startPlayOrResumePlay();
  8790. })
  8791. }
  8792. .width(CommonConstants.FULL_PERCENT)
  8793. .height(CommonConstants.FULL_PERCENT)
  8794. .justifyContent(FlexAlign.End)
  8795. }
  8796. .justifyContent(FlexAlign.End)
  8797. .margin({ bottom: 8 })
  8798. }
  8799. .backgroundImage(!this.isMusicBGCover||StrUtil.isEmpty(this.cover)?null: this.cover)
  8800. .backgroundImageSize(this.isPuraWP()||!this.isMusicBGCover ? { width: '100%' } : { height: '150%', width: '100%' })
  8801. .animation({
  8802. duration: 666,
  8803. curve: 'ease-in-out' // 可选动画曲线
  8804. })
  8805. .backgroundBlurStyle((this.isPuraWP() && this.currentSwiperIndex === 0) ||!this.isMusicBGCover
  8806. ? BlurStyle.NONE :
  8807. BlurStyle.BACKGROUND_ULTRA_THICK)
  8808. .hitTestBehavior(HitTestMode.Transparent)
  8809. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  8810. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  8811. .onClick(() => {
  8812. if(this.isHiCar())
  8813. return
  8814. if(this.is_auto_hide_progress){
  8815. this.is_auto_hide_progress = false
  8816. }
  8817. this.startAutoHide()
  8818. })
  8819. }
  8820. @Consume progressValue: number ;
  8821. @State currentTime: string = "00:00";
  8822. @State totalTime: string = "00:00";
  8823. @State loadingVisible: Visibility = Visibility.None;
  8824. @State replayVisible: Visibility = Visibility.None;
  8825. @State slideEnable: boolean = false;
  8826. @State aspRatio: number = 0.5;
  8827. @State mContext: object | undefined = undefined;
  8828. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  8829. @State mFirst: boolean = true;
  8830. @State mDestroyPage: boolean = false;
  8831. @State playSpeed: number = 1;
  8832. @State oldSeconds: number = 0;
  8833. @State isSeekTo: boolean = false;
  8834. @State isCurrentTime: boolean = false;
  8835. @State videoWidth: string = '100%';
  8836. @State videoHeight: string = '100%';
  8837. @State initAspectRatio: number = 1;
  8838. @State videoAspectRatio: number = this.initAspectRatio;
  8839. @State videoUrl: string = '';
  8840. private last: number = 0;
  8841. @State videoParentAspectRatio: number = this.initAspectRatio;
  8842. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  8843. @Consume CONTROL_PlayStatus: number ;
  8844. @State PROGRESS_MAX_VALUE: number = 100;
  8845. @State updateProgressTimer: number = 0;
  8846. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  8847. @State name: string = '';
  8848. // @State loop: boolean = false;
  8849. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  8850. @State multiple: string = '1.0X';
  8851. xcomponentController: XComponentController = new XComponentController()
  8852. private panOptionBright: PanGestureOptions =
  8853. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  8854. private panOptionVolume: PanGestureOptions =
  8855. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  8856. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  8857. //手势的音量控制和亮度控制
  8858. private positionX: number = PlayConstants.POSITION_X;
  8859. private positionY: number = PlayConstants.POSITION_Y;
  8860. private windowClass: window.Window = globalThis.windowClass
  8861. @State volume: number = 0.5;
  8862. @State volumeSmall: boolean = false
  8863. @State autoParseMusicName: boolean = true
  8864. @State isShowFileName: boolean = false
  8865. @State isLongNameRoLL: boolean = true//长歌名滚动
  8866. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  8867. @State bright: number = PlayConstants.BRIGHT;
  8868. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  8869. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  8870. @State screenWidth: number = 0
  8871. @State screenHeight: number = 0
  8872. @State statusBarHeight: number = 0
  8873. @State isYesFull: boolean = false
  8874. private seekValue: number = 0
  8875. @State isVideoLock: boolean = false; // Whether the video playback is locked
  8876. private preloadNextRandomIndex: number = -1; // 预缓存的随机下一首索引
  8877. eventHub = getContext().eventHub;
  8878. //投播组件
  8879. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  8880. // 新的投播控制器(封装了官方示例的逻辑)
  8881. private castControllerWrapper: CastController | undefined = undefined;
  8882. // 保留原始的 avCastController 引用(用于兼容旧代码)
  8883. private castController: avSession.AVCastController | undefined = undefined;
  8884. @State isCastPlaying: boolean = false;
  8885. @State currentTime2: number = 0;
  8886. @State currentStringTime: string = '00:00';
  8887. @State duration: number = 0;
  8888. @State isReady: boolean = false;
  8889. @State durationTime: number = 0;
  8890. @State durationStringTime: string = '00:00';
  8891. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  8892. // @State isPlaying: boolean = false;
  8893. private castSeek: boolean = false;
  8894. private castItem: avSession.AVQueueItem | undefined = undefined;
  8895. private castFile: fs.File | undefined = undefined; // 保持文件描述符引用,避免被垃圾回收
  8896. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  8897. @State rotateAngle2: number = -9
  8898. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  8899. @Consume cover: string | undefined ;
  8900. @State artist: string | undefined = ''
  8901. // 1.初始化controller
  8902. private lyricController: LyricController = new LyricController()
  8903. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  8904. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  8905. private parser = new LyricParser()
  8906. @State randomShakenX: number = 0
  8907. @State randomShakenY: number = 0
  8908. @State lyricTextSize: number = 24
  8909. @State lyricContent: string = ''
  8910. @State isDebug: boolean = false
  8911. @State isHightLightCenter: boolean = true
  8912. /**
  8913. * 初始化歌词加载与展示逻辑
  8914. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  8915. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  8916. * @param isApi2 是否使用API2获取歌词(可选)
  8917. *
  8918. * 主要流程:
  8919. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  8920. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  8921. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  8922. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  8923. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  8924. * 6. 解析失败或读取失败时,清空歌词显示。
  8925. *
  8926. * 注意事项:
  8927. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  8928. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  8929. * - 歌词内容解析后通过lyricController驱动UI渲染。
  8930. */
  8931. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
  8932. if (StrUtil.isEmpty(lyricPath)) {
  8933. return
  8934. }
  8935. this.initPipLyricSetting()
  8936. this.lyricControllerSingle
  8937. .setTextSize(15)
  8938. .setCacheSize(4)
  8939. .setTextColor("#FFFFFF")
  8940. .setHighlightColor(this.currentHighLightLyricColor)
  8941. .setHighlightScale(1.2)
  8942. .setEmptyHint("")
  8943. .setLineSpace(1)
  8944. .setAlignMode('center')
  8945. .setAnimationDuration(500)
  8946. .setSingleLine(true)
  8947. this.lyricContent = ''
  8948. this.lyricController
  8949. .setTextSize(this.currentLyricSize)
  8950. .setCacheSize(4)
  8951. .setTextColor("#DDDDDD")
  8952. .setHighlightColor("#FFFFFF")
  8953. .setEmptyHint("")
  8954. .setAnimationDuration(1000)
  8955. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  8956. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  8957. this.setBlurDegree(this.blurDegree, false)
  8958. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  8959. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  8960. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  8961. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  8962. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  8963. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  8964. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  8965. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  8966. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  8967. this.lyricController.setTextWeight(this.lyricTextWeight)
  8968. this.showSingleLyric = false
  8969. this.timeOffset = 0
  8970. this.lyricController.setLyric(null)
  8971. this.lyricControllerSingle.setLyric(null)
  8972. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  8973. console.log("onecold lyricPath =" + lyricPath)
  8974. // 1. 检查内嵌歌词
  8975. let neiqianLrc = ''
  8976. let lyContent = this.currentSong?.lyricContent
  8977. if(lyContent && StrUtil.isNotEmpty(lyContent)){
  8978. neiqianLrc = lyContent
  8979. }
  8980. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast && !isLocal) {
  8981. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  8982. // Navidrome JSON歌词转换
  8983. if (this.currentSong && isNavidromeType(this.currentSong.type)) {
  8984. const convertedLyric: string | undefined = LyricUtil.convertNavidromeJsonLyricToLrc(neiqianLrc);
  8985. if (convertedLyric) {
  8986. neiqianLrc = convertedLyric;
  8987. console.log("onecold Navidrome歌词转换成功");
  8988. }
  8989. }
  8990. this.setLyricToControllers(neiqianLrc);
  8991. return
  8992. }
  8993. // 2. 尝试从服务器获取歌词 (Navidrome/Jellyfin/Emby/AudioStation/Plex)
  8994. if (this.currentSong && (isJellyfinType(this.currentSong.type)||isNavidromeType(this.currentSong.type)
  8995. || isEmbyType(this.currentSong.type) || isAudioStationType(this.currentSong.type)
  8996. || isPlexType(this.currentSong.type))) {
  8997. const manager = RemoteDriveManager.getInstance();
  8998. const getAccount = (accountId: string) => manager.getWebDavAccountById(accountId);
  8999. // 将currentSong转换为SongData接口
  9000. const songData: SongData = {
  9001. webdav_account_id: this.currentSong.webdav_account_id,
  9002. artist: this.currentSong.artist,
  9003. name: this.currentSong.name,
  9004. webdav_id: this.currentSong.webdav_id,
  9005. lyricIndex: this.currentSong.lyricIndex,
  9006. type: this.currentSong.type
  9007. };
  9008. let serverLyric = '';
  9009. if (!serverLyric && isNavidromeType(songData.type)) {
  9010. serverLyric = await lyricService.fetchNavidromeLyric(songData, getAccount,this.currentSong.id);
  9011. }
  9012. if (!serverLyric && isJellyfinType(songData.type)) {
  9013. serverLyric = await lyricService.fetchJellyfinLyric(songData, getAccount);
  9014. }
  9015. if (!serverLyric && isEmbyType(songData.type)) {
  9016. serverLyric = await lyricService.fetchEmbyLyric(songData, getAccount);
  9017. }
  9018. if (!serverLyric && isAudioStationType(songData.type)) {
  9019. serverLyric = await lyricService.fetchAudioStationLyric(songData, getAccount);
  9020. }
  9021. if (!serverLyric && isPlexType(songData.type)) {
  9022. serverLyric = await lyricService.fetchPlexLyric(songData, getAccount);
  9023. }
  9024. if (serverLyric) {
  9025. this.setLyricToControllers(serverLyric, lyricPath);
  9026. return;
  9027. }
  9028. }
  9029. // 3. 尝试在线歌词API
  9030. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  9031. && !Utility.isVideoByExtension(this.videoUrl))) {
  9032. this.fetchOnlineLyric(lyricPath, isOnLineAndToast || false, isApi2);
  9033. return;
  9034. }
  9035. // 4. 从本地文件读取歌词
  9036. await this.loadLyricFromFile(lyricPath, jiaMilyricPath, isLocal || false);
  9037. }
  9038. /**
  9039. * 从本地文件加载歌词
  9040. */
  9041. private async loadLyricFromFile(lyricPath: string, jiaMilyricPath: string, isLocal: boolean): Promise<void> {
  9042. try {
  9043. let isJiaMi = false;
  9044. let realLyricPath = lyricPath;
  9045. if (FileUtil.accessSync(jiaMilyricPath)) {
  9046. isJiaMi = true;
  9047. realLyricPath = jiaMilyricPath;
  9048. console.info("onecold 找到加密本地歌词 ");
  9049. } else {
  9050. isJiaMi = false;
  9051. realLyricPath = lyricPath;
  9052. console.info("onecold 找到本地歌词 ");
  9053. }
  9054. // 读取文件内容
  9055. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  9056. const stat = await fileIo.stat(file.fd);
  9057. const arrayBuffer = new ArrayBuffer(stat.size);
  9058. fs.read(file.fd, arrayBuffer)
  9059. .then((readLen: number) => {
  9060. console.info("read file data succeed");
  9061. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  9062. if (buf.length === 0) {
  9063. throw new Error("Buffer is empty after reading the file");
  9064. }
  9065. try {
  9066. // 检测文件编码
  9067. let detectedEncoding = this.detect(arrayBuffer);
  9068. console.info("onecoldT Detected encoding: " + detectedEncoding);
  9069. // 使用检测到的编码解码,解决中文乱码问题
  9070. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  9071. console.info("onecoldT Detected textDecoder: " + textDecoder);
  9072. let fileContent = textDecoder.decode(buf);
  9073. console.info(`onecoldT The content of file1: ${fileContent}`);
  9074. // 解密
  9075. if (isJiaMi) {
  9076. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  9077. }
  9078. console.info(`onecold The content of file2: ${fileContent}`);
  9079. this.lyricContent = fileContent;
  9080. if(isLocal){
  9081. // 编辑标签选择本地歌词需要赋值给this.lyricConStr
  9082. this.lyricConStr = fileContent;
  9083. }
  9084. this.setLyricToControllers(fileContent);
  9085. console.info(`The content of file: ${fileContent}`);
  9086. } catch (chardetError) {
  9087. console.error("chardet.detect failed with error: " + chardetError.message);
  9088. this.clearLyricControllers();
  9089. }
  9090. })
  9091. .catch((err: BusinessError) => {
  9092. this.clearLyricControllers();
  9093. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  9094. })
  9095. .catch((err: Error) => {
  9096. this.clearLyricControllers();
  9097. console.error("read file 2 data failed with error message: " + err.message);
  9098. })
  9099. .finally(() => {
  9100. fs.closeSync(file);
  9101. });
  9102. } catch (error) {
  9103. this.clearLyricControllers();
  9104. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  9105. }
  9106. }
  9107. detect(data: ArrayBuffer): string {
  9108. //创建检测对象
  9109. let detector: UniversalDetector = new UniversalDetector();
  9110. // 传入检测数据并实时判断编码格式
  9111. detector.handleData(data, 0, data.byteLength);
  9112. // 标记检测数据 读取结束
  9113. detector.dataEnd();
  9114. // 获取检测结果
  9115. let detected: string = detector.getDetectedCharset();
  9116. // 释放资源
  9117. detector.reset();
  9118. return detected;
  9119. }
  9120. /**
  9121. * 设置歌词到所有控制器
  9122. * @param lyricText 歌词文本
  9123. * @param savePath 可选,如果提供则保存到本地文件
  9124. */
  9125. private setLyricToControllers(lyricText: string, savePath?: string): void {
  9126. if (StrUtil.isEmpty(lyricText)) {
  9127. this.clearLyricControllers();
  9128. return;
  9129. }
  9130. this.lyricContent = lyricText;
  9131. const lines: string[] = lyricText.split('\n').map((line: string) => line.trim());
  9132. const lyric: Lyric = this.parser.parse(lines);
  9133. this.lyricController.setLyric(lyric);
  9134. this.lyricControllerXF.setLyric(lyric);
  9135. this.lyricControllerSingle.setLyric(lyric);
  9136. this.showSingleLyric = true;
  9137. // 如果提供了保存路径,保存歌词到本地
  9138. if (savePath) {
  9139. this.saveDataToFile(lyricText, savePath, false);
  9140. }
  9141. }
  9142. /**
  9143. * 清空所有歌词控制器
  9144. */
  9145. private clearLyricControllers(): void {
  9146. this.lyricController.setLyric(null);
  9147. this.lyricControllerXF.setLyric(null);
  9148. this.lyricControllerSingle.setLyric(null);
  9149. }
  9150. /**
  9151. * 从在线API获取歌词
  9152. */
  9153. private fetchOnlineLyric(lyricPath: string, isOnLineAndToast: boolean, isApi2?: boolean): void {
  9154. if (!this.currentSong) {
  9155. this.clearLyricControllers();
  9156. if (isOnLineAndToast) {
  9157. ToastUtil.showShort('未获取到歌词!');
  9158. }
  9159. return;
  9160. }
  9161. let artist = this.currentSong.artist || '';
  9162. if (isApi2 === undefined) {
  9163. isApi2 = false;
  9164. }
  9165. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  9166. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  9167. this.setLyricToControllers(res, lyricPath);
  9168. } else {
  9169. this.clearLyricControllers();
  9170. if (isOnLineAndToast) {
  9171. ToastUtil.showShort('未获取到歌词!');
  9172. }
  9173. }
  9174. });
  9175. }
  9176. //初始化悬浮歌词的自定义设置
  9177. initPipLyricSetting() {
  9178. this.lyricControllerXF
  9179. .setTextSize(this.currentLyricSize)
  9180. .setCacheSize(4)
  9181. .setTextColor("#DDDDDD")
  9182. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  9183. .setEmptyHint("")
  9184. .setAnimationDuration(1000)
  9185. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  9186. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  9187. this.setBlurDegree(this.blurDegreePip, true)
  9188. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  9189. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  9190. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  9191. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  9192. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  9193. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  9194. this.lyricControllerXF.setHightLightCenter(true)
  9195. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  9196. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  9197. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  9198. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  9199. if (this.pipBgIndex === 0) {
  9200. if (this.cover) {
  9201. this.pipBg = this.cover
  9202. } else {
  9203. this.pipBg = this.imageColor
  9204. }
  9205. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  9206. }
  9207. }
  9208. //根据item返回歌词内容
  9209. async getLyricContent(item: VideoItem): Promise<string> {
  9210. let neiqianLrc = ''
  9211. let lyContent = item?.lyricContent
  9212. if(lyContent&&StrUtil.isNotEmpty(lyContent)){
  9213. neiqianLrc = lyContent
  9214. return neiqianLrc
  9215. }
  9216. try {
  9217. //取数据库里面的歌词lyContent
  9218. const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
  9219. if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
  9220. console.log("onecold Lyrics:", lyricContent);
  9221. neiqianLrc = lyricContent
  9222. return neiqianLrc
  9223. }
  9224. } catch (error) {
  9225. console.error("Error fetching lyrics:", error);
  9226. }
  9227. try {
  9228. let filePath = item.filePath;
  9229. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  9230. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  9231. let isJiaMi = false;
  9232. let realLyricPath = lyricPath;
  9233. if (FileUtil.accessSync(jiaMilyricPath)) {
  9234. isJiaMi = true;
  9235. realLyricPath = jiaMilyricPath;
  9236. console.info("onecold 找到加密本地歌词");
  9237. } else {
  9238. console.info("onecold 找到本地歌词");
  9239. }
  9240. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  9241. const stat = await fileIo.stat(file.fd);
  9242. const arrayBuffer = new ArrayBuffer(stat.size);
  9243. const readLen = await fs.read(file.fd, arrayBuffer);
  9244. console.info("read file data succeed");
  9245. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  9246. if (buf.length === 0) {
  9247. throw new Error("Buffer is empty after reading the file");
  9248. }
  9249. // let detectedEncoding = chardet.detect(buf);
  9250. let detectedEncoding = this.detect(arrayBuffer)
  9251. console.info("Detected encoding: " + detectedEncoding);
  9252. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  9253. let fileContent = textDecoder.decode(buf);
  9254. console.info(`onecold The content of file1: ${fileContent}`);
  9255. if (isJiaMi) {
  9256. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  9257. }
  9258. console.info(`onecold The content of file2: ${fileContent}`);
  9259. fs.closeSync(file);
  9260. return fileContent;
  9261. } catch (error) {
  9262. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  9263. return '';
  9264. }
  9265. }
  9266. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  9267. if (StrUtil.isEmpty(filePath)) {
  9268. return
  9269. }
  9270. try {
  9271. //将content进行加密
  9272. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  9273. let lyricContent = ''
  9274. if (isJiaMi) {
  9275. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  9276. } else {
  9277. lyricContent = content
  9278. }
  9279. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  9280. // 清空文件内容
  9281. await fileIo.truncate(file.fd, 0);
  9282. await fileIo.write(file.fd, lyricContent);
  9283. await fileIo.close(file);
  9284. console.log('onecold lyric file Data saved successfully.');
  9285. } catch (error) {
  9286. console.error('onecold lyric file Failed to save data:', error);
  9287. }
  9288. }
  9289. // 定义开始旋转的方法
  9290. // 使用动画系统优化旋转性能,避免 setInterval 频繁更新导致卡顿
  9291. @State timer: number = 0
  9292. @State rotateAngle: number = 0
  9293. @State isRotationRunning: boolean = false // 旋转动画是否正在运行
  9294. //封面旋转动画
  9295. animationRoFun() {
  9296. if (this.isPlaying && !this.isCoverRectangle) {
  9297. // 启动旋转动画
  9298. if (!this.isRotationRunning) {
  9299. this.isRotationRunning = true
  9300. this.startContinuousRotation()
  9301. }
  9302. this.startRotation()
  9303. } else {
  9304. // 停止旋转动画
  9305. this.isRotationRunning = false
  9306. clearInterval(this.timer)
  9307. this.stopRotation()
  9308. }
  9309. }
  9310. // 使用持续的动画进行旋转,避免频繁状态更新
  9311. private startContinuousRotation() {
  9312. clearInterval(this.timer)
  9313. // 改为每 1000ms 更新 36 度(10秒一圈),减少更新频率
  9314. // 不使用 % 360 取模,让角度持续累加,避免反转
  9315. this.timer = setInterval(() => {
  9316. if (this.isRotationRunning) {
  9317. this.rotateAngle = this.rotateAngle + 36
  9318. }
  9319. }, 1000)
  9320. }
  9321. // 定义开始旋转的方法
  9322. startRotation() {
  9323. if (this.isPlaying) {
  9324. animateTo({
  9325. duration: 777,
  9326. iterations: 1,
  9327. curve: Curve.Linear
  9328. }, () => {
  9329. this.rotateAngle2 = -9
  9330. })
  9331. }
  9332. }
  9333. // 回调,暂停和播放按钮回调,下一首和上一首
  9334. playChange() {
  9335. // if(this.isCoverRectangle){
  9336. // return
  9337. // }
  9338. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  9339. this.setIsPlaying(true)
  9340. this.animationState = AnimationStatus.Running
  9341. } else {
  9342. this.setIsPlaying(false)
  9343. this.animationState = AnimationStatus.Paused
  9344. }
  9345. AppStorage.setOrCreate('animationState', this.animationState);
  9346. }
  9347. // 定义停止旋转的方法
  9348. stopRotation() {
  9349. if (this.isCoverRectangle) {
  9350. this.rotateAngle = 0
  9351. } else {
  9352. //唱针以左上角为点选择逆时针40度
  9353. animateTo({
  9354. duration: 1000,
  9355. curve: Curve.Linear,
  9356. iterations: 1,
  9357. }, () => {
  9358. this.rotateAngle2 = -45;
  9359. });
  9360. }
  9361. }
  9362. @Builder
  9363. private LyricsTopItem() {
  9364. Row() {
  9365. Stack() {
  9366. Image(this.cover)
  9367. .height(58)
  9368. .width(58)
  9369. .clip(true)
  9370. .sourceSize({width:38, height:38})
  9371. .alt($r('app.media.alt'))
  9372. .borderRadius(8)
  9373. .clickEffect({ level: ClickEffectLevel.HEAVY })
  9374. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  9375. .shadow({
  9376. radius: 22,
  9377. type: ShadowType.BLUR,
  9378. color: 'on_primary'
  9379. })
  9380. }
  9381. .width('18%')
  9382. Column() {
  9383. Column() {
  9384. Text(this.name)
  9385. .fontSize(16)
  9386. .maxLines(1)
  9387. .fontWeight(FontWeight.Bolder)
  9388. .fontColor(Color.White)
  9389. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  9390. Row() {
  9391. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  9392. .fontSize(13)
  9393. .fontWeight(FontWeight.Bolder)
  9394. .padding({ top: 8 })
  9395. .fontColor(Color.White)
  9396. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  9397. Blank()
  9398. }
  9399. }
  9400. .height('100%')
  9401. .width('100%')
  9402. .justifyContent(FlexAlign.Center)
  9403. .alignItems(HorizontalAlign.Start)
  9404. }
  9405. .height('100%')
  9406. .width('65%')
  9407. Column() {
  9408. PointLightDefaultButton({
  9409. isSysBol:false,
  9410. pointColor:Color.White,
  9411. imageResource:$r('app.media.lyric'),
  9412. isPx: false,
  9413. builderHeight: 27,
  9414. builderWidth: 27,
  9415. })
  9416. .onClick(() => {
  9417. this.isLyricSetting = !this.isLyricSetting;
  9418. })
  9419. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  9420. height: '99%',
  9421. dragBar: true,
  9422. preferType: SheetType.CENTER,
  9423. showClose: true,
  9424. blurStyle: BlurStyle.Thin,
  9425. backgroundColor: Color.Transparent,
  9426. title: { title: $r('app.string.lyric_setting') }
  9427. })
  9428. }
  9429. .width('18%')
  9430. }
  9431. .width('82%')
  9432. .height(58)
  9433. .justifyContent(FlexAlign.SpaceBetween)
  9434. }
  9435. //歌词显示
  9436. @Builder
  9437. PlayerLyrics() {
  9438. Column() {
  9439. Column() {
  9440. this.LyricsTopItem()
  9441. }
  9442. .height(this.isPuraWP() ? 15 : 58)
  9443. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  9444. Visibility.None : Visibility.Visible)
  9445. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  9446. .width("100%")
  9447. Column() {
  9448. LyricView2({
  9449. controller: this.lyricController,
  9450. enableSeek: true,
  9451. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  9452. seekLineColor: "#80ffffff", // 滑动定位线颜色
  9453. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  9454. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  9455. if (!this.isPlaying) {
  9456. console.info('onecold startPlayOrResumePlay 7527')
  9457. this.startPlayOrResumePlay()
  9458. }
  9459. else {
  9460. this.isSeekTo = true;
  9461. this.mDestroyPage = false;
  9462. // 只有播放网盘歌曲时才显示转圈圈
  9463. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  9464. this.showLoadIng();
  9465. }
  9466. this.seekTo(position + "");
  9467. }
  9468. return true
  9469. }
  9470. })
  9471. .width("100%")
  9472. .layoutWeight(1)
  9473. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  9474. if (this.isPhoneLan()) {
  9475. Column() {
  9476. this.playProgressView()
  9477. }
  9478. .margin({ bottom: 32, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  9479. }
  9480. }
  9481. .position({
  9482. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  9483. (this.isPuraWP() ? 58 : 99)
  9484. })
  9485. .justifyContent(FlexAlign.Center)
  9486. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  9487. }
  9488. }
  9489. @Builder
  9490. SingleLyricView() {
  9491. Column() {
  9492. Column() {
  9493. LyricView2({
  9494. controller: this.lyricControllerSingle,
  9495. enableSeek: false,
  9496. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  9497. seekLineColor: "#80ffffff", // 滑动定位线颜色
  9498. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  9499. })
  9500. }
  9501. .height(82)
  9502. .margin({ bottom: 20 })
  9503. }
  9504. }
  9505. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  9506. @Builder
  9507. BottomControl() {
  9508. Column() {
  9509. this.TopPlayProgressView()
  9510. //播放 暂停,下一首,上一首
  9511. this.playCenterView()
  9512. if(!this.curDisplayIsHiCar){
  9513. //播放进度条
  9514. this.BottomView()
  9515. }
  9516. }
  9517. .justifyContent(FlexAlign.Center)
  9518. .alignItems(HorizontalAlign.Center)
  9519. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  9520. }
  9521. @Builder
  9522. playMenuBuilder(){
  9523. Image($r('app.media.menu'))
  9524. .width(24)
  9525. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9526. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  9527. height: '99%',
  9528. preferType:SheetType.CENTER,
  9529. dragBar: true,
  9530. showClose: true,
  9531. blurStyle: BlurStyle.Thin,
  9532. title: { title: $r('app.string.more') },
  9533. backgroundColor: Color.Transparent,
  9534. })
  9535. }
  9536. //播放控制上一首 下一首 暂停和播放
  9537. @Builder
  9538. playCenterView(){
  9539. Row() {
  9540. PointLightButton({
  9541. builder: () => {
  9542. this.playMenuBuilder()
  9543. },
  9544. isPx: false,
  9545. builderHeight: 32,
  9546. builderWidth: 32,
  9547. })
  9548. .onClick(async () =>{
  9549. this.isShowMoreView = !this.isShowMoreView;
  9550. })
  9551. PointLightButton({
  9552. builder: () => {
  9553. this.playPreviousBuilder()
  9554. },
  9555. isPx: false,
  9556. builderHeight: 32,
  9557. builderWidth: 32,
  9558. })
  9559. .onClick(async () =>{
  9560. await this.playPrevious()
  9561. })
  9562. PointLightButton({
  9563. builder: () => {
  9564. this.PlayOrPauseButton()
  9565. },
  9566. isPx: false,
  9567. builderHeight: this.isPhoneLan()?42:55,
  9568. builderWidth: this.isPhoneLan()?42:55,
  9569. })
  9570. .onClick(() =>{
  9571. this.playOrPause()
  9572. })
  9573. PointLightButton({
  9574. builder: () => {
  9575. this.playNextBuilder()
  9576. },
  9577. isPx: false,
  9578. builderHeight: 32,
  9579. builderWidth: 32,
  9580. })
  9581. .onClick(async () =>{
  9582. await this.playNext()
  9583. })
  9584. this.playModeButton()
  9585. }
  9586. .width('95%')
  9587. .margin({ bottom:this.isCoverOpacity()?0:15 })
  9588. .justifyContent(FlexAlign.SpaceEvenly)
  9589. }
  9590. @Builder
  9591. playPreviousBuilder(){
  9592. Image($r('app.media.ic_previous'))
  9593. .width(32)
  9594. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9595. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9596. }
  9597. @Builder
  9598. playNextBuilder(){
  9599. Image($r('app.media.ic_next'))
  9600. .width(32)
  9601. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9602. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9603. }
  9604. @Builder
  9605. PlayOrPauseButton(){
  9606. Stack() {
  9607. Column() {
  9608. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  9609. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  9610. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  9611. .width(this.isPhoneLan()?43:53)
  9612. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9613. .fillColor(Color.White)
  9614. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9615. }
  9616. // 加载进度圈
  9617. if (this.isPlayerLoading) {
  9618. Progress({value:0,total:100,type:ProgressType.Ring })
  9619. .width(this.isPhoneLan()?46:55)
  9620. .height(this.isPhoneLan()?46:55)
  9621. .color(Color.White)
  9622. .style({ strokeWidth: 5, status: ProgressStatus.LOADING })
  9623. }
  9624. }
  9625. .width(this.isPhoneLan()?43:53)
  9626. .height(this.isPhoneLan()?43:53)
  9627. }
  9628. @Builder
  9629. TopPlayProgressView(){
  9630. Column() {
  9631. Row(){
  9632. Stack(){
  9633. SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
  9634. .fontColor([Color.White])
  9635. .fontSize(21)
  9636. .effectStrategy(1)
  9637. Text(this.fastForwardSeconds)
  9638. .fontColor(Color.White)
  9639. .fontSize(10)
  9640. .fontWeight(FontWeight.Bold)
  9641. }
  9642. .padding({left:12,bottom:6})
  9643. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  9644. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9645. .onClick(()=>{
  9646. this.backForward()
  9647. })
  9648. Slider({
  9649. value: this.progressValue,
  9650. min: 0,
  9651. max: this.PROGRESS_MAX_VALUE,
  9652. step: 1,
  9653. style: SliderStyle.InSet
  9654. })
  9655. .height(20)
  9656. .blockColor('rgba(255,255,255,1)')
  9657. .trackColor('rgba(255,255,255,0.3)')
  9658. .selectedColor(Color.White)
  9659. .trackThickness(4)
  9660. .showSteps(false)
  9661. .showTips(true)
  9662. .layoutWeight(1)
  9663. .enabled(this.slideEnable)
  9664. .onChange((value: number, mode: SliderChangeMode) => {
  9665. if(this.isSeekTo)
  9666. return
  9667. this.isSeekTo = true;
  9668. this.mDestroyPage = false;
  9669. // 只有播放网盘歌曲时才显示转圈圈
  9670. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  9671. this.showLoadIng();
  9672. }
  9673. let seekValue = value * (this.getActiveDuration() / 100);
  9674. console.info("onecold this.currentSong.type:"+this.currentSong?.type)
  9675. this.seekTo(seekValue + "");
  9676. })
  9677. Stack(){
  9678. SymbolGlyph($r('sys.symbol.arrow_clockwise'))
  9679. .fontColor([Color.White])
  9680. .fontSize(21)
  9681. .effectStrategy(1)
  9682. Text(this.fastForwardSeconds)
  9683. .fontColor(Color.White)
  9684. .fontSize(10)
  9685. .fontWeight(FontWeight.Bold)
  9686. }
  9687. .padding({right:10,bottom:6})
  9688. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  9689. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9690. .onClick(()=>{
  9691. this.fastForward()
  9692. })
  9693. }
  9694. .justifyContent(FlexAlign.Center)
  9695. .padding({left:20,right:20})
  9696. .width(this.isLandscape?'88%':'95%')
  9697. Row() {
  9698. Text(this.currentTime)
  9699. .fontSize(10)
  9700. .fontColor(Color.White)
  9701. .margin({left:25})
  9702. Blank()
  9703. Text(this.totalTime)
  9704. .fontSize(10)
  9705. .fontColor(Color.White)
  9706. .margin({right:25})
  9707. }
  9708. .width(this.isLandscape?'85%':'90%')
  9709. .height(10)
  9710. }
  9711. .width('100%')
  9712. .alignItems(HorizontalAlign.Center)
  9713. }
  9714. @Builder
  9715. playModeButton(){
  9716. PointLightButton({
  9717. builder: () => {
  9718. this.playModeBuilder()
  9719. },
  9720. isPx: false,
  9721. builderHeight: 32,
  9722. builderWidth: 32,
  9723. })
  9724. .onClick(async () =>{
  9725. this.setLoopMode()
  9726. })
  9727. }
  9728. @Builder
  9729. playModeBuilder(){
  9730. Column() {
  9731. if (this.playType === 0) {
  9732. Image($r('app.media.loop'))
  9733. .width(26)
  9734. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9735. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9736. } else if (this.playType === 1) {
  9737. Image($r('app.media.single'))
  9738. .width(26)
  9739. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9740. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9741. } else if (this.playType === 2) {
  9742. Image($r('app.media.normal_play'))
  9743. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9744. .width(26)
  9745. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9746. } else if (this.playType === 3) {
  9747. Image($r('app.media.random'))
  9748. .width(26)
  9749. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9750. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9751. }
  9752. }
  9753. }
  9754. //播放进度条
  9755. @Builder
  9756. BottomView(){
  9757. Row() {
  9758. PointLightDefaultButton({
  9759. isSysBol:true,
  9760. pointColor:Color.White,
  9761. imageResource:$r('sys.symbol.rectangle_portrait_rotate'),
  9762. isPx: false,
  9763. builderHeight: 26,
  9764. builderWidth: 26,
  9765. })
  9766. .onClick(async () =>{
  9767. if (this.isLandscape) {
  9768. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  9769. } else {
  9770. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  9771. }
  9772. })
  9773. if(this.currentSong){
  9774. PointLightDefaultButton({
  9775. isSysBol:true,
  9776. pointColor:Color.White,
  9777. imageResource:$r('sys.symbol.rename'),
  9778. isPx: false,
  9779. builderHeight: 26,
  9780. builderWidth: 26,
  9781. })
  9782. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  9783. height: '99%',
  9784. dragBar: true,
  9785. showClose: true,
  9786. preferType: SheetType.BOTTOM,
  9787. title: { title: '编辑标签' }
  9788. })
  9789. .onClick(async () => {
  9790. this.initEditFields(this.currentSong)
  9791. this.tempLyricContent = this.lyricContent
  9792. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  9793. this.lyricConStr = this.tempLyricContent
  9794. }
  9795. this.isShowEdit = !this.isShowEdit;
  9796. })
  9797. }
  9798. PointLightDefaultButton({
  9799. isSysBol:false,
  9800. pointColor:Color.White,
  9801. imageResource:$r('app.media.lyric'),
  9802. isPx: false,
  9803. builderHeight: 26,
  9804. builderWidth: 26,
  9805. })
  9806. .onClick(async () => {
  9807. this.isLyricSetting = !this.isLyricSetting;
  9808. })
  9809. this.playListBuilder()
  9810. }
  9811. .width(this.isLandscape?'88%':'95%')
  9812. .justifyContent(FlexAlign.SpaceAround)
  9813. .visibility(this.showSimple?Visibility.None:Visibility.Visible)
  9814. .height(30)
  9815. .animation({
  9816. duration: 666,
  9817. curve: 'ease-in-out' // 可选动画曲线
  9818. })
  9819. }
  9820. @Builder
  9821. fullButton(){
  9822. Column() {
  9823. Image($r('app.media.full_4'))
  9824. .width(25)
  9825. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9826. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9827. }
  9828. }
  9829. @Builder
  9830. playListBuilder(){
  9831. PointLightDefaultButton({
  9832. isSysBol:true,
  9833. pointColor:Color.White,
  9834. imageResource:$r('sys.symbol.music_note_list'),
  9835. isPx: false,
  9836. builderHeight: 26,
  9837. builderWidth: 26,
  9838. })
  9839. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  9840. height: '95%',
  9841. dragBar: true,
  9842. showClose: true,
  9843. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9844. blurStyle: BlurStyle.Thin,
  9845. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  9846. title: {
  9847. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  9848. + `(${this.getPlayListDisplayCount()}首)`
  9849. }
  9850. })
  9851. .onClick(() => {
  9852. this.isShowSheetView = !this.isShowSheetView;
  9853. if(this.isPlayListBgGrass){
  9854. this.isFrontWhite = true
  9855. }else{
  9856. this.isFrontWhite = false
  9857. }
  9858. this.scrollIndex()
  9859. void this.hydrateFullMediaPlayListIfNeeded();
  9860. })
  9861. }
  9862. //旧版本播放进度条(现在是手机横屏的播放条)
  9863. @Builder
  9864. playProgressView() {
  9865. Row() {
  9866. Column(){
  9867. PointLightDefaultButton({
  9868. isSysBol:true,
  9869. pointColor:Color.White,
  9870. imageResource:$r('sys.symbol.rectangle_portrait_rotate'),
  9871. isPx: false,
  9872. builderHeight: 26,
  9873. builderWidth: 26,
  9874. })
  9875. .onClick(async () =>{
  9876. if (this.isLandscape) {
  9877. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  9878. } else {
  9879. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  9880. }
  9881. })
  9882. }
  9883. .margin({ right: 10,bottom:6})
  9884. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  9885. .animation({
  9886. duration: 666,
  9887. curve: 'ease-in-out' // 可选动画曲线
  9888. })
  9889. Text(this.currentTime)
  9890. .fontSize($r('app.float.slider_font_size'))
  9891. .fontColor(Color.White)
  9892. .margin(3)
  9893. Slider({
  9894. value: this.progressValue,
  9895. min: 0,
  9896. max: this.PROGRESS_MAX_VALUE,
  9897. step: 1,
  9898. style: SliderStyle.InSet
  9899. })
  9900. .width('600px')
  9901. .blockColor('rgba(255,255,255,1)')
  9902. .trackColor('rgba(255,255,255,0.3)')
  9903. .selectedColor(Color.White)
  9904. .trackThickness(5)
  9905. .layoutWeight(1)
  9906. .margin({top:4, left: PlayConstants.PROGRESS_MARGIN_LEFT })
  9907. .showSteps(false)
  9908. .showTips(true)
  9909. .enabled(this.slideEnable)
  9910. .onChange((value: number, mode: SliderChangeMode) => {
  9911. // if (mode == 2) {
  9912. this.isSeekTo = true;
  9913. this.mDestroyPage = false;
  9914. // 只有播放网盘歌曲时才显示转圈圈
  9915. console.info("onecold this.currentSong.type:"+this.currentSong?.type)
  9916. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  9917. console.info("onecold 开始转圈圈")
  9918. this.showLoadIng();
  9919. }
  9920. let seekValue = value * (this.getActiveDuration() / 100);
  9921. this.seekTo(seekValue + "");
  9922. })
  9923. Text(this.totalTime)
  9924. .fontSize($r('app.float.slider_font_size'))
  9925. .fontColor(Color.White)
  9926. .margin(3)
  9927. //播放列表
  9928. Column(){
  9929. this.playListBuilder()
  9930. }
  9931. .margin({ left: 10,bottom:6})
  9932. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  9933. .animation({
  9934. duration: 666,
  9935. curve: 'ease-in-out' // 可选动画曲线
  9936. })
  9937. }
  9938. //x5的竖屏模式需要99%
  9939. .width(this.isPhonePortrait() ? '93.4%'
  9940. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  9941. .height(this.isPhoneLan() ? 25 : 33)
  9942. .alignItems(VerticalAlign.Bottom)
  9943. .animation({
  9944. duration: 666,
  9945. curve: 'ease-in-out' // 可选动画曲线
  9946. })
  9947. }
  9948. isBigScreen() {
  9949. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  9950. return true
  9951. }
  9952. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  9953. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  9954. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  9955. return false
  9956. } else {
  9957. return true
  9958. }
  9959. return false
  9960. }
  9961. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  9962. // 添加控制缩放的状态变量
  9963. @State scaleValueImage: number = 1
  9964. @State scaleValueText: number = 1
  9965. @Builder
  9966. CoverInfo() {
  9967. Column() {
  9968. Stack() {
  9969. Column() {
  9970. //方形封面布局
  9971. if (this.isCoverRectangle) {
  9972. this.RectangleCoverView()
  9973. } else {
  9974. //圆形封面布局
  9975. this.CicleCoverView()
  9976. }
  9977. this.musicNameInfo(false)
  9978. if (this.isPhoneLan()) {
  9979. Text(this.name)
  9980. .fontSize(18)
  9981. .fontWeight(FontWeight.Bold)
  9982. .margin({ top: 13 })
  9983. .textOverflow({ overflow: TextOverflow.Ellipsis })
  9984. .maxLines(1)
  9985. .width('99%')
  9986. .textAlign(TextAlign.Center)
  9987. .fontColor(Color.White)
  9988. }
  9989. }
  9990. .width('100%')
  9991. Column({ space: 8 }) {
  9992. Text(this.name)
  9993. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  9994. .fontWeight(FontWeight.Bold)
  9995. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9996. .maxLines(1)
  9997. .width('85%')
  9998. .textAlign(TextAlign.Center)
  9999. .fontColor(Color.White)
  10000. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  10001. Text(this.artist)
  10002. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  10003. .fontColor(Color.White)
  10004. .fontWeight(FontWeight.Bold)
  10005. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  10006. }
  10007. .justifyContent(FlexAlign.Start)
  10008. .zIndex(1)
  10009. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  10010. }
  10011. .margin({
  10012. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  10013. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  10014. top: this.isCoverOpacity() ? 0 : 20
  10015. })
  10016. if (this.isPhonePortrait() && this.isShowSingleLineLyric) {
  10017. this.SingleLyricView()
  10018. }
  10019. if (this.isPhoneLan()) {
  10020. Column() {
  10021. this.playCenterView()
  10022. }
  10023. .position({ left: 28, bottom: 38 })
  10024. } else {
  10025. this.BottomControl()
  10026. }
  10027. }
  10028. .width(CommonConstants.FULL_PERCENT)
  10029. .clip(true)
  10030. }
  10031. //方形封面布局
  10032. @Builder
  10033. RectangleCoverView(){
  10034. Stack({alignContent:Alignment.Center}){
  10035. Image( StrUtil.isNotEmpty(this.cover)?
  10036. this.cover:$r('app.media.alt'))
  10037. .height(this.isHiCar()?(px2vp(this.windowHeight)*0.43):
  10038. this.isCoverOpacity()?(px2vp(this.windowHeight)*0.54):'auto')
  10039. .width(this.isHiCar()||this.isCoverOpacity()?'auto':this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '88%')
  10040. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  10041. .alt($r('app.media.alt'))
  10042. .margin({ right: 8, left: 8, top: 8 })
  10043. .aspectRatio(1)
  10044. .geometryTransition('cover') // 绑定标识符
  10045. .opacity(this.opacityValueImage)
  10046. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  10047. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  10048. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  10049. .clip(true)
  10050. .rotate({
  10051. x: 0,
  10052. y: 0,
  10053. z: 1,
  10054. angle: this.rotateAngle
  10055. })
  10056. .animation({
  10057. duration: 1000, // 与 setInterval 同步
  10058. curve: Curve.Linear,
  10059. iterations: 1
  10060. })
  10061. .shadow({
  10062. radius: 22,
  10063. type: ShadowType.BLUR,
  10064. color: 'on_primary'
  10065. })
  10066. .onClick(() => {
  10067. this.isMusicBGCover = !this.isMusicBGCover
  10068. })
  10069. }
  10070. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  10071. // 设置左下角为缩放中心点
  10072. centerX: '0%',
  10073. centerY: '100%' })
  10074. }
  10075. @Builder
  10076. CicleCoverView() {
  10077. //圆形封面布局
  10078. Stack({alignContent:Alignment.Center}) {
  10079. Image($r('app.media.ic_music_disc'))
  10080. .width(245)
  10081. .height(245)
  10082. .margin({ right: 20, left: 20 ,top:this.isCoverRectangle||this.isLandscape?0:50 })
  10083. .aspectRatio(1)
  10084. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  10085. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  10086. .borderRadius('100%')
  10087. .align(Alignment.Center)
  10088. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  10089. .rotate({
  10090. angle: this.rotateAngle,
  10091. centerX: "50%",
  10092. centerY: "50%",
  10093. })
  10094. .animation({
  10095. duration: 1000, // 改为 1000ms 与 setInterval 同步
  10096. curve: Curve.Linear,
  10097. iterations: 1 // 只执行一次,下一次更新会触发新的动画
  10098. })
  10099. .shadow({
  10100. radius: 22,
  10101. type: ShadowType.BLUR,
  10102. color: 'on_primary'
  10103. })
  10104. Image( StrUtil.isNotEmpty(this.cover)?
  10105. this.cover:$r('app.media.alt'))
  10106. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
  10107. (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 168))
  10108. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  10109. .alt($r('app.media.alt'))
  10110. .margin({ right: 20, left: 20,
  10111. top:this.isCoverRectangle||this.isLandscape?0:50})
  10112. .aspectRatio(1)
  10113. .opacity(this.opacityValueImage)
  10114. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  10115. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  10116. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  10117. .align(Alignment.Center)//
  10118. .clip(true)
  10119. .shadow({
  10120. radius: 22,
  10121. type: ShadowType.BLUR,
  10122. color: 'on_primary'
  10123. })
  10124. .rotate({
  10125. x: 0,
  10126. y: 0,
  10127. z: 1,
  10128. angle: this.rotateAngle
  10129. })
  10130. .animation({
  10131. duration: 1000, // 与 setInterval 同步
  10132. curve: Curve.Linear,
  10133. iterations: 1
  10134. })
  10135. .onClick(() => {
  10136. this.isMusicBGCover = !this.isMusicBGCover
  10137. })
  10138. // 唱针以左上角为点选择逆时针40度
  10139. Image($r('app.media.ic_music_cover_hand'))
  10140. .height(130)
  10141. .margin({ bottom: 200, top: 0 })
  10142. // .position({ x: this.windowWidth/2, y: 0 })
  10143. .align(Alignment.Top)
  10144. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  10145. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  10146. .visibility(this.isHiCar()||this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  10147. }
  10148. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  10149. // 设置左下角为缩放中心点
  10150. centerX: '0%',
  10151. centerY: '100%' })
  10152. }
  10153. @Builder
  10154. private musicNameInfo(isHidden: boolean) {
  10155. Row(){
  10156. Column({ space: 8 }) {
  10157. Text(this.name)
  10158. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 20)
  10159. .fontWeight(FontWeight.Bold)
  10160. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  10161. .maxLines(1)
  10162. .width('99%')
  10163. .textAlign(TextAlign.Start)
  10164. .fontColor(Color.White)
  10165. Text(this.artist + ' ' + this.currentSong?.album)
  10166. .fontSize(this.isCoverOpacity() ? 12 : 15)
  10167. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  10168. .fontColor(Color.White)
  10169. .textAlign(TextAlign.Start)
  10170. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  10171. .width('99%')
  10172. .maxLines(1)
  10173. }
  10174. .zIndex(1)
  10175. .layoutWeight(1)
  10176. .margin({ left: 15 })
  10177. Blank()
  10178. Row(){
  10179. Button({type:ButtonType.Circle,stateEffect:true}){
  10180. //添加或取消收藏
  10181. SymbolGlyph(Utility.getIsFav(this.favList,this.currentSong)?
  10182. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'))
  10183. .fontSize(22)
  10184. .fontColor([Color.White])
  10185. .alignSelf(ItemAlign.Center)
  10186. .clickEffect({level:ClickEffectLevel.MIDDLE})
  10187. .aspectRatio(CommonConstants.ASPECT_RATIO)
  10188. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  10189. .onClick(async () => {
  10190. if(this.currentSong){
  10191. this.doFav(this.currentSong)
  10192. }
  10193. })
  10194. }
  10195. .margin({ left: 8,right:8 })
  10196. .backgroundColor(Color.Transparent)
  10197. .width(45)
  10198. .height(45)
  10199. }
  10200. }
  10201. .width(this.isLandscape?'83%':'90%')
  10202. .scale({ x: this.scaleValueText, y: this.scaleValueText }) // 添加缩放效果
  10203. .margin({ top:this.isCoverRectangle?10: 0 })
  10204. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  10205. }
  10206. @Builder
  10207. private PlayTitle() {
  10208. Row() {
  10209. Row() {
  10210. Image($r('app.media.ic_back_down'))
  10211. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  10212. .hitTestBehavior(HitTestMode.Transparent)
  10213. }
  10214. .layoutWeight(1)
  10215. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10216. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  10217. .onClick(() => {
  10218. this.setShowPlayFalse()
  10219. })
  10220. Column() {
  10221. AVCastPicker({
  10222. normalColor: Color.White,
  10223. onStateChange: this.onStateVastChange
  10224. })
  10225. .width(24)
  10226. .height(24)
  10227. }
  10228. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  10229. }
  10230. .width(PlayConstants.ROW_WIDTH)
  10231. }
  10232. @Builder
  10233. lyricSettingSheet(isPip: boolean) {
  10234. Scroll() {
  10235. this.lyricSetting(isPip)
  10236. }
  10237. .width('100%')
  10238. .height('100%')
  10239. }
  10240. @Builder
  10241. lyricSetting(isPip: boolean) {
  10242. Column() {
  10243. // 时间调节模块
  10244. if (!isPip) {
  10245. this.BuildTimeControls()
  10246. }
  10247. // 字号控制模块
  10248. this.BuildFontControls(isPip)
  10249. }
  10250. }
  10251. // 歌词时间偏移状态
  10252. @State timeOffset: number = 0.0
  10253. @State currentLyricColor: string = '#FFFFFF'
  10254. @State currentLyricColorPip: string = '#FFFFFF'
  10255. @State currentHighLightLyricColor: string = '#FF4081'
  10256. @State currentHighLightLyricColorPip: string = '#FF4081'
  10257. // 歌词字号状态
  10258. @State currentLyricSize: number = 20
  10259. @State currentLyricSizePip: number = 20
  10260. // 高亮歌词放大倍数
  10261. @State currentHightLyricSize: number = 1.2
  10262. @State currentHightLyricSizePip: number = 1.2
  10263. @State currentLyricLineSpace: number = 10
  10264. @State currentLyricLineSpacePip: number = 10
  10265. @State currentLyricAlignMode: number = 1
  10266. @State currentLyricAlignModePip: number = 1
  10267. @State blurDegree: number = 2
  10268. @State blurDegreePip: number = 2
  10269. @State isShowSelectColor: boolean = false
  10270. @State isShowHLSelectColor: boolean = false
  10271. @State isShowPipBgSelectColor: boolean = false
  10272. @State pipLyWidth: number = 330
  10273. @State pipLyHeight: number = 120
  10274. // 构建颜色选择器
  10275. @Builder
  10276. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  10277. Row({ space: 10 }) {
  10278. HSBColorPicker({
  10279. color: '#FFFFFF',
  10280. radius: 8,
  10281. layout: HSBColorPickerLayout.COLUMN,
  10282. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  10283. '#fa7105'],
  10284. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  10285. this.changeLyricColor(value, isPip, isBGPip)
  10286. })
  10287. .height(250)
  10288. .layoutWeight(1)
  10289. .padding(25)
  10290. }
  10291. .width('66%')
  10292. }
  10293. @State isOpenPip: boolean = false
  10294. @State pipBgIndex: number = 0
  10295. // 构建字号控制器
  10296. @Builder
  10297. BuildFontControls(isPip: boolean) {
  10298. Column() {
  10299. if (isPip) {
  10300. Column() {
  10301. Row() {
  10302. Text('悬浮歌词')
  10303. .margin({ left: 18 })
  10304. .fontSize(15)
  10305. .fontColor(Color.White)
  10306. .fontWeight(480)
  10307. .layoutWeight(1)
  10308. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  10309. .selectedColor(this.themeColor)
  10310. .switchPointColor(Color.White)
  10311. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10312. .margin({ right: 18 })
  10313. .onChange((checked: boolean) => {
  10314. this.isOpenPip = checked;
  10315. if (this.isOpenPip) {
  10316. this.startPip()
  10317. } else {
  10318. this.stopPip()
  10319. }
  10320. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  10321. })
  10322. .width(50)
  10323. .height(30);
  10324. }
  10325. .height(55)
  10326. }
  10327. .backgroundColor(Color.Transparent)
  10328. .borderRadius(15)
  10329. .margin({
  10330. left: 30,
  10331. right: 30,
  10332. top: 0,
  10333. bottom: 20
  10334. })
  10335. .padding(0)
  10336. .border({
  10337. color: Color.White,
  10338. width: 1.8
  10339. })
  10340. }else{
  10341. Column() {
  10342. Row() {
  10343. Text('显示迷你歌词')
  10344. .margin({ left: 18 })
  10345. .fontSize(15)
  10346. .fontColor(Color.White)
  10347. .fontWeight(480)
  10348. .layoutWeight(1)
  10349. Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
  10350. .selectedColor(this.themeColor)
  10351. .switchPointColor(Color.White)
  10352. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10353. .margin({ right: 18 })
  10354. .onChange((checked: boolean) => {
  10355. this.isShowSingleLineLyric = checked;
  10356. PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
  10357. })
  10358. .width(50)
  10359. .height(30);
  10360. }
  10361. .height(55)
  10362. }
  10363. .backgroundColor(Color.Transparent)
  10364. .borderRadius(15)
  10365. .margin({
  10366. left: 30,
  10367. right: 30,
  10368. top: 10,
  10369. bottom: 10
  10370. })
  10371. .padding(0)
  10372. .border({
  10373. color: Color.White,
  10374. width: 1.8
  10375. })
  10376. }
  10377. Row() {
  10378. Text(`歌词居中:`)
  10379. .fontSize(14)
  10380. .fontColor(Color.White)
  10381. .margin({ left: 2 })
  10382. Row() {
  10383. ForEach(['居中', '居左'], (size: string, index: number) => {
  10384. Button(size)
  10385. .width(60)
  10386. .height(28)
  10387. .fontSize(12)
  10388. .fontColor('#FFFFFF')
  10389. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  10390. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  10391. .border({
  10392. color: (!isPip && this.currentLyricAlignMode === index) ||
  10393. (isPip && this.currentLyricAlignModePip === index) ?
  10394. '#007DFF' : '#DDDDDD',
  10395. width: 1.8
  10396. })
  10397. .onClick(() => {
  10398. this.setLyricAlignMode(index, isPip)
  10399. })
  10400. .margin({ left: 10, right: 8 })
  10401. })
  10402. }
  10403. .width('76%')
  10404. Blank()
  10405. }
  10406. .margin({
  10407. top: 10,
  10408. bottom: 10,
  10409. right: 20,
  10410. left: 20
  10411. })
  10412. if (isPip) {
  10413. Row() {
  10414. Text(`悬浮背景:`)
  10415. .fontSize(14)
  10416. .fontColor(Color.White)
  10417. Select([
  10418. { value: CommonConstants.PIP_LYRIC_BG[0] },
  10419. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  10420. .font({ size: 13, weight: FontWeight.Medium })
  10421. .fontColor(Color.White)
  10422. .margin({ left: 10 })
  10423. .selected(this.pipBgIndex)
  10424. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  10425. .onSelect(async (_index: number, text?: string | undefined) => {
  10426. this.pipBgIndex = _index
  10427. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  10428. if (this.pipBgIndex === 0) {
  10429. if (this.cover) {
  10430. this.pipBg = this.cover
  10431. } else {
  10432. this.pipBg = this.imageColor
  10433. }
  10434. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  10435. } else {
  10436. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  10437. }
  10438. })
  10439. Column() {
  10440. }
  10441. .backgroundColor(this.pipBg)
  10442. .margin({ left: 10, right: 10 })
  10443. .borderRadius(20)
  10444. .height(28)
  10445. .width(28)
  10446. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10447. Row() {
  10448. SymbolGlyph($r('sys.symbol.paintbrush'))
  10449. .fontColor([Color.White])
  10450. .effectStrategy(1)
  10451. Text(`选择颜色`)
  10452. .fontSize(13)
  10453. .margin({ left: 10 })
  10454. .fontColor(Color.White)
  10455. }
  10456. }
  10457. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  10458. .backgroundColor(Color.Transparent)
  10459. .border({
  10460. color: '#FFFFFF',
  10461. radius: 20,
  10462. width: 1.8
  10463. })
  10464. .height(36)
  10465. .width(110)
  10466. .onClick(() => {
  10467. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  10468. })
  10469. .bindPopup(this.isShowPipBgSelectColor, {
  10470. builder: this.SelectColor(false, isPip, true),
  10471. placement: Placement.Top,
  10472. mask: { color: '#33000000' },
  10473. enableArrow: false, //是否显示箭头
  10474. showInSubWindow: false,
  10475. onStateChange: (e) => {
  10476. if (!e.isVisible) {
  10477. this.isShowPipBgSelectColor = false
  10478. }
  10479. }
  10480. })
  10481. }
  10482. .width('76%')
  10483. .margin({ bottom: 5, right: 45, left: 20 })
  10484. }
  10485. if (!isPip) {
  10486. Row() {
  10487. Text(`高亮居中:`)
  10488. .fontSize(14)
  10489. .fontColor(Color.White)
  10490. Column() {
  10491. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  10492. .selectedColor(this.themeColor)
  10493. .switchPointColor(Color.White)
  10494. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10495. .onChange((checked: boolean) => {
  10496. this.isHightLightCenter = checked;
  10497. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  10498. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  10499. })
  10500. .width(50)
  10501. .height(30)
  10502. .alignSelf(ItemAlign.Start)
  10503. .margin({ left: 12 })
  10504. Blank()
  10505. }
  10506. .width('76%')
  10507. }
  10508. .margin({
  10509. left: 20,
  10510. right: 15,
  10511. top: 10,
  10512. bottom: 10
  10513. })
  10514. }
  10515. Row() {
  10516. Text(`歌词颜色:`)
  10517. .fontSize(14)
  10518. .fontColor(Color.White)
  10519. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  10520. .fontSize(15)
  10521. .fontColor(Color.White)
  10522. .margin({ left: 12, right: 12 })
  10523. Column() {
  10524. }
  10525. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  10526. .margin({ right: 12 })
  10527. .borderRadius(20)
  10528. .height(28)
  10529. .width(28)
  10530. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10531. Row() {
  10532. SymbolGlyph($r('sys.symbol.paintbrush'))
  10533. .fontColor([Color.White])
  10534. .effectStrategy(1)
  10535. Text(`选择颜色`)
  10536. .fontSize(13)
  10537. .margin({ left: 10 })
  10538. .fontColor(Color.White)
  10539. }
  10540. }
  10541. .backgroundColor(Color.Transparent)
  10542. .border({
  10543. color: '#FFFFFF',
  10544. radius: 20,
  10545. width: 1.8
  10546. })
  10547. .height(36)
  10548. .width(110)
  10549. .onClick(() => {
  10550. this.isShowSelectColor = !this.isShowSelectColor
  10551. })
  10552. .bindPopup(this.isShowSelectColor, {
  10553. builder: this.SelectColor(false, isPip),
  10554. placement: Placement.Top,
  10555. mask: { color: '#33000000' },
  10556. enableArrow: false, //是否显示箭头
  10557. showInSubWindow: false,
  10558. onStateChange: (e) => {
  10559. if (!e.isVisible) {
  10560. this.isShowSelectColor = false
  10561. }
  10562. }
  10563. })
  10564. }
  10565. .width('76%')
  10566. .margin({
  10567. top: 10,
  10568. bottom: 10,
  10569. right: 45,
  10570. left: 20
  10571. })
  10572. Row() {
  10573. Text(`高亮颜色:`)
  10574. .fontSize(14)
  10575. .fontColor(Color.White)
  10576. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  10577. .fontSize(15)
  10578. .fontColor(Color.White)
  10579. .margin({ left: 12, right: 12 })
  10580. Column() {
  10581. }
  10582. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  10583. .margin({ right: 12 })
  10584. .borderRadius(20)
  10585. .height(28)
  10586. .width(28)
  10587. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10588. Row() {
  10589. SymbolGlyph($r('sys.symbol.paintbrush'))
  10590. .fontColor([Color.White])
  10591. .effectStrategy(1)
  10592. Text(`选择颜色`)
  10593. .fontSize(13)
  10594. .margin({ left: 10 })
  10595. .fontColor(Color.White)
  10596. }
  10597. }
  10598. .backgroundColor(Color.Transparent)
  10599. .border({
  10600. color: '#FFFFFF',
  10601. radius: 20,
  10602. width: 1.8
  10603. })
  10604. .height(36)
  10605. .width(110)
  10606. .onClick(() => {
  10607. this.isShowHLSelectColor = !this.isShowHLSelectColor
  10608. })
  10609. .bindPopup(this.isShowHLSelectColor, {
  10610. builder: this.SelectColor(true, isPip),
  10611. placement: Placement.Top,
  10612. mask: { color: '#33000000' },
  10613. enableArrow: false, //是否显示箭头
  10614. showInSubWindow: false,
  10615. onStateChange: (e) => {
  10616. if (!e.isVisible) {
  10617. this.isShowHLSelectColor = false
  10618. }
  10619. }
  10620. })
  10621. }
  10622. .width('76%')
  10623. .margin({
  10624. top: 10,
  10625. bottom: 10,
  10626. right: 45,
  10627. left: 20
  10628. })
  10629. if (isPip) {
  10630. Row() {
  10631. Text(`显示宽度:`)
  10632. .fontSize(14)
  10633. .fontColor(Color.White)
  10634. Slider({
  10635. value: this.pipLyWidth,
  10636. min: 10,
  10637. max: 800,
  10638. step: 1,
  10639. style: SliderStyle.OutSet
  10640. })
  10641. .blockColor(this.themeColor)
  10642. .trackColor($r('app.color.speed_text_color'))
  10643. .selectedColor(Color.White)
  10644. .trackThickness(6)
  10645. .onChange((value: number) => {
  10646. this.pipLyWidth = value
  10647. if (this.pipController) {
  10648. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  10649. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  10650. }
  10651. })
  10652. .width('76%')
  10653. }
  10654. .margin({
  10655. left: 20,
  10656. right: 15,
  10657. top: 5,
  10658. bottom: 5
  10659. })
  10660. Row() {
  10661. Text(`显示高度:`)
  10662. .fontSize(14)
  10663. .fontColor(Color.White)
  10664. Slider({
  10665. value: this.pipLyHeight,
  10666. min: 10,
  10667. max: 1000,
  10668. step: 1,
  10669. style: SliderStyle.OutSet
  10670. })
  10671. .blockColor(this.themeColor)
  10672. .trackColor($r('app.color.speed_text_color'))
  10673. .selectedColor(Color.White)
  10674. .trackThickness(6)
  10675. .onChange((value: number) => {
  10676. this.pipLyHeight = value
  10677. if (this.pipController) {
  10678. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  10679. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  10680. }
  10681. })
  10682. .width('76%')
  10683. }
  10684. .margin({
  10685. left: 20,
  10686. right: 15,
  10687. top: 5,
  10688. bottom: 5
  10689. })
  10690. }
  10691. Row() {
  10692. Text(`歌词字号:`)
  10693. .fontSize(14)
  10694. .fontColor(Color.White)
  10695. Slider({
  10696. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  10697. min: 12,
  10698. max: 30,
  10699. step: 0.1,
  10700. style: SliderStyle.OutSet
  10701. })
  10702. .blockColor(this.themeColor)
  10703. .trackColor($r('app.color.speed_text_color'))
  10704. .selectedColor(Color.White)
  10705. .trackThickness(6)
  10706. .onChange((value: number) => {
  10707. this.setLyricTextSize(value, isPip)
  10708. })
  10709. .width('76%')
  10710. }
  10711. .margin({
  10712. left: 20,
  10713. right: 15,
  10714. top: 5,
  10715. bottom: 5
  10716. })
  10717. Row() {
  10718. Text(`高亮倍数:`)
  10719. .fontSize(14)
  10720. .fontColor(Color.White)
  10721. Slider({
  10722. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  10723. min: 1,
  10724. max: 2,
  10725. step: 0.1,
  10726. style: SliderStyle.OutSet
  10727. })
  10728. .blockColor(this.themeColor)
  10729. .trackColor($r('app.color.speed_text_color'))
  10730. .selectedColor(Color.White)
  10731. .trackThickness(6)
  10732. .onChange((value: number) => {
  10733. this.setHighLyricTextSize(value, isPip)
  10734. })
  10735. .width('76%')
  10736. }
  10737. .margin({
  10738. left: 20,
  10739. right: 15,
  10740. top: 5,
  10741. bottom: 5
  10742. })
  10743. Row() {
  10744. Text(`歌词间隙:`)
  10745. .fontSize(14)
  10746. .fontColor(Color.White)
  10747. Slider({
  10748. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  10749. min: 0,
  10750. max: 100,
  10751. step: 1,
  10752. style: SliderStyle.OutSet
  10753. })
  10754. .blockColor(this.themeColor)
  10755. .trackColor($r('app.color.speed_text_color'))
  10756. .selectedColor(Color.White)
  10757. .trackThickness(6)
  10758. .onChange((value: number) => {
  10759. this.setLyricLineSpace(value, isPip)
  10760. })
  10761. .width('76%')
  10762. }
  10763. .margin({
  10764. left: 20,
  10765. right: 15,
  10766. top: 5,
  10767. bottom: 5
  10768. })
  10769. //取值间隔为100,默认为400,取值越大,字体越粗
  10770. Row() {
  10771. Text(`歌词字重:`)
  10772. .fontSize(14)
  10773. .fontColor(Color.White)
  10774. Slider({
  10775. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  10776. min: 100,
  10777. max: 900,
  10778. step: 100,
  10779. style: SliderStyle.OutSet
  10780. })
  10781. .blockColor(this.themeColor)
  10782. .trackColor($r('app.color.speed_text_color'))
  10783. .selectedColor(Color.White)
  10784. .trackThickness(6)
  10785. .onChange((value: number) => {
  10786. if (isPip) {
  10787. this.lyricTextWeightPip = value
  10788. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  10789. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  10790. } else {
  10791. this.lyricTextWeight = value
  10792. this.lyricController.setTextWeight(this.lyricTextWeight)
  10793. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  10794. }
  10795. })
  10796. .width('76%')
  10797. }
  10798. .margin({
  10799. left: 20,
  10800. right: 15,
  10801. top: 5,
  10802. bottom: 5
  10803. })
  10804. Row() {
  10805. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  10806. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  10807. // this.pushLyricButton($r('app.media.white_search'), 1, '繁体转简体')
  10808. }
  10809. .justifyContent(FlexAlign.Center)
  10810. .margin({ top: 3, bottom: 10 })
  10811. }
  10812. }
  10813. private setBlurDegree(index: number, isPip: boolean) {
  10814. if (isPip) {
  10815. this.blurDegreePip = index
  10816. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  10817. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  10818. } else {
  10819. this.blurDegree = index
  10820. this.lyricController.setBlurDegree(this.blurDegree)
  10821. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  10822. }
  10823. }
  10824. private setLyricAlignMode(index: number, isPip: boolean) {
  10825. if (isPip) {
  10826. this.currentLyricAlignModePip = index
  10827. if (this.currentLyricAlignModePip === 1) {
  10828. this.lyricControllerXF.setAlignMode("left")
  10829. } else {
  10830. this.lyricControllerXF.setAlignMode("center")
  10831. }
  10832. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  10833. } else {
  10834. this.currentLyricAlignMode = index
  10835. if (this.currentLyricAlignMode === 1) {
  10836. this.lyricController.setAlignMode("left")
  10837. } else {
  10838. this.lyricController.setAlignMode("center")
  10839. }
  10840. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  10841. }
  10842. }
  10843. private setLyricTextSize(index: number, isPip: boolean) {
  10844. if (isPip) {
  10845. this.currentLyricSizePip = index
  10846. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  10847. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  10848. } else {
  10849. this.currentLyricSize = index
  10850. this.lyricController.setTextSize(this.currentLyricSize)
  10851. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  10852. }
  10853. }
  10854. private setHighLyricTextSize(scale: number, isPip: boolean) {
  10855. if (isPip) {
  10856. this.currentHightLyricSizePip = scale
  10857. this.lyricControllerXF
  10858. .setHighlightScale(this.currentHightLyricSizePip)
  10859. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  10860. } else {
  10861. this.currentHightLyricSize = scale
  10862. this.lyricController
  10863. .setHighlightScale(this.currentHightLyricSize)
  10864. PreferencesUtil.putSync('HighLyricTextSize', scale)
  10865. }
  10866. }
  10867. private setLyricLineSpace(index: number, isPip: boolean) {
  10868. if (isPip) {
  10869. this.currentLyricLineSpacePip = index
  10870. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  10871. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  10872. } else {
  10873. this.currentLyricLineSpace = index
  10874. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  10875. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  10876. }
  10877. }
  10878. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  10879. LogUtil.info('onecold isBG = ' + isBG)
  10880. if (isBG) { //如果是设置悬浮背景
  10881. this.pipBg = color
  10882. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  10883. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  10884. return
  10885. }
  10886. if (isPip) {
  10887. this.currentLyricColorPip = color
  10888. this.lyricControllerXF
  10889. .setTextColor(this.currentLyricColorPip)
  10890. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  10891. } else {
  10892. this.currentLyricColor = color
  10893. this.lyricController
  10894. .setTextColor(this.currentLyricColor)
  10895. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  10896. }
  10897. }
  10898. private changeLyricHightLightColor(color: string, isPip: boolean) {
  10899. if (isPip) {
  10900. this.currentHighLightLyricColorPip = color
  10901. this.lyricControllerXF
  10902. .setHighlightColor(this.currentHighLightLyricColorPip)
  10903. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  10904. } else {
  10905. this.currentHighLightLyricColor = color
  10906. this.lyricController
  10907. .setHighlightColor(this.currentHighLightLyricColor)
  10908. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  10909. }
  10910. }
  10911. // 构建时间控制器
  10912. @Builder
  10913. BuildTimeControls() {
  10914. Column() {
  10915. // 时间显示
  10916. Text(this.getTimeText())
  10917. .fontSize(18)
  10918. .fontColor(Color.White)
  10919. .margin({ bottom: 10 })
  10920. Row() {
  10921. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  10922. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  10923. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  10924. }
  10925. .justifyContent(FlexAlign.Center)
  10926. }
  10927. .margin({ top: 12, bottom: 8 })
  10928. }
  10929. // 精度按钮组件
  10930. @Builder
  10931. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  10932. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10933. Column() {
  10934. Image(icon)
  10935. .width(28)
  10936. .margin({ bottom: 5 })
  10937. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  10938. Text(label)
  10939. .fontSize(12)
  10940. .fontColor('#FFFFFF')
  10941. }
  10942. }
  10943. .backgroundColor(Color.Transparent)
  10944. .enabled(!this.isButtonDisabled(step))
  10945. .onClick(() => this.handlePrecisionAdjust(step))
  10946. .padding(5)
  10947. .width(66)
  10948. .height(66)
  10949. .margin({ left: 18, right: 18 })
  10950. .border({
  10951. color: '#FFFFFF',
  10952. width: 1.8
  10953. })
  10954. }
  10955. private handlePrecisionAdjust(step: number) {
  10956. if (step === 0) {
  10957. this.timeOffset = 0
  10958. return
  10959. }
  10960. // 精度处理:保留1位小数
  10961. const newOffset = Number((this.timeOffset + step).toFixed(5))
  10962. // 边界保护(±15.0秒)
  10963. if (newOffset < -30.0 || newOffset > 30.0) {
  10964. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  10965. return
  10966. }
  10967. // 状态更新
  10968. this.timeOffset = newOffset
  10969. }
  10970. // 按钮禁用逻辑
  10971. private isButtonDisabled(step: number): boolean {
  10972. const futureOffset = this.timeOffset + step
  10973. return (futureOffset < -30.0) || (futureOffset > 30.0)
  10974. }
  10975. // 时间显示文本升级
  10976. private getTimeText(): string {
  10977. const absValue = Math.abs(this.timeOffset)
  10978. return this.timeOffset === 0
  10979. ? '歌词时间已重置'
  10980. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  10981. }
  10982. // 导入 本地歌词 搜索歌词
  10983. @Builder
  10984. pushLyricButton(icon: Resource, step: number, label: string) {
  10985. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10986. Row() {
  10987. Image(icon)
  10988. .width(14)
  10989. .margin({ left: 13 })
  10990. Text(label)
  10991. .fontSize(12)
  10992. .margin({ left: 6 })
  10993. .fontColor('#FFFFFF')
  10994. }
  10995. }
  10996. .onClick(() => {
  10997. switch (step) {
  10998. case 0:
  10999. this.callFilePickerSelectFileForLyric()
  11000. break;
  11001. case 1:
  11002. //判断有没有设置api
  11003. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  11004. this.isLyricSetting = false
  11005. this.showTipsDialog()
  11006. return
  11007. }
  11008. if (StrUtil.isNotEmpty(this.videoUrl)) {
  11009. ToastUtil.showToast('正在获取')
  11010. this.isLyricSetting = false
  11011. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  11012. this.initLyric(lyricPath, true);
  11013. }
  11014. break;
  11015. }
  11016. })
  11017. .padding(5)
  11018. .width(110)
  11019. .backgroundColor(Color.Transparent)
  11020. .height(40)
  11021. .margin({ left: 6, right: 6 })
  11022. .border({
  11023. color: '#FFFFFF',
  11024. radius: 20,
  11025. width: 1.8
  11026. })
  11027. }
  11028. showVipDialog() {
  11029. DialogHelper.showCustomContentDialog({
  11030. dialogId: 'vip',
  11031. title: "友情提示",
  11032. autoCancel: false, //点击遮障层时,不关闭弹窗
  11033. backCancel: true, //点击返回键,不关闭弹窗
  11034. contentBuilder: () => {
  11035. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  11036. },
  11037. buttons: [],
  11038. })
  11039. }
  11040. //去赞助的自定义内容
  11041. @Builder
  11042. customVipBuilder(content: string) {
  11043. Column() {
  11044. Text(content)
  11045. .fontColor(Color.Gray)
  11046. .fontSize(16)
  11047. .alignSelf(ItemAlign.Start)
  11048. .margin({ bottom: 15 })
  11049. .fontSize(16)
  11050. Row() {
  11051. Button('取消')
  11052. .fontColor(Color.White)
  11053. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  11054. .height(50)
  11055. .layoutWeight(1)
  11056. .stateEffect(true)
  11057. .margin({ right: 6 })
  11058. .onClick(() => {
  11059. DialogHelper.closeDialog('vip'); //关闭弹框
  11060. })
  11061. Button('开通')
  11062. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  11063. .layoutWeight(1)
  11064. .height(50)
  11065. .backgroundColor(this.themeColor)
  11066. .stateEffect(true)
  11067. .margin({ left: 6 })
  11068. .onClick(() => {
  11069. DialogHelper.closeDialog('vip'); //关闭弹框
  11070. this.isShowPlay = false
  11071. this.mType = 1 //跳转到用户中心
  11072. // router.pushUrl({
  11073. // url: 'pages/VipPage'
  11074. // }, router.RouterMode.Single);
  11075. })
  11076. }
  11077. }
  11078. .width("100%")
  11079. .padding(10)
  11080. }
  11081. showTipsDialog() {
  11082. DialogHelper.showCustomContentDialog({
  11083. dialogId: 'tips',
  11084. title: "友情提示",
  11085. autoCancel: false, //点击遮障层时,不关闭弹窗
  11086. backCancel: true, //点击返回键,不关闭弹窗
  11087. contentBuilder: () => {
  11088. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  11089. },
  11090. buttons: [],
  11091. })
  11092. }
  11093. @Builder
  11094. customTipsBuilder(content: string) {
  11095. Column() {
  11096. Text(content)
  11097. .fontColor(Color.Gray)
  11098. .fontSize(16)
  11099. .alignSelf(ItemAlign.Start)
  11100. .margin({ bottom: 15 })
  11101. .fontSize(16)
  11102. Row() {
  11103. Button('取消')
  11104. .fontColor(Color.White)
  11105. .backgroundColor(this.themeColor)
  11106. .height(50)
  11107. .layoutWeight(1)
  11108. .stateEffect(true)
  11109. .margin({ right: 6 })
  11110. .onClick(() => {
  11111. DialogHelper.closeDialog('tips'); //关闭弹框
  11112. })
  11113. Button('跳转')
  11114. .fontColor(Color.White)//
  11115. .layoutWeight(1)
  11116. .height(50)
  11117. .backgroundColor(this.themeColor)
  11118. .stateEffect(true)
  11119. .margin({ left: 6 })
  11120. .onClick(() => {
  11121. DialogHelper.closeDialog('tips'); //关闭弹框
  11122. this.isShowEdit = false
  11123. this.longItemFilePath = ''
  11124. // if(this.isGridMusic&&!this.isShowPlay){
  11125. // this.longItemFilePath== ''
  11126. // }else{
  11127. // this.isShowEdit = false
  11128. // }
  11129. this.isShowMoreView = false;
  11130. this.isShowPlay = false
  11131. this.mType = 4
  11132. // router.pushUrl({
  11133. // url: 'pages/SettingPage'
  11134. // }, router.RouterMode.Single);
  11135. })
  11136. }
  11137. }
  11138. .width("100%")
  11139. .padding(10)
  11140. }
  11141. @Builder
  11142. PlayMoreSheet() {
  11143. Column() {
  11144. this.MoreList()
  11145. }
  11146. .width('100%')
  11147. .height('100%')
  11148. }
  11149. @Builder
  11150. MoreList() {
  11151. Scroll() {
  11152. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  11153. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  11154. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  11155. Row() {
  11156. if (more.id === 3&&this.currentSong) {
  11157. Image(more.image)
  11158. .width(24)
  11159. .height(24)
  11160. .margin({ left: 10, right: 10 })
  11161. Text(more.title)
  11162. .fontSize(16)
  11163. .fontColor(Color.White)
  11164. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  11165. height: '99%',
  11166. dragBar: true,
  11167. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11168. showClose: true,
  11169. blurStyle: BlurStyle.Thin,
  11170. backgroundColor: Color.Transparent,
  11171. title: { title: '歌曲信息' }
  11172. })
  11173. } else if (more.id === 15 && this.currentSong) { //编辑标签
  11174. Image(more.image)
  11175. .width(24)
  11176. .height(24)
  11177. .margin({ left: 10, right: 10 })
  11178. Text(more.title)
  11179. .fontSize(16)
  11180. .fontColor(Color.White)
  11181. } else if (more.id === 5) { //定时关闭
  11182. Image(more.image)
  11183. .width(24)
  11184. .height(24)
  11185. .margin({ left: 10, right: 10 })
  11186. Text(more.title)
  11187. .fontSize(16)
  11188. .fontColor(Color.White)
  11189. .onClick(() => {
  11190. this.doMore(more.id)
  11191. })
  11192. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  11193. height: this.isCoverOpacity() ? '95%' : '95%',
  11194. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11195. dragBar: true,
  11196. showClose: true,
  11197. title: { title: $r('app.string.time_close') }
  11198. })
  11199. } else if (more.id === 2) { //歌词设置
  11200. Image(more.image)
  11201. .width(24)
  11202. .height(24)
  11203. .margin({ left: 10, right: 10 })
  11204. Text(more.title)
  11205. .fontSize(16)
  11206. .fontColor(Color.White)
  11207. } else if (more.id === 16) { //悬浮歌词设置
  11208. Image(more.image)
  11209. .width(24)
  11210. .height(24)
  11211. .margin({ left: 10, right: 10 })
  11212. Text(more.title)
  11213. .fontSize(16)
  11214. .fontColor(Color.White)
  11215. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  11216. height: '99%',
  11217. dragBar: true,
  11218. preferType: SheetType.CENTER,
  11219. showClose: true,
  11220. blurStyle: BlurStyle.Thin,
  11221. backgroundColor: Color.Transparent,
  11222. title: { title: '悬浮歌词' }
  11223. })
  11224. } else if (more.id === 11) {
  11225. Image(more.image)
  11226. .width(24)
  11227. .height(24)
  11228. .margin({ left: 10, right: 10 })
  11229. Text(more.title)
  11230. .fontSize(16)
  11231. .fontColor(Color.White)
  11232. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  11233. height: this.isCoverOpacity() ? '95%' : '60%',
  11234. dragBar: true,
  11235. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11236. showClose: true,
  11237. blurStyle: BlurStyle.Thin,
  11238. backgroundColor: Color.Transparent,
  11239. title: { title: '跳过头尾' }
  11240. })
  11241. } else if (more.id === 12) { //投播
  11242. AVCastPicker({
  11243. customPicker: (): void => this.TPImageBuilder(more),
  11244. onStateChange: (state) => {
  11245. if (state == AVCastPickerState.STATE_APPEARING) {
  11246. console.log(' The picker starts showing.');
  11247. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  11248. console.log(' The picker finishes presenting.');
  11249. }
  11250. },
  11251. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  11252. sessionType: 'video'
  11253. })
  11254. .id('AVCastPicker')
  11255. } else {
  11256. Image(more.image)
  11257. .width(24)
  11258. .height(24)
  11259. .fillColor(Color.White)
  11260. .margin({ left: 10, right: 10 })
  11261. .onClick(() => {
  11262. this.doMore(more.id)
  11263. })
  11264. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  11265. .fontSize(16)
  11266. .fontColor(Color.White)
  11267. .onClick(() => {
  11268. this.doMore(more.id)
  11269. })
  11270. Select([//倍速
  11271. { value: '0.25x' },
  11272. { value: '0.5x' },
  11273. { value: '0.75x' },
  11274. { value: '1x' },
  11275. { value: '1.25x' },
  11276. { value: '1.5x' },
  11277. { value: '1.75x' },
  11278. { value: '2x' },
  11279. { value: '3x' }])
  11280. .font({ size: 16, weight: FontWeight.Medium })
  11281. .fontColor($r('sys.color.white'))
  11282. .margin({ left: 25 })
  11283. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  11284. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  11285. .value(Utility.optimizedFormat(this.playSpeed))
  11286. .onSelect(async (_index: number, text?: string | undefined) => {
  11287. let speed = parseFloat(text?.replace('x', '') || '1');
  11288. if (!CommonConstants.video_speed_list.includes(speed)) {
  11289. speed = 1;
  11290. }
  11291. this.playSpeed = speed
  11292. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  11293. })
  11294. Slider({
  11295. value: this.volume,
  11296. min: 0,
  11297. max: 1,
  11298. step: 0.1,
  11299. style: SliderStyle.OutSet
  11300. })
  11301. .margin({ left: 18, right: 8 })
  11302. .blockColor(this.themeColor)
  11303. .trackColor($r('app.color.speed_text_color'))
  11304. .selectedColor(Color.White)
  11305. .trackThickness(9)
  11306. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  11307. .onChange((value: number) => {
  11308. this.volume = value;
  11309. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  11310. PreferencesUtil.putSync('DefalutVolume',this.volume)
  11311. })
  11312. .layoutWeight(1)
  11313. Blank()
  11314. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  11315. .selectedColor(this.themeColor)
  11316. .switchPointColor(Color.White)
  11317. .margin({ right: 15 })
  11318. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11319. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  11320. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11321. if (more.id == 6) {
  11322. this.isMusicMemoryPlay = checked;
  11323. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  11324. if (this.isMusicMemoryPlay) {
  11325. ToastUtil.showToast('记忆播放已开启')
  11326. } else {
  11327. ToastUtil.showToast('记忆播放已关闭')
  11328. }
  11329. }
  11330. })
  11331. .width(48)
  11332. .height(24);
  11333. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  11334. .selectedColor(this.themeColor)
  11335. .switchPointColor(Color.White)
  11336. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11337. .margin({ right: 15 })
  11338. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  11339. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11340. if (more.id == 7) {
  11341. this.isMusicBGCover = checked;
  11342. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  11343. if (this.isMusicBGCover) {
  11344. ToastUtil.showToast('播放背景随音乐封面已开启')
  11345. } else {
  11346. ToastUtil.showToast('播放背景随音乐封面已关闭')
  11347. }
  11348. }
  11349. })
  11350. .width(48)
  11351. .height(24);
  11352. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  11353. .selectedColor(this.themeColor)
  11354. .switchPointColor(Color.White)
  11355. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11356. .margin({ right: 15 })
  11357. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  11358. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11359. if (more.id == 8) {
  11360. this.isSavePlayMode = checked;
  11361. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  11362. if (this.isSavePlayMode) {
  11363. ToastUtil.showToast('保存播放模式已开启')
  11364. } else {
  11365. ToastUtil.showToast('保存播放模式已关闭')
  11366. }
  11367. }
  11368. })
  11369. .width(48)
  11370. .height(24);
  11371. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  11372. .selectedColor(this.themeColor)
  11373. .switchPointColor(Color.White)
  11374. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11375. .margin({ right: 15 })
  11376. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  11377. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11378. if (more.id == 13) {
  11379. this.isCoverRectangle = checked;
  11380. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  11381. if (this.isCoverRectangle) {
  11382. ToastUtil.showToast('封面方形已开启')
  11383. this.animationRoFun()
  11384. } else {
  11385. ToastUtil.showToast('封面圆形已开启')
  11386. this.animationRoFun()
  11387. }
  11388. }
  11389. })
  11390. .width(48)
  11391. .height(24);
  11392. Toggle({ type: ToggleType.Switch, isOn: this.showSimple })
  11393. .selectedColor(this.themeColor)
  11394. .switchPointColor(Color.White)
  11395. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11396. .margin({ right: 15 })
  11397. .visibility(more.id == 22 ? Visibility.Visible : Visibility.None)
  11398. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11399. if (more.id == 22) {
  11400. this.showSimple = checked;
  11401. PreferencesUtil.put('showSimple', this.showSimple)
  11402. }
  11403. })
  11404. .width(48)
  11405. .height(24);
  11406. Toggle({ type: ToggleType.Switch, isOn: this.enablePointLight })
  11407. .selectedColor(this.themeColor)
  11408. .switchPointColor(Color.White)
  11409. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11410. .margin({ right: 15 })
  11411. .visibility(more.id == 23 ? Visibility.Visible : Visibility.None)
  11412. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11413. if (more.id == 23) {
  11414. this.enablePointLight = checked;
  11415. PreferencesUtil.put('enablePointLight', this.enablePointLight)
  11416. AppStorage.setOrCreate('EnablePointLight', this.enablePointLight);
  11417. }
  11418. })
  11419. .width(48)
  11420. .height(24);
  11421. Toggle({ type: ToggleType.Switch, isOn: this.isShowBgLiuGUANG })
  11422. .selectedColor(this.themeColor)
  11423. .switchPointColor(Color.White)
  11424. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11425. .margin({ right: 15 })
  11426. .visibility(more.id == 21 ? Visibility.Visible : Visibility.None)
  11427. .onChange((checked: boolean) => { // 是否开启背景流光效果
  11428. if (more.id == 21) {
  11429. this.isShowBgLiuGUANG = checked;
  11430. PreferencesUtil.putSync('isShowBgLiuGUANG',this.isShowBgLiuGUANG)
  11431. }
  11432. })
  11433. .width(48)
  11434. .height(24);
  11435. }
  11436. }
  11437. .width('100%')
  11438. .height(45)
  11439. .padding(15)
  11440. .backgroundColor(Color.Transparent)
  11441. .borderRadius(12)
  11442. .margin({ bottom: 6 })
  11443. }
  11444. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  11445. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  11446. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  11447. .backgroundColor(Color.Transparent)
  11448. .onClick(() => {
  11449. this.doMore(more.id)
  11450. })
  11451. });
  11452. }
  11453. .width('100%')
  11454. .padding(16)
  11455. }.margin({ bottom: 18 })
  11456. }
  11457. @Builder
  11458. TPImageBuilder(more: MoreItem): void {
  11459. Row() {
  11460. Image($r('app.media.tuoping'))
  11461. .width(22)
  11462. .height(22)
  11463. .margin({ left: 10, right: 10 })
  11464. Text(more.title)
  11465. .fontSize(16)
  11466. .fontColor(Color.White)
  11467. }
  11468. .width('100%')
  11469. .layoutWeight(1)
  11470. .alignItems(VerticalAlign.Center)
  11471. .justifyContent(FlexAlign.Start)
  11472. }
  11473. private moreItems: MoreItem[] = [
  11474. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  11475. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  11476. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  11477. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  11478. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  11479. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  11480. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  11481. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  11482. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  11483. { id:20,image: $r("app.media.a_b"), title: 'AB循环' },
  11484. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  11485. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  11486. { id: 4, image: $r('app.media.share2'), title: '分享' },
  11487. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  11488. // { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  11489. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  11490. { id : 22, image: $r('app.media.skip'), title: '沉浸式' },
  11491. { id : 23, image: $r('app.media.more_do'), title: '点光源效果' },
  11492. { id : 21, image: $r('app.media.kp_music'), title: '背景双边流光' },
  11493. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  11494. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  11495. ];
  11496. @State isShowBgLiuGUANG: boolean = false;
  11497. @State isShowMoreView: boolean = false;
  11498. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  11499. @State isShowTimeCloseMore: boolean = false
  11500. @State isShowDetailMore: boolean = false
  11501. @State isMusicBGCover: boolean = true
  11502. @State isSavePlayMode: boolean = true
  11503. @State isLyricSetting: boolean = false
  11504. @State isJumpSetting: boolean = false
  11505. @State isShowEdit: boolean = false
  11506. @State showPipLyric: boolean = false
  11507. async setRingTone() {
  11508. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  11509. return
  11510. }
  11511. // 确定后的逻辑
  11512. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  11513. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  11514. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  11515. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  11516. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  11517. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  11518. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  11519. , this.videoUrl, this.name).then(res => {
  11520. LogUtil.info('onecold setFlag :' + res);
  11521. });
  11522. }
  11523. doMore(moreId: number) {
  11524. switch (moreId) {
  11525. case 2: //歌词
  11526. this.isLyricSetting = !this.isLyricSetting;
  11527. this.isShowMoreView = false
  11528. break;
  11529. case 3: //详情
  11530. this.isShowDetailMore = !this.isShowDetailMore;
  11531. break;
  11532. case 4: //分享
  11533. if (this.currentSong !== undefined) {
  11534. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  11535. }
  11536. this.isShowMoreView = false
  11537. break;
  11538. case 5: //定时关闭
  11539. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  11540. break;
  11541. case 10: //设为铃声
  11542. this.setRingTone()
  11543. this.isShowMoreView = false
  11544. break;
  11545. case 11: //跳过头尾
  11546. this.isJumpSetting = !this.isJumpSetting;
  11547. break;
  11548. case 13: //倍速
  11549. break;
  11550. case 14: //搜索封面
  11551. if (this.currentSong !== undefined) {
  11552. this.doSearchCover(this.currentSong)
  11553. }
  11554. this.isShowMoreView = false
  11555. break;
  11556. case 15: //编辑标签
  11557. this.initEditFields(this.currentSong)
  11558. this.tempLyricContent = this.lyricContent
  11559. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  11560. this.lyricConStr = this.tempLyricContent
  11561. }
  11562. this.isShowEdit = !this.isShowEdit;
  11563. break;
  11564. case 16: //悬浮歌词
  11565. this.showPipLyric = !this.showPipLyric;
  11566. break;
  11567. case 17: //横屏模式
  11568. if (this.isLandscape) {
  11569. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  11570. } else {
  11571. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  11572. }
  11573. this.isShowMoreView = false
  11574. break;
  11575. case 20://AB循环
  11576. this.isABSheet = !this.isABSheet
  11577. break;
  11578. }
  11579. }
  11580. //AB循环
  11581. @State isOpenAB:boolean = false
  11582. @State jumpATime:number = 0
  11583. @State jumpBTime:number = 0
  11584. @State isABSheet:boolean = false
  11585. @Builder
  11586. ABLoopSheet() {
  11587. ABLoopComptent({
  11588. jumpATime:this.jumpATime,
  11589. jumpBTime:this.jumpBTime,
  11590. onClickAItem: async ()=>{
  11591. if(this.mIjkMediaPlayer){
  11592. this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
  11593. }
  11594. },
  11595. onClickBItem: async ()=>{
  11596. if(this.mIjkMediaPlayer){
  11597. this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
  11598. if(this.jumpBTime<=this.jumpATime){
  11599. ToastUtil.showToast('设置B点时间不能小于A点时间')
  11600. this.jumpBTime = 0
  11601. }
  11602. }
  11603. },
  11604. onCancleButtonClick: async ()=>{
  11605. this.isOpenAB = false
  11606. this.isABSheet = false
  11607. },
  11608. onStartButtonClick: async ()=>{
  11609. if(this.jumpBTime<=this.jumpATime||this.stringForTime(this.jumpATime)==this.stringForTime(this.jumpBTime)){
  11610. ToastUtil.showToast('设置B点时间不能小于或等于A点时间')
  11611. return
  11612. }
  11613. this.isABSheet = false
  11614. this.startABLoop()
  11615. },
  11616. })
  11617. }
  11618. //开始AB循环
  11619. startABLoop(){
  11620. if(this.mIjkMediaPlayer){
  11621. this.seekTo(this.jumpATime+'')
  11622. this.isOpenAB = true
  11623. }
  11624. }
  11625. /**
  11626. * 切换横竖屏
  11627. *
  11628. */
  11629. setOrientation(orientation: number) {
  11630. this.windowClass.setPreferredOrientation(orientation).then(() => {
  11631. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  11632. }).catch((err: BusinessError) => {
  11633. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  11634. });
  11635. }
  11636. /**
  11637. * 画中画功能(悬浮歌词功能)
  11638. *
  11639. */
  11640. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  11641. pipController?: PiPWindow.PiPController;
  11642. navigationId: string = '';
  11643. @State curState: string = '';
  11644. @State curError: ResourceStr = '';
  11645. @State pipBg: string = '#E8E8E8'
  11646. @State buttonAction: string = '';
  11647. //开启画中画功能
  11648. async startPip() {
  11649. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  11650. if (!this.pipController) {
  11651. await this.createPipController();
  11652. }
  11653. if (!this.pipController) {
  11654. Logger.info(`[${TAG}] pipController create error`);
  11655. return;
  11656. }
  11657. await this.pipController.startPiP();
  11658. }
  11659. async stopPip() {
  11660. if (!this.pipController) {
  11661. Logger.info(`[${TAG}] pipController is not exist`);
  11662. return;
  11663. }
  11664. this.isOpenPip = false
  11665. await this.pipController.stopPiP();
  11666. }
  11667. async createPipController() {
  11668. this.pipController = await PiPWindow.create({
  11669. context: getContext(this),
  11670. componentController: this.xcomponentController,
  11671. navigationId: this.navigationId,
  11672. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  11673. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  11674. customUIController: this.nodeController,
  11675. });
  11676. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  11677. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  11678. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  11679. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  11680. this.onStateChange(state, reason);
  11681. });
  11682. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  11683. this.onActionEvent(event, status);
  11684. });
  11685. }
  11686. destroyPipController() {
  11687. if (!this.pipController) {
  11688. return;
  11689. }
  11690. this.pipController.off('stateChange');
  11691. this.pipController.off('controlPanelActionEvent');
  11692. this.pipController = undefined;
  11693. }
  11694. onStateChange(state: PiPWindow.PiPState, reason: string) {
  11695. switch (state) {
  11696. case PiPWindow.PiPState.ABOUT_TO_START:
  11697. this.curState = 'ABOUT_TO_START';
  11698. this.curError = $r('app.string.current_error_hint');
  11699. break;
  11700. case PiPWindow.PiPState.STARTED:
  11701. this.curState = 'STARTED';
  11702. this.curError = $r('app.string.current_error_hint');
  11703. break;
  11704. case PiPWindow.PiPState.ABOUT_TO_STOP:
  11705. this.curState = 'ABOUT_TO_STOP';
  11706. this.curError = $r('app.string.current_error_hint');
  11707. break;
  11708. case PiPWindow.PiPState.STOPPED:
  11709. this.curState = 'STOPPED';
  11710. this.curError = $r('app.string.current_error_hint');
  11711. this.stopPip()
  11712. this.destroyPipController()
  11713. break;
  11714. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  11715. this.curState = 'ABOUT_TO_RESTORE';
  11716. this.curError = $r('app.string.current_error_hint');
  11717. break;
  11718. case PiPWindow.PiPState.ERROR:
  11719. this.curState = 'ERROR';
  11720. this.curError = reason;
  11721. break;
  11722. default:
  11723. break;
  11724. }
  11725. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  11726. }
  11727. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  11728. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  11729. switch (event) {
  11730. case 'playbackStateChanged':
  11731. if (status === 0) {
  11732. this.pause();
  11733. } else {
  11734. console.info('onecold startPlayOrResumePlay 9869')
  11735. this.startPlayOrResumePlay();
  11736. }
  11737. break;
  11738. case 'nextVideo':
  11739. // 切换到下一个视频
  11740. this.playNext().catch(() => {
  11741. Logger.error('heanup onActionEvent playNext', `播放下一首失败`);
  11742. });
  11743. break;
  11744. case 'previousVideo':
  11745. // 切换到上一个视频
  11746. this.playPrevious().catch(() => {
  11747. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败`);
  11748. });
  11749. break;
  11750. case 'previousVideo':
  11751. // 切换到上一个视频
  11752. this.playPrevious().catch(() => {
  11753. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败:`);
  11754. });
  11755. break;
  11756. default:
  11757. }
  11758. this.buttonAction = event + `-status:${status}`;
  11759. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  11760. }
  11761. /**
  11762. * 画中画功能(悬浮歌词功能)结束
  11763. *
  11764. */
  11765. async doSearchCover(item: VideoItem,title?:string,artist?:string): Promise<string> {
  11766. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  11767. this.isShowMoreView = false;
  11768. this.showTipsDialog();
  11769. return ''; // Return empty string when no API is configured
  11770. }
  11771. if (!item) {
  11772. return ''; // Return empty string if item is undefined
  11773. }
  11774. const titleS = title||item?.name || '';
  11775. const artistS = artist||item?.artist || ''; // Use empty string if artist is missing
  11776. return this.searchCover(item, titleS, artistS); // Await is not needed here as we return the promise directly
  11777. }
  11778. /**
  11779. *api搜索封面
  11780. *item,根据title和artist
  11781. */
  11782. searchCover(item: VideoItem, title: string, artist: string): Promise<string> {
  11783. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  11784. LogUtil.debug("onecold res =" + res);
  11785. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  11786. if (item.filePath == this.currentSong?.filePath) {
  11787. this.cover = res;
  11788. if (this.currentSong) {
  11789. this.currentSong.pixelMapPath = res;
  11790. }
  11791. }
  11792. // Update pixel map path but always return res regardless of success
  11793. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  11794. if (success) {
  11795. this.doUpdateData();
  11796. console.log("onecold 更新音乐封面成功,数据库已同步");
  11797. } else {
  11798. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  11799. }
  11800. // Note: We don't resolve/reject here because we already returned res
  11801. });
  11802. LogUtil.debug("onecold this.cover =" + this.cover);
  11803. }
  11804. return res; // Always return res regardless of updatePixelMapPath result
  11805. });
  11806. }
  11807. @State jumpTopTime: number = 0
  11808. @State jumpEndTime: number = 0
  11809. @State isOpenJump: boolean = false
  11810. @Builder
  11811. JumpTopEndSheet() {
  11812. Scroll() {
  11813. Column() {
  11814. Column() {
  11815. Text('仅对本播放列表有效')
  11816. .fontSize(16)
  11817. .fontColor($r('app.color.text_color'))
  11818. // 跳过头尾
  11819. Column() {
  11820. Row() {
  11821. Text('跳过片头:')
  11822. .fontSize(16)
  11823. .fontColor($r('app.color.text_color'))
  11824. Text(this.jumpTopTime + 's')
  11825. .fontSize(16)
  11826. .fontColor($r('app.color.text_color'))
  11827. }
  11828. .margin({ bottom: 5 })
  11829. Row() {
  11830. Slider({
  11831. value: this.jumpTopTime,
  11832. min: 0,
  11833. max: 120,
  11834. step: 1,
  11835. style: SliderStyle.OutSet
  11836. })
  11837. .blockColor(this.themeColor)
  11838. .trackColor($r('app.color.speed_text_color'))
  11839. .selectedColor(Color.White)
  11840. .trackThickness(8)
  11841. .onChange((value: number) => {
  11842. this.jumpTopTime = value;
  11843. })
  11844. .width('85%')
  11845. }
  11846. .alignItems(VerticalAlign.Top)
  11847. }
  11848. .margin({ top: 10, bottom: 10 })
  11849. // 跳过头尾
  11850. Column() {
  11851. Row() {
  11852. Text('跳过片尾:')
  11853. .fontSize(16)
  11854. .fontColor($r('app.color.text_color'))
  11855. Text(this.jumpEndTime + 's')
  11856. .fontSize(16)
  11857. .fontColor($r('app.color.text_color'))
  11858. }
  11859. .margin({ bottom: 5 })
  11860. Row() {
  11861. Slider({
  11862. value: this.jumpEndTime,
  11863. min: 0,
  11864. max: 120,
  11865. step: 1,
  11866. style: SliderStyle.OutSet
  11867. })
  11868. .blockColor(this.themeColor)
  11869. .trackColor($r('app.color.speed_text_color'))
  11870. .selectedColor(Color.White)
  11871. .trackThickness(8)
  11872. .onChange((value: number) => {
  11873. this.jumpEndTime = value;
  11874. })
  11875. .width('85%')
  11876. }
  11877. .alignItems(VerticalAlign.Top)
  11878. }
  11879. .margin({ top: 10, bottom: 10 })
  11880. Row() {
  11881. Button('保存设置')
  11882. .fontColor(Color.White)
  11883. .layoutWeight(1)
  11884. .height(40)
  11885. .width(80)
  11886. .backgroundColor(this.themeColor)
  11887. .stateEffect(true)
  11888. .margin({ left: 0, bottom: 20 })
  11889. .onClick(async () => {
  11890. if (!Utility.isNoble()) {
  11891. this.isJumpSetting = false
  11892. this.isShowMoreView = false
  11893. this.showVipDialog()
  11894. return
  11895. }
  11896. if (this.currentSong === undefined) {
  11897. return
  11898. }
  11899. if (this.modeType === 0) {
  11900. let parentPath = FileUtil.getParentPath(this.videoUrl)
  11901. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  11902. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  11903. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  11904. } else if (this.modeType === 1) { //媒体库
  11905. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  11906. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  11907. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  11908. } else if (this.modeType === 2) { //艺术家
  11909. if (this.currentSong?.artist) {
  11910. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  11911. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  11912. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  11913. }
  11914. } else if (this.modeType === 3) { //专辑
  11915. if (this.currentSong?.album) {
  11916. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  11917. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  11918. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  11919. }
  11920. }
  11921. ToastUtil.showShort("保存成功")
  11922. this.isJumpSetting = false
  11923. })
  11924. }
  11925. .margin({
  11926. left: 38,
  11927. right: 38,
  11928. top: 10,
  11929. bottom: 10
  11930. })
  11931. .width(120)
  11932. .height(50)
  11933. }
  11934. }
  11935. }
  11936. .width('100%')
  11937. .height('100%')
  11938. }
  11939. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  11940. private onStateVastChange(state: AVCastPickerState) {
  11941. if (state == AVCastPickerState.STATE_APPEARING) {
  11942. console.log('The picker starts showing.');
  11943. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  11944. console.log('The picker finishes presenting.');
  11945. }
  11946. }
  11947. private showSelectLyric() {
  11948. DialogHelper.showActionSheetDialog({
  11949. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  11950. // sheets: ["本地歌词", "搜索歌词"],
  11951. sheets: [
  11952. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  11953. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  11954. ],
  11955. maskColor: Color.Transparent,
  11956. backgroundColor: $r('app.color.bg_card'),
  11957. transition: AnimationHelper.transitionInDown(666),
  11958. onAction: (index) => {
  11959. switch (index) {
  11960. case 0:
  11961. this.callFilePickerSelectFileForLyric()
  11962. break;
  11963. case 1:
  11964. if (StrUtil.isNotEmpty(this.videoUrl)) {
  11965. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  11966. this.initLyric(lyricPath);
  11967. }
  11968. break;
  11969. }
  11970. }
  11971. })
  11972. }
  11973. // 拉起picker选择文件管理器
  11974. async callFilePickerSelectFileForLyric(): Promise<void> {
  11975. try {
  11976. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  11977. DocumentSelectOptions.maxSelectNumber = 1
  11978. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  11979. let documentPicker = new picker.DocumentViewPicker();
  11980. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  11981. Logger.info(TAG,
  11982. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  11983. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  11984. this.saveVideoDatasLyric(DocumentSelectResult)
  11985. }
  11986. }).catch((err: BusinessError) => {
  11987. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  11988. });
  11989. } catch (err) {
  11990. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  11991. }
  11992. }
  11993. async saveVideoDatasLyric(uris: string[]) {
  11994. if (ArrayUtil.isEmpty(uris)) {
  11995. return
  11996. }
  11997. let newUris: string[] = [];
  11998. for (let i = 0; i < uris.length; i++) {
  11999. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  12000. Logger.info(TAG, 'filePath uri: ' + filePath);
  12001. newUris.push(filePath)
  12002. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  12003. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  12004. fileIo.copyFileSync(file.fd, file2.fd)
  12005. fileIo.closeSync(file);
  12006. fileIo.closeSync(file2);
  12007. this.initLyric(filePath,false,false,true)
  12008. }
  12009. }
  12010. private initDelayPlay(context: object) {
  12011. this.mContext = context;
  12012. }
  12013. startPipLyric() {
  12014. if (this.pipController) {
  12015. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  12016. PiPWindow.PiPControlStatus.PLAY);
  12017. }
  12018. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  12019. if (this.isOpenPip) {
  12020. this.startPip()
  12021. } else {
  12022. this.stopPip()
  12023. }
  12024. }
  12025. //startOffset 从cue分轨时间开始播
  12026. private startPlayOrResumePlay(startOffset?:number) {
  12027. //针对dsf文件高采样率,统一转wav播放
  12028. const sampleRate = this.currentSong?.sampleRate||0
  12029. if(this.videoUrl.toLowerCase().endsWith('.dsf')&&sampleRate>=441000){
  12030. console.info('onecold 采样率 ='+sampleRate)
  12031. let newDsfPath = this.context.filesDir + '/'+FileUtil.getFileName(this.videoUrl)+'.wav'
  12032. console.info('onecold newDsfPath ='+newDsfPath)
  12033. if(!FileUtil.accessSync(newDsfPath)){
  12034. const task = new taskpool.Task(convertDsfToWav,this.videoUrl,newDsfPath);
  12035. taskpool.execute(task, taskpool.Priority.HIGH).then((data)=>{
  12036. this.videoUrl = newDsfPath
  12037. this.startPlay(startOffset)
  12038. }).catch((e:object)=>{
  12039. console.info("task1 catch e: " + e);
  12040. })
  12041. }else{
  12042. this.videoUrl = newDsfPath
  12043. this.startPlay(startOffset)
  12044. }
  12045. }else{
  12046. this.startPlay(startOffset)
  12047. }
  12048. // 仅当前播放的是网盘歌曲时,才提前缓存下一首
  12049. // 排除用户拖动进度条的情况
  12050. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !this.isSeekTo) {
  12051. void this.preloadNextSongInternal();
  12052. }
  12053. }
  12054. startPlay(startOffset?:number) {
  12055. this.startPipLyric()
  12056. this.mDestroyPage = false;
  12057. this.animationState = AnimationStatus.Running
  12058. LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  12059. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  12060. this.stopProgressTask();
  12061. this.startProgressTask();
  12062. // 判断是否是HTTP或在线网盘视频,显示加载进度
  12063. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  12064. this.isPlayerLoading = true;
  12065. }
  12066. this.play(this.videoUrl.toString(),startOffset);
  12067. }
  12068. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  12069. this.mIjkMediaPlayer.start();
  12070. this.setProgress()
  12071. this.CONTROL_PlayStatus = PlayStatus.PLAY
  12072. }
  12073. this.setIsPlaying(true)
  12074. this.updateSessionPlayState(true)
  12075. this.watchStatus();
  12076. this.updateLastPlayTimeStr(this.videoUrl)
  12077. }
  12078. updateLastPlayTimeStr(filePath: string) {
  12079. // 检查是否为网络音频(WebDAV),如果是则不更新本地数据库
  12080. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  12081. Logger.info(`heanup 检测到网络音频播放,跳过数据库更新: ${filePath}`)
  12082. return;
  12083. }
  12084. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  12085. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  12086. if (success) {
  12087. this.getHistoryList(false)
  12088. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  12089. } else {
  12090. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  12091. }
  12092. });
  12093. }
  12094. private completionNum(num: number): string | number {
  12095. if (num < 10) {
  12096. return '0' + num;
  12097. } else {
  12098. return num;
  12099. }
  12100. }
  12101. private stringForTime(timeMs: number): string {
  12102. let totalSeconds: number | string = (timeMs / 1000);
  12103. let newSeconds: number | string = totalSeconds % 60;
  12104. let minutes: number | string = (totalSeconds / 60) % 60;
  12105. let hours: number | string = totalSeconds / 3600;
  12106. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  12107. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  12108. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  12109. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  12110. if (this.isCurrentTime) {
  12111. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  12112. this.oldSeconds = newSeconds
  12113. } else {
  12114. newSeconds = this.oldSeconds
  12115. }
  12116. }
  12117. newSeconds = this.completionNum(newSeconds);
  12118. if (hours > 0) {
  12119. return hours + ":" + minutes + ":" + newSeconds;
  12120. } else {
  12121. return minutes + ":" + newSeconds;
  12122. }
  12123. }
  12124. private setProgress() {
  12125. if (this.castControllerWrapper && this.isCastPlaying) {
  12126. return;
  12127. }
  12128. let position = this.mIjkMediaPlayer.getCurrentPosition();
  12129. let duration = this.mIjkMediaPlayer.getDuration();
  12130. if (duration <= 0 && this.duration > 0) {
  12131. duration = this.duration;
  12132. }
  12133. let pos = 0;
  12134. if (duration > 0) {
  12135. this.slideEnable = true;
  12136. let curPercent = position / duration;
  12137. pos = curPercent * 100;
  12138. if (pos > this.PROGRESS_MAX_VALUE) {
  12139. this.progressValue = this.PROGRESS_MAX_VALUE
  12140. } else {
  12141. this.progressValue = pos;
  12142. }
  12143. }
  12144. // LogUtils.getInstance()
  12145. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  12146. this.totalTime = this.stringForTime(duration);
  12147. if (position > duration) {
  12148. position = duration;
  12149. }
  12150. this.isCurrentTime = true;
  12151. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  12152. if(this.showPipLyric){
  12153. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000);
  12154. }
  12155. if(this.isShowSingleLineLyric){
  12156. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000);
  12157. }
  12158. this.currentTime = this.stringForTime(position);
  12159. this.isCurrentTime = false
  12160. if (this.mIjkMediaPlayer.isPlaying()) {
  12161. //如果是开启AB循环
  12162. if(this.isOpenAB){
  12163. if(position >=this.jumpBTime){
  12164. this.seekTo(this.jumpATime+'')
  12165. return
  12166. }
  12167. }
  12168. // 判断是否播放到结束时间
  12169. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  12170. if (position >= duration - this.jumpEndTime * 1000) {
  12171. if(this.playType == 1){//跳过尾部如果是单曲循环就选择单曲循环
  12172. this.CONTROL_PlayStatus = PlayStatus.INIT
  12173. this.startPlayOrResumePlay();
  12174. }else if (this.playType == 2) { //2:正常播放,单曲播完
  12175. this.showRePlay();
  12176. this.currentTime = this.stringForTime(this.mIjkMediaPlayer.getDuration());
  12177. this.progressValue = this.PROGRESS_MAX_VALUE;
  12178. this.slideEnable = false;
  12179. this.stop();
  12180. // ToastUtil.showToast('开始重新播放')
  12181. }else{
  12182. this.playNext().catch(() => {
  12183. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  12184. });
  12185. }
  12186. }
  12187. }
  12188. }
  12189. }
  12190. private startProgressTask() {
  12191. let that = this;
  12192. this.updateProgressTimer = setInterval(() => {
  12193. //LogUtils.getInstance().LOGI("startProgressTask");
  12194. if (!that.mDestroyPage) {
  12195. that.setProgress();
  12196. }
  12197. }, 300);
  12198. }
  12199. private stopProgressTask() {
  12200. LogUtils.getInstance().LOGI("stopProgressTask");
  12201. clearInterval(this.updateProgressTimer);
  12202. }
  12203. private showLoadIng() {
  12204. this.loadingVisible = Visibility.Visible;
  12205. this.replayVisible = Visibility.None;
  12206. }
  12207. private hideLoadIng() {
  12208. this.loadingVisible = Visibility.None;
  12209. this.replayVisible = Visibility.None;
  12210. }
  12211. private showRePlay() {
  12212. this.loadingVisible = Visibility.None;
  12213. this.replayVisible = Visibility.Visible;
  12214. }
  12215. private async play(url: string,startOffset?:number) {
  12216. this.isShowBgLiuGUANG = PreferencesUtil.getBooleanSync('isShowBgLiuGUANG', false)
  12217. console.info('onecold this.url 1= '+url)
  12218. if(!url.toLowerCase().startsWith('http')){
  12219. let hasPermission = await PermissionUtil.activatePermission(url)
  12220. console.info('onecold this.hasPermission 1= '+hasPermission)
  12221. if(!url.includes(this.packName)){
  12222. const file = fs.openSync(url)
  12223. this.videoUrl = file.path
  12224. url= this.videoUrl
  12225. }
  12226. console.info('onecold this.hasPermission 1= '+hasPermission)
  12227. console.info('onecold this.videoUrl 1= '+this.videoUrl)
  12228. }
  12229. let that = this;
  12230. that.showLoadIng();
  12231. this.isOpenAB = false
  12232. //设置XComponent回调的context
  12233. if (!!this.mContext) {
  12234. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  12235. }
  12236. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  12237. this.mIjkMediaPlayer.reset();
  12238. }
  12239. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  12240. //设置debug模式
  12241. this.mIjkMediaPlayer.setDebug(false);
  12242. //初始化配置
  12243. this.mIjkMediaPlayer.native_setup();
  12244. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  12245. if(this.volumeSmall){
  12246. if(this.videoUrl.toLowerCase().endsWith('.dsf')){
  12247. this.mIjkMediaPlayer.setVolume('1', '1');
  12248. }else{
  12249. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  12250. }
  12251. }else{
  12252. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  12253. }
  12254. // 构建规范的HTTP请求头(统一一次性设置,避免未带认证提前发起连接)
  12255. const headers = new Map<string, string>();
  12256. headers.set("User-Agent", "TTMusic-WebDAV/1.0");
  12257. headers.set("Accept", "*/*");
  12258. if (this.currentSong&&StrUtil.isEmpty(this.currentSong.pixelMapPath)
  12259. &&PreferencesUtil.getStringSync('COVER_API', '') != '') {
  12260. //如果封面为空,则搜索封面
  12261. this.searchCover(this.currentSong, this.currentSong.name, this.currentSong.artist||'')
  12262. }
  12263. // 如果是WebDAV网络音频,使用webdav_account_id获取认证信息(等待完成后再设置一次性头部)
  12264. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !isBaiduType(this.currentSong.type)) {
  12265. Logger.info(`heanup WebDAV歌曲认证 - 歌曲名: ${this.currentSong.name}, webdav_account_id: ${this.currentSong.webdav_account_id || '未设置'}`);
  12266. if (this.currentSong.webdav_account_id) {
  12267. try {
  12268. const webdavManager = RemoteDriveManager.getInstance();
  12269. const webDavHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  12270. if (webDavHeaders && webDavHeaders.size > 0) {
  12271. webDavHeaders.forEach((value, key) => headers.set(key, value));
  12272. Logger.info(`heanup 成功通过webdav_account_id获取并合并WebDAV认证头`);
  12273. } else {
  12274. Logger.warn(`heanup 通过webdav_account_id获取认证头失败,播放可能无法继续`);
  12275. }
  12276. } catch (error) {
  12277. const err = error as Error;
  12278. Logger.error(`heanup 获取WebDAV认证头时出错: ${err.message}`);
  12279. }
  12280. } else {
  12281. Logger.error(`heanup WebDAV歌曲 "${this.currentSong.name}" 缺少webdav_account_id,无法进行认证`);
  12282. }
  12283. }
  12284. // 统一设置带认证的请求头
  12285. // 百度类型也需要特殊请求头
  12286. if (this.currentSong && isBaiduType(this.currentSong.type)) {
  12287. try {
  12288. const webdavManager = RemoteDriveManager.getInstance();
  12289. const baiduHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  12290. baiduHeaders.forEach((value, key) => headers.set(key, value));
  12291. const headerSnapshot: Record<string, string> = {};
  12292. headers.forEach((value, key) => headerSnapshot[key] = value);
  12293. Logger.info(TAG, `Baidu播放请求头: ${JSON.stringify(headerSnapshot)}`);
  12294. } catch (error) {
  12295. Logger.error(`heanup 构建百度请求头失败: ${(error as Error).message}`);
  12296. }
  12297. }
  12298. //设置视频源(先准备好认证头,再设置数据源)
  12299. Logger.info(TAG, `IjkPlayer setDataSource url=${url}`);
  12300. this.mIjkMediaPlayer.setDataSource(url);
  12301. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  12302. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !isBaiduType(this.currentSong.type)) {
  12303. console.log(`heanup 为WebDAV播放设置IjkPlayer选项`);
  12304. // 网络超时设置(单位:微秒,文档显示应该是字符串格式)
  12305. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "30000000"); // 30秒
  12306. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "30000000"); // 连接超时30秒
  12307. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "listen_timeout", "30000000"); // 监听超时30秒
  12308. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "30000000"); // DNS缓存超时30秒
  12309. // 缓冲和播放优化设置
  12310. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "1024000"); // 增大缓冲区
  12311. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "50"); // 减少最小帧数
  12312. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1"); // 预加载启动
  12313. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0"); // 无缓冲播放
  12314. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "30000"); // 最大缓存30秒
  12315. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1"); // 无限制收流
  12316. // 网络相关设置
  12317. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1"); // 启用HTTP重定向
  12318. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", "TTMusic-WebDAV/1.0"); // 用户代理
  12319. // 重连设置
  12320. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "reconnect", "3"); // 重连3次
  12321. console.log(`heanup WebDAV IjkPlayer选项设置完成`);
  12322. } else if (this.currentSong && isBaiduType(this.currentSong.type)) {
  12323. console.log(`heanup 为百度网盘播放设置IjkPlayer选项`);
  12324. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "15000000");
  12325. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "15000000");
  12326. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1");
  12327. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "1");
  12328. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "2097152");
  12329. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "25");
  12330. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", BaiduConstants.USER_AGENT);
  12331. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", "3");
  12332. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http-detect-range-support", "1");
  12333. console.log(`heanup 百度网盘 IjkPlayer 选项设置完成`);
  12334. }
  12335. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  12336. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  12337. // }
  12338. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  12339. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  12340. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  12341. let bufferSize = 50 * 1024 ; // 默认缓冲区大小为1MB
  12342. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  12343. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  12344. //停止预读的最小帧数
  12345. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  12346. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  12347. // 设置其他缓冲相关选项
  12348. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  12349. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  12350. //启动预加载
  12351. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
  12352. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  12353. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  12354. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  12355. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  12356. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  12357. // 因此需要播放器丢包,才不会累积延时
  12358. // 这个和第三个参数packet-buffering无关。
  12359. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  12360. // 无限制收流
  12361. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  12362. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  12363. // 屏幕常亮
  12364. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  12365. // 开启hls起播优化 默认是关闭的
  12366. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "fetch_first", "on");
  12367. // 设置超时
  12368. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  12369. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  12370. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  12371. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  12372. // 变速播放
  12373. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  12374. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  12375. let Speed = this.mIjkMediaPlayer.getSpeed()
  12376. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  12377. //是否开启循环播放
  12378. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  12379. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = {
  12380. onVideoSizeChanged: (width: number, height: number, sar_num: number, sar_den: number) => {
  12381. if (height === 0) {
  12382. return;
  12383. }
  12384. const va = width / height;
  12385. const vpa = that.videoParentAspectRatio;
  12386. if (vpa > va) {
  12387. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  12388. } else {
  12389. that.videoWidth = '100%';
  12390. }
  12391. if (width && height) {
  12392. that.videoAspectRatio = width / height;
  12393. }
  12394. LogUtils.getInstance()
  12395. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  12396. that.hideLoadIng();
  12397. }
  12398. }
  12399. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  12400. let mOnPreparedListener: OnPreparedListener = {
  12401. onPrepared: async () => {
  12402. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  12403. // 隐藏加载进度
  12404. this.isPlayerLoading = false;
  12405. try {
  12406. //保存碰一碰分享的当前的歌曲
  12407. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  12408. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  12409. await this.initLyric(lyricPath);
  12410. const applyDuration = (durationMs: number): void => {
  12411. if (durationMs <= 0) {
  12412. return;
  12413. }
  12414. this.duration = durationMs;
  12415. this.durationTime = Math.floor(durationMs / 1000);
  12416. this.durationStringTime = secondToTime(this.durationTime);
  12417. this.totalTime = this.stringForTime(durationMs);
  12418. if (this.currentSong) {
  12419. this.currentSong.duration = this.totalTime;
  12420. try {
  12421. this.avSessionController.setAVMetadataMusic(this.currentSong, durationMs, this.lyricContent);
  12422. } catch (metaError) {
  12423. Logger.warn(TAG, `heanup 首次播放写入AVSession失败: ${(metaError as Error).message}`);
  12424. }
  12425. }
  12426. };
  12427. const fetchBaiduM3u8Duration = async (url: string): Promise<number> => {
  12428. if (!url || !isBaiduType(this.currentSong?.type ?? -1)) {
  12429. return 0;
  12430. }
  12431. const httpRequest = http.createHttp();
  12432. try {
  12433. const response = await httpRequest.request(url, {
  12434. method: http.RequestMethod.GET,
  12435. connectTimeout: 8000,
  12436. readTimeout: 8000,
  12437. expectDataType: http.HttpDataType.STRING,
  12438. header: {
  12439. 'User-Agent': BaiduConstants.STREAMING_USER_AGENT,
  12440. 'Host': 'pan.baidu.com',
  12441. 'Referer': 'https://pan.baidu.com/disk/home',
  12442. 'Accept-Encoding': 'identity'
  12443. }
  12444. });
  12445. if (response.responseCode !== 200 || typeof response.result !== 'string') {
  12446. return 0;
  12447. }
  12448. const text = response.result;
  12449. if (text.indexOf('#EXTM3U') < 0) {
  12450. return 0;
  12451. }
  12452. const lines = text.split('\n');
  12453. let totalSeconds = 0;
  12454. for (let i = 0; i < lines.length; i++) {
  12455. const line = lines[i].trim();
  12456. if (line.startsWith('#EXTINF:')) {
  12457. const colonIndex = line.indexOf(':');
  12458. if (colonIndex < 0) {
  12459. continue;
  12460. }
  12461. const content = line.substring(colonIndex + 1);
  12462. const commaIndex = content.indexOf(',');
  12463. const numberPart = commaIndex >= 0 ? content.substring(0, commaIndex) : content;
  12464. const seconds = Number(numberPart);
  12465. if (!Number.isNaN(seconds) && seconds > 0) {
  12466. totalSeconds += seconds;
  12467. }
  12468. }
  12469. }
  12470. if (totalSeconds > 0) {
  12471. return Math.floor(totalSeconds * 1000);
  12472. }
  12473. return 0;
  12474. } catch (fetchError) {
  12475. Logger.warn(TAG, `heanup 解析百度M3U8时长失败: ${(fetchError as Error).message}`);
  12476. return 0;
  12477. } finally {
  12478. httpRequest.destroy();
  12479. }
  12480. };
  12481. const fetchDurationFallback = async (): Promise<void> => {
  12482. const durationMs = await fetchBaiduM3u8Duration(this.videoUrl);
  12483. if (durationMs > 0) {
  12484. Logger.info(TAG, `heanup 通过M3U8推导出时长: ${durationMs}ms`);
  12485. applyDuration(durationMs);
  12486. return;
  12487. }
  12488. Logger.warn(TAG, 'heanup 首次播放未拿到时长,保持未知');
  12489. };
  12490. const preparedDuration = this.mIjkMediaPlayer.getDuration();
  12491. console.info("onecold preparedDuration--" + preparedDuration)
  12492. if (preparedDuration > 0) {
  12493. applyDuration(preparedDuration);
  12494. if (this.videoUrl.includes('method=streaming') && isBaiduType(this.currentSong?.type ?? -1)) {
  12495. const durationMs = await fetchBaiduM3u8Duration(this.videoUrl);
  12496. if (durationMs > 0 && Math.abs(durationMs - preparedDuration) > 1000) {
  12497. Logger.info(TAG, `heanup 使用M3U8时长覆盖播放器时长: ${preparedDuration}ms -> ${durationMs}ms`);
  12498. applyDuration(durationMs);
  12499. }
  12500. }
  12501. } else {
  12502. fetchDurationFallback();
  12503. }
  12504. setTimeout(() => {
  12505. this.avSessionController.initAvSession(false);
  12506. if (this.duration > 0) {
  12507. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  12508. }
  12509. this.setAvSessionListener();
  12510. this.updateSessionPlayState(true)
  12511. this.setCurrentPlayMode()
  12512. if(startOffset&&startOffset>0){//cue分轨播放
  12513. this.seekTo(startOffset + "");
  12514. this.saveLastPlayList()
  12515. return
  12516. }
  12517. }, 500)
  12518. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12519. let timeoutPlay = 0
  12520. if (StrUtil.isNotEmpty(this.videoUrl) &&
  12521. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  12522. timeoutPlay = 1000
  12523. }
  12524. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  12525. if (this.modeType === 0) { //文件夹
  12526. let parentPath = FileUtil.getParentPath(this.videoUrl)
  12527. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  12528. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  12529. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  12530. } else if (this.modeType === 1) { //媒体库
  12531. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  12532. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  12533. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  12534. } else if (this.modeType === 2) { //艺术家
  12535. if (this.currentSong?.artist) {
  12536. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  12537. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  12538. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  12539. }
  12540. } else if (this.modeType === 3) { //专辑
  12541. if (this.currentSong?.album) {
  12542. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  12543. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  12544. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  12545. }
  12546. }
  12547. this.duration = this.mIjkMediaPlayer.getDuration()
  12548. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  12549. if (this.mIjkMediaPlayer != null) {
  12550. let jumpTopTimeMs = this.jumpTopTime*1000;
  12551. if (jumpTopTimeMs <= this.duration) {
  12552. // 调用 seekTo 方法,跳到指定时间
  12553. if(PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY,true)){
  12554. console.log('onecold jumpTopTime = '+jumpTopTimeMs);
  12555. const position:number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  12556. console.log('onecold position = '+position);
  12557. if (position > jumpTopTimeMs) {
  12558. jumpTopTimeMs = position
  12559. }
  12560. }
  12561. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12562. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  12563. this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
  12564. }
  12565. }, timeoutPlay)
  12566. } else {
  12567. // 提示用户无法跳过
  12568. ToastUtil.showToast('跳过时间超过视频时长');
  12569. }
  12570. }
  12571. } else {
  12572. this.jumpTopTime = 0
  12573. this.jumpEndTime = 0
  12574. // console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  12575. // console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  12576. // console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  12577. // PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  12578. //记忆播放(每一首都会记忆播放)
  12579. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  12580. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12581. if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  12582. this.restorePlaybackPosition() //读取播放记忆功能
  12583. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  12584. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  12585. this.restorePlaybackPosition() //读取播放记忆功能
  12586. }
  12587. this.isFirstStartPlay = false
  12588. }, timeoutPlay)
  12589. } else {
  12590. this.isFirstStartPlay = false
  12591. }
  12592. }
  12593. this.saveLastPlayList()
  12594. } catch (error) {
  12595. let err: BusinessError = error as BusinessError;
  12596. console.error('onecold failed with err: ' + JSON.stringify(err));
  12597. }
  12598. }
  12599. }
  12600. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  12601. let mOnTimedTextListener: OnTimedTextListener = {
  12602. onTimedText: () => {
  12603. }
  12604. }
  12605. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  12606. let mOnCompletionListener: OnCompletionListener = {
  12607. onCompletion: () => {
  12608. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  12609. if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
  12610. // 异步调用playNext
  12611. this.playNext().catch(() => {
  12612. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  12613. });
  12614. } else if (this.playType == 1) { //1:单片重复播放
  12615. this.CONTROL_PlayStatus = PlayStatus.INIT
  12616. that.startPlayOrResumePlay();
  12617. } else if (this.playType == 2) { //2:正常播放,单曲播完
  12618. that.showRePlay();
  12619. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  12620. that.progressValue = this.PROGRESS_MAX_VALUE;
  12621. that.slideEnable = false;
  12622. that.stop();
  12623. // ToastUtil.showToast('开始重新播放')
  12624. } else if (this.playType == 3) { //3:随机播放
  12625. // 异步调用randomPlay
  12626. this.randomPlay().catch(() => {
  12627. Logger.error('heanup OnCompletionListener randomPlay', `随机播放失败`);
  12628. });
  12629. }
  12630. }
  12631. }
  12632. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  12633. let mOnBufferingUpdateListener: OnBufferingUpdateListener = {
  12634. onBufferingUpdate: (percent: number) => {
  12635. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  12636. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  12637. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  12638. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  12639. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  12640. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  12641. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  12642. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  12643. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  12644. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  12645. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  12646. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  12647. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  12648. let Looping = this.mIjkMediaPlayer.isLooping()
  12649. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  12650. }
  12651. }
  12652. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  12653. let mOnSeekCompleteListener: OnSeekCompleteListener = {
  12654. onSeekComplete: () => {
  12655. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  12656. console.info('onecold startPlayOrResumePlay 10643')
  12657. // seek 完成,延迟恢复播放,确保 ijkplayer 内部状态完全稳定
  12658. setTimeout(() => {
  12659. // seek 完成,隐藏转圈圈并重置标志
  12660. that.hideLoadIng();
  12661. that.isSeekTo = false;
  12662. that.startPlayOrResumePlay();
  12663. }, 200); // 延迟200ms,确保ijkplayer内部状态稳定
  12664. }
  12665. }
  12666. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  12667. let mOnInfoListener: OnInfoListener = {
  12668. onInfo: (what: number, extra: number) => {
  12669. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  12670. that.hideLoadIng();
  12671. }
  12672. }
  12673. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  12674. let mOnErrorListener: OnErrorListener = {
  12675. onError: (what: number, extra: number) => {
  12676. // 隐藏加载进度
  12677. this.isPlayerLoading = false;
  12678. this.stopProgressTask();
  12679. console.info("heanup OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  12680. console.info('heanup 播放错误,歌曲详情:' + JSON.stringify(this.currentSong))
  12681. // 检查是否为WebDAV播放错误
  12682. let isWebDavError = false;
  12683. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.currentSong.filePath) {
  12684. try {
  12685. const globalContext = GlobalContext.getContext();
  12686. const webDavAuthInfo = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
  12687. if (webDavAuthInfo) {
  12688. isWebDavError = true;
  12689. }
  12690. } catch (error) {
  12691. console.error('OnErrorListener-->go: 获取WebDAV认证信息失败');
  12692. }
  12693. }
  12694. if (isWebDavError) {
  12695. console.info(`heanup WebDAV播放错误 - what: ${what}, extra: ${extra}, URL: ${this.videoUrl}`);
  12696. // 播放失败时清空实例变量中的WebDAV认证信息,防止错误账户持续使用
  12697. // this.currentWebDavAuthInfo = null;
  12698. console.info('heanup WebDAV播放失败,保留认证信息用于后续歌曲切换');
  12699. // 根据错误代码提供更具体的错误信息
  12700. let errorMessage = "WebDAV播放失败";
  12701. if (what === -1) { // 网络错误
  12702. errorMessage = "网络连接失败,请检查WebDAV服务器连接";
  12703. } else if (what === -1004) { // HTTP 404
  12704. errorMessage = "文件未找到,请检查WebDAV服务器上的文件";
  12705. } else if (what === -1001) { // 超时
  12706. errorMessage = "连接超时,请检查网络或WebDAV服务器状态";
  12707. } else if (what === -1003) { // 无法解析主机
  12708. errorMessage = "无法连接到WebDAV服务器";
  12709. }
  12710. ToastUtil.showToast(errorMessage);
  12711. } else {
  12712. if (StrUtil.isNotEmpty(this.videoUrl) &&
  12713. !this.videoUrl.startsWith('http') &&
  12714. this.currentSong &&this.currentSong.type==CommonConstants.TYPE_LOCAL&&
  12715. !FileUtil.accessSync(this.videoUrl)) {
  12716. console.info('heanup 播放.文件不存在');
  12717. ToastUtil.showToast(Utility.resourceToString(this.context, $r('app.string.file_not_exist')))
  12718. }
  12719. }
  12720. that.hideLoadIng();
  12721. }
  12722. }
  12723. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  12724. this.mIjkMediaPlayer.setMessageListener();
  12725. this.mIjkMediaPlayer.prepareAsync();
  12726. this.mIjkMediaPlayer.start();
  12727. }
  12728. //保存最后播放的那首歌和已经对应的播放列表
  12729. saveLastPlayList() {
  12730. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  12731. PreferencesUtil.putSync('LastMusicList', this.songList)
  12732. PreferencesUtil.putSync('LastPlayQueueScope', this.playQueueScope)
  12733. PreferencesUtil.putSync('LastPlayModeType', this.modeType)
  12734. PreferencesUtil.putSync('LastPlayTotalCount', this.totalCount)
  12735. }
  12736. // 清空播放记录
  12737. clearVideoHistory() {
  12738. this.table.clearPlayHistory((success: boolean, error?: string) => {
  12739. if (success) {
  12740. this.historyList = [];
  12741. this.updateListData(this.historyList)
  12742. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  12743. ToastUtil.showToast('清空播放记录成功')
  12744. } else {
  12745. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  12746. }
  12747. });
  12748. }
  12749. public async setAvSessionListener() {
  12750. if (!this.avSessionController) {
  12751. return;
  12752. }
  12753. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  12754. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  12755. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  12756. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  12757. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  12758. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  12759. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  12760. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  12761. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  12762. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  12763. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  12764. }
  12765. setLoopMode() {
  12766. let itype = this.playType + 1
  12767. if (itype >= 4) {
  12768. this.playType = 0
  12769. ToastUtil.showToast('连续播放')
  12770. } else if (itype === 1) {
  12771. this.playType = 1
  12772. ToastUtil.showToast('单曲循环')
  12773. } else if (itype === 2) {
  12774. this.playType = 2
  12775. ToastUtil.showToast('单曲播完')
  12776. } else if (itype === 3) {
  12777. this.playType = 3
  12778. ToastUtil.showToast('随机播放')
  12779. } else if (itype === 0) {
  12780. this.playType = 0
  12781. ToastUtil.showToast('连续播放')
  12782. }
  12783. PreferencesUtil.putSync('musicPlayType', this.playType)
  12784. this.setCurrentPlayMode()
  12785. }
  12786. private sessionSetLoopModeCallback = (mode: number) => {
  12787. if (this.mIjkMediaPlayer != null) {
  12788. ToastUtil.showToast('当前播放模式:' + mode)
  12789. Logger.info('onecold 当前播放模式= ' + mode)
  12790. let hmPlayMode = mode + 1
  12791. if (hmPlayMode >= 4) {
  12792. hmPlayMode = 0
  12793. }
  12794. if (hmPlayMode === 1) {
  12795. this.playType = 1
  12796. ToastUtil.showToast('单曲循环')
  12797. } else if (hmPlayMode === 0) {
  12798. this.playType = 2
  12799. ToastUtil.showToast('单曲播完')
  12800. } else if (hmPlayMode === 3) {
  12801. this.playType = 3
  12802. ToastUtil.showToast('随机播放')
  12803. } else if (hmPlayMode === 2) {
  12804. this.playType = 0
  12805. ToastUtil.showToast('连续播放')
  12806. }
  12807. PreferencesUtil.putSync('musicPlayType', this.playType)
  12808. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  12809. let playBackState: avSession.AVPlaybackState = {
  12810. loopMode: hmPlayMode,
  12811. };
  12812. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  12813. console.info(`set setLoopMode AVPlaybackState successfully`);
  12814. }).catch((err: BusinessError) => {
  12815. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  12816. });
  12817. }
  12818. }
  12819. setCurrentPlayMode() {
  12820. if (!this.avSessionController) {
  12821. return;
  12822. }
  12823. let mLoopMode = 0
  12824. switch (this.playType) {
  12825. case 0:
  12826. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  12827. break;
  12828. case 1:
  12829. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  12830. break;
  12831. case 2:
  12832. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  12833. break;
  12834. case 3:
  12835. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  12836. break;
  12837. }
  12838. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  12839. let playBState: avSession.AVPlaybackState = {
  12840. loopMode: mLoopMode,
  12841. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  12842. };
  12843. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  12844. console.info(`set setLoopMode AVPlaybackState successfully`);
  12845. }).catch((err: BusinessError) => {
  12846. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  12847. });
  12848. }
  12849. private sessionToggleFavoriteCallback = (assetId: string) => {
  12850. if (this.mIjkMediaPlayer != null && this.currentSong) {
  12851. console.info(`on toggleFavorite `);
  12852. // 应用收到收藏命令,进行收藏处理。
  12853. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  12854. this.doFav(this.currentSong)
  12855. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  12856. let playbackState: avSession.AVPlaybackState = {
  12857. isFavorite: !this.isFac,
  12858. };
  12859. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  12860. console.info(`SetAVPlaybackState successfully`);
  12861. }).catch((err: BusinessError) => {
  12862. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  12863. });
  12864. }
  12865. }
  12866. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  12867. device: avSession.OutputDeviceInfo) => {
  12868. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  12869. // 将 connectState 转换为可读的字符串
  12870. let stateName = 'UNKNOWN';
  12871. switch (connectState) {
  12872. case avSession.ConnectionState.STATE_CONNECTED:
  12873. stateName = 'CONNECTED(1)';
  12874. break;
  12875. case avSession.ConnectionState.STATE_DISCONNECTED:
  12876. stateName = 'DISCONNECTED(2)';
  12877. break;
  12878. case avSession.ConnectionState.STATE_CONNECTING:
  12879. stateName = 'CONNECTING(3)';
  12880. break;
  12881. default:
  12882. stateName = `OTHER(${connectState})`;
  12883. }
  12884. Logger.info('heanup sessionOutputDeviceChange', `设备状态变化: connectState=${stateName}, castCategory=${currentDevice?.castCategory}, isCastPlaying=${this.isCastPlaying}`);
  12885. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  12886. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  12887. await this.startCasting();
  12888. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  12889. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  12890. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  12891. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  12892. if (device) {
  12893. Logger.info('heanup sessionOutputDeviceChange', '设备断开连接');
  12894. Logger.info('heanup sessionOutputDeviceChange', '用户主动断开连接或已停止播放,调用endCasting');
  12895. this.endCasting();
  12896. }
  12897. }
  12898. };
  12899. private async startCasting() {
  12900. try {
  12901. Logger.info('heanup startCasting', '========== 开始投播初始化 ==========');
  12902. // 获取原始的 AVCastController
  12903. let avCastCtrl = await this.avSessionController.getAvSession()?.getAVCastController();
  12904. if (!avCastCtrl) {
  12905. Logger.error('heanup startCasting', '获取 AVCastController 失败');
  12906. return;
  12907. }
  12908. this.castController = avCastCtrl;
  12909. Logger.info('heanup startCasting', '✅ 获取 AVCastController 成功');
  12910. // 创建新的 CastController 封装器
  12911. this.castControllerWrapper = new CastController(avCastCtrl);
  12912. Logger.info('heanup startCasting', '✅ 创建 CastController 成功');
  12913. // 设置回调函数
  12914. let callbacks: CastControllerCallbacks = {
  12915. onPlayNext: () => {
  12916. Logger.info('heanup CastController', '收到 playNext 回调');
  12917. this.playNext();
  12918. },
  12919. onPlayPrevious: () => {
  12920. Logger.info('heanup CastController', '收到 playPrevious 回调');
  12921. this.playPrevious();
  12922. },
  12923. onPositionChanged: (position: number) => {
  12924. this.positionChange(position);
  12925. },
  12926. onDurationChanged: (duration: number) => {
  12927. this.playDurationChange(duration);
  12928. }
  12929. };
  12930. this.castControllerWrapper.setCallbacks(callbacks);
  12931. Logger.info('heanup startCasting', '✅ 设置回调成功');
  12932. // 暂停本地播放
  12933. this.pause();
  12934. Logger.info('heanup startCasting', '✅ 暂停本地播放成功');
  12935. // 初始化投播会话
  12936. Logger.info('heanup startCasting', `准备调用 initAVCast: songList.length=${this.songList.length}, curIndex=${this.curIndex}, videoUrl=${this.videoUrl}`);
  12937. await this.castControllerWrapper.initAVCast(
  12938. this.songList,
  12939. this.curIndex,
  12940. this.mIjkMediaPlayer.getCurrentPosition(),
  12941. this.videoUrl,
  12942. this.getActiveDuration()
  12943. );
  12944. Logger.info('heanup startCasting', '✅ initAVCast 调用完成');
  12945. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  12946. refToIsCasting?.set(true);
  12947. this.castSeek = true;
  12948. // 从 CastController 获取投播状态
  12949. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  12950. if (this.isCastPlaying) {
  12951. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  12952. this.setIsPlaying(true);
  12953. this.updateSessionPlayState(true);
  12954. }
  12955. Logger.info('heanup startCasting', `✅ 投播初始化完成, isCastPlaying=${this.isCastPlaying}`);
  12956. } catch (error) {
  12957. Logger.error('heanup startCasting', `❌ 投播初始化失败: ${error}`);
  12958. }
  12959. }
  12960. async changeCasting() {
  12961. Logger.info('heanup changeCasting', '切换投播');
  12962. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  12963. this.initQueueItem();
  12964. await this.prepare();
  12965. this.setPlaybackStateChangeListener();
  12966. // isCastPlaying 会在 playbackStateChangeListener 中根据实际状态更新
  12967. this.castSeek = true;
  12968. }
  12969. public endCasting() {
  12970. Logger.info('heanup endCasting', 'endCasting被调用');
  12971. this.avSessionController.getAvSession()?.stopCasting();
  12972. this.stopCast();
  12973. // 关闭文件描述符
  12974. if (this.castFile) {
  12975. try {
  12976. fs.closeSync(this.castFile);
  12977. this.castFile = undefined;
  12978. Logger.info('heanup endCasting', '关闭投播文件描述符');
  12979. } catch (error) {
  12980. Logger.warn('heanup endCasting', `关闭文件描述符失败: ${error}`);
  12981. }
  12982. }
  12983. this.isCastPlaying = false;
  12984. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  12985. refToIsCasting?.set(false);
  12986. this.pause();
  12987. this.setIsPlaying(false);
  12988. // if (this.curIndex === this.curSource.index) {
  12989. // this.play
  12990. // this.seek(this.currentTime * 1000);
  12991. // this.setIsPlaying(true);
  12992. // } else {
  12993. // this.pauseVideo();
  12994. // this.setIsPlaying(false);
  12995. // }
  12996. }
  12997. public setIsPlaying(isPlayer: boolean) {
  12998. this.isPlaying = isPlayer;
  12999. // 发送播放状态变化事件给歌单详情页面
  13000. try {
  13001. const eventPlaybackStatus: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYBACK_STATUS }
  13002. const currentFilePath = this.currentSong?.filePath || ''
  13003. const eventData: emitter.EventData = {
  13004. data: {
  13005. isPlaying: this.isPlaying,
  13006. curIndex: this.curIndex,
  13007. currentFilePath: currentFilePath
  13008. }
  13009. };
  13010. emitter.emit(eventPlaybackStatus, eventData)
  13011. Logger.info(`heanup 发送播放状态变化事件: isPlaying=${this.isPlaying}, curIndex=${this.curIndex}, currentFilePath=${currentFilePath}`)
  13012. } catch (error) {
  13013. Logger.error('heanup 发送播放状态变化事件失败: ' + error)
  13014. }
  13015. }
  13016. private setPlaybackStateChangeListener(): void {
  13017. // 注意: HarmonyOS 的投播控制器可能不返回 state 字段
  13018. // 我们需要通过其他方式来判断播放状态
  13019. // 1. 监听位置变化
  13020. this.castController?.on('playbackStateChange', ['position'], (playbackState: avSession.AVPlaybackState) => {
  13021. if (playbackState.position && typeof playbackState.position.elapsedTime !== 'undefined') {
  13022. Logger.info('heanup playbackStateChange[position]', `elapsedTime=${playbackState.position.elapsedTime}`);
  13023. this.positionChange(playbackState.position.elapsedTime);
  13024. }
  13025. });
  13026. // 2. 监听时长变化
  13027. this.castController?.on('playbackStateChange', ['extras'], (playbackState: avSession.AVPlaybackState) => {
  13028. const duration = playbackState?.extras?.duration;
  13029. if (typeof duration === 'number') {
  13030. this.playDurationChange(duration);
  13031. }
  13032. });
  13033. // 3. 监听所有状态变化(用于调试和状态判断)
  13034. this.castController?.on('playbackStateChange', 'all', (playbackState: avSession.AVPlaybackState) => {
  13035. Logger.info('heanup playbackStateChange[all]', `完整状态=${JSON.stringify(playbackState)}`);
  13036. // 检查是否有 state 字段(某些设备可能返回)
  13037. if (playbackState.state !== undefined) {
  13038. Logger.info('heanup playbackStateChange', `state字段存在: ${playbackState.state}`);
  13039. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  13040. this.isCastPlaying = true;
  13041. }
  13042. }
  13043. });
  13044. // 4. 监听播放完成事件
  13045. this.castController?.on('endOfStream', this.playNextCallback);
  13046. this.castController?.on('playNext', this.playNextCallback);
  13047. this.castController?.on('playPrevious', this.playPreviousCallback);
  13048. // 5. 监听错误事件
  13049. this.castController?.on('error', (error: BusinessError) => {
  13050. Logger.error('heanup playbackStateChange', `投播错误: code=${error.code}, message=${error.message}`);
  13051. this.isCastPlaying = false;
  13052. });
  13053. }
  13054. private updateSessionPlayState(isPlay: boolean): void {
  13055. // if(!this.isBgPlayOpen)
  13056. // return
  13057. const elapsedTime = (this.castControllerWrapper && this.isCastPlaying) ? this.currentTime2 * 1000
  13058. : this.mIjkMediaPlayer.getCurrentPosition();
  13059. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  13060. this.setAVSessionPlayState({
  13061. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  13062. position: {
  13063. elapsedTime: elapsedTime,
  13064. updateTime: new Date().getTime()
  13065. }
  13066. });
  13067. }
  13068. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  13069. this.avSessionController.setAvSessionPlayState(playbackState)
  13070. }
  13071. private positionChange(position: number) {
  13072. this.currentTime2 = position / 1000;
  13073. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  13074. if (this.castControllerWrapper && this.isCastPlaying) {
  13075. this.updateCastProgress(position);
  13076. if (this.isSeekTo) {
  13077. this.isSeekTo = false;
  13078. }
  13079. }
  13080. }
  13081. private playDurationChange(duration: number) {
  13082. this.duration = duration;
  13083. this.durationTime = Math.floor(this.duration / 1000);
  13084. this.durationStringTime = secondToTime((this.durationTime));
  13085. if (this.castControllerWrapper && this.isCastPlaying) {
  13086. this.totalTime = this.stringForTime(this.duration);
  13087. }
  13088. }
  13089. // playbackStateChangeListener 方法已被删除,改用 setPlaybackStateChangeListener 中的内联函数
  13090. private reloadCasting = async () => {
  13091. Logger.info('heanup reloadCasting', '重新加载投播');
  13092. // 使用 initQueueItem() 方法来准备投播项目,保持逻辑一致
  13093. this.initQueueItem();
  13094. await this.prepare();
  13095. };
  13096. public playNextCallback = (): void => {
  13097. this.playNext().catch(() => {
  13098. Logger.error('heanup playNextCallback', `播放下一首失败`);
  13099. });
  13100. };
  13101. public playPreviousCallback = (): void => {
  13102. this.playPrevious().catch(() => {
  13103. Logger.error('heanup playNextCallback', `播放上一首失败`);
  13104. });
  13105. };
  13106. async prepare() {
  13107. try {
  13108. Logger.info('heanup prepare', `开始准备投播: ${this.castItem?.description?.title}`);
  13109. await this.castController?.prepare(this.castItem);
  13110. Logger.info('heanup prepare', '投播prepare成功');
  13111. await this.castController?.start(this.castItem);
  13112. Logger.info('heanup prepare', '投播start成功');
  13113. // 投播启动成功,设置为投播状态
  13114. this.isCastPlaying = true;
  13115. Logger.info('heanup prepare', '投播启动成功,设置isCastPlaying=true');
  13116. } catch (error) {
  13117. Logger.error('heanup prepare', `投播准备失败: ${error}`);
  13118. this.isCastPlaying = false;
  13119. }
  13120. }
  13121. public initQueueItem() {
  13122. let item = this.songList[this.curIndex];
  13123. // 判断是否是流媒体地址 - 使用 videoUrl 判断而不是 filePath
  13124. // 因为 filePath 可能是 navidrome:// 等自定义协议,而 videoUrl 才是真实的流地址
  13125. let isStreaming = this.isUrl(this.videoUrl);
  13126. Logger.info('heanup initQueueItem', `准备投播歌曲: ${item.name}, 是否流媒体: ${isStreaming}, videoUrl: ${this.videoUrl}`);
  13127. // 关闭之前的文件描述符
  13128. if (this.castFile) {
  13129. try {
  13130. fs.closeSync(this.castFile);
  13131. Logger.info('heanup initQueueItem', '关闭之前的文件描述符');
  13132. } catch (error) {
  13133. Logger.warn('heanup initQueueItem', `关闭文件描述符失败: ${error}`);
  13134. }
  13135. }
  13136. let description: avSession.AVMediaDescription = {
  13137. assetId: 'AUDIO-' + item.filePath,
  13138. title: item.name,
  13139. artist: item.artist || '',
  13140. // 该字段大写,音频'AUDIO',视频'VIDEO'
  13141. mediaType: 'AUDIO',
  13142. mediaSize: item.videoSize,
  13143. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  13144. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  13145. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  13146. duration: this.duration,
  13147. albumCoverUri: item.pixelMapPath, // 本地路径电视可能无法访问,暂时注释
  13148. appName: this.appName,
  13149. lyricContent: item.lyricContent,
  13150. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  13151. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  13152. };
  13153. console.log('heanup initQueueItem this.lyricContent', item.lyricContent);
  13154. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  13155. if (isStreaming) {
  13156. // 流媒体地址使用 mediaUri
  13157. description.mediaUri = this.videoUrl;
  13158. Logger.info('heanup initQueueItem', `使用流媒体地址投播: ${this.videoUrl}`);
  13159. } else {
  13160. // 本地文件使用 fdSrc
  13161. const localPath = this.videoUrl || item.filePath;
  13162. let uri = fileUri.getUriFromPath(localPath);
  13163. this.castFile = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  13164. let fdSrc: media.AVFileDescriptor = {
  13165. fd: this.castFile.fd
  13166. };
  13167. description.fdSrc = fdSrc;
  13168. Logger.info('heanup initQueueItem', `使用本地文件投播: ${localPath}, fd: ${this.castFile.fd}`);
  13169. }
  13170. this.castItem = {
  13171. itemId: this.curIndex,
  13172. description: description
  13173. };
  13174. Logger.info('heanup initQueueItem', `投播项目创建完成: ${JSON.stringify({
  13175. title: description.title,
  13176. mediaType: description.mediaType,
  13177. hasMediaUri: !!description.mediaUri,
  13178. hasFdSrc: !!description.fdSrc,
  13179. duration: description.duration
  13180. })}`);
  13181. }
  13182. // 判断是否是 URL 或流媒体地址
  13183. private isUrl(str: string): boolean {
  13184. if (!str) {
  13185. return false;
  13186. }
  13187. // 检查常见的流媒体协议
  13188. if (str.startsWith('http://') || str.startsWith('https://') ||
  13189. str.startsWith('rtmp://') || str.startsWith('rtsp://') ||
  13190. str.startsWith('rtp://') || str.startsWith('mms://')) {
  13191. return true;
  13192. }
  13193. // 扩展的URL正则表达式,支持多种协议
  13194. const urlPattern = new RegExp(
  13195. '^((https?|ftp|rtmp|rtsp|mms|ws|rtp|wss):\\/\\/)?' + // 支持多种协议
  13196. '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // 域名
  13197. '((\\d{1,3}\\.){3}\\d{1,3})|' + // 或IPv4地址
  13198. '\\[([a-f\\d]{1,4}:){7}[a-f\\d]{1,4}\\]|' + // 或IPv6地址
  13199. 'localhost)' + // 或localhost
  13200. '(\\:\\d+)?' + // 端口号(可选)
  13201. '(\\/[-a-z\\d%_.~+]*)*' + // 路径
  13202. '(\\?[;&a-z\\d%_.~+=-]*)?' + // 查询字符串(可选)
  13203. '(\\#[-a-z\\d_]*)?$', // 片段标识符(可选)
  13204. 'i' // 不区分大小写
  13205. );
  13206. return urlPattern.test(str);
  13207. }
  13208. async stopCast() {
  13209. try {
  13210. // 使用 CastController 释放资源
  13211. if (this.castControllerWrapper) {
  13212. await this.castControllerWrapper.releaseAVCast();
  13213. Logger.info('heanup stopCast', 'CastController 释放投播控制器成功');
  13214. }
  13215. // 清空引用
  13216. this.castControllerWrapper = undefined;
  13217. this.castController = undefined;
  13218. this.castItem = undefined;
  13219. this.castFile = undefined;
  13220. } catch (error) {
  13221. Logger.error('heanup stopCast', `停止投播失败: ${error}`);
  13222. }
  13223. }
  13224. private sessionPlayCallback = (): void => {
  13225. this.playOrPause()
  13226. };
  13227. private sessionPauseCallback = (): void => {
  13228. this.pause()
  13229. };
  13230. private async playOrPause() {
  13231. if (!this.debounce()) {
  13232. return;
  13233. }
  13234. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  13235. await this.pause();
  13236. } else {
  13237. // 如果是投播模式,使用 CastController 的 play 方法
  13238. if (this.castControllerWrapper && this.isCastPlaying) {
  13239. try {
  13240. Logger.info('heanup playOrPause', '投播模式播放');
  13241. await this.castControllerWrapper.setPlaying();
  13242. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  13243. this.setIsPlaying(true);
  13244. this.updateSessionPlayState(true);
  13245. Logger.info('heanup playOrPause', '投播播放成功');
  13246. this.playChange();
  13247. } catch (error) {
  13248. Logger.error('heanup playOrPause', `投播播放失败: ${error}`);
  13249. }
  13250. } else {
  13251. console.info('onecold startPlayOrResumePlay 11064')
  13252. this.startPlayOrResumePlay();
  13253. this.playChange()
  13254. }
  13255. }
  13256. }
  13257. private sessionPlayNextCallback = (): void => {
  13258. this.playNext().catch(() => {
  13259. Logger.error('heanup sessionPlayPreviousCallback', `播放下 一首失败`);
  13260. });
  13261. };
  13262. private sessionPlayPreviousCallback = (): void => {
  13263. this.playPrevious().catch(() => {
  13264. Logger.error('heanup sessionPlayPreviousCallback', `播放上一首失败`);
  13265. });
  13266. };
  13267. private sessionStopCallback = (): void => {
  13268. this.stop()
  13269. };
  13270. private sessionFastForwardCallback = async (time?: number) => {
  13271. if (!time) {
  13272. return;
  13273. }
  13274. let curPosition: number;
  13275. if (this.castController && this.isCastPlaying) {
  13276. // 投播模式,使用UI显示的时间
  13277. curPosition = this.currentTime2 * 1000;
  13278. } else if (this.mIjkMediaPlayer != null) {
  13279. // 本地播放器模式
  13280. curPosition = this.mIjkMediaPlayer.getCurrentPosition();
  13281. } else {
  13282. return;
  13283. }
  13284. let seeTime = curPosition + time * 1000;
  13285. // 限制 seekValue 在合法范围内
  13286. if (seeTime < 0) {
  13287. seeTime = 0;
  13288. } else if (seeTime > this.duration) {
  13289. seeTime = this.duration;
  13290. }
  13291. Logger.info('heanup sessionFastForwardCallback', `快进: ${time}秒, 目标位置: ${seeTime}ms`);
  13292. this.setSeekToActionProgress(seeTime);
  13293. await this.seekTo(seeTime + "");
  13294. };
  13295. private getActiveDuration(): number {
  13296. let duration = this.mIjkMediaPlayer.getDuration();
  13297. if (this.castControllerWrapper && this.isCastPlaying) {
  13298. return this.duration > 0 ? this.duration : duration;
  13299. }
  13300. if (duration <= 0 && this.duration > 0) {
  13301. duration = this.duration;
  13302. }
  13303. return duration;
  13304. }
  13305. private getSongDurationMs(song?: VideoItem): number {
  13306. if (!song || !song.duration) {
  13307. return 0;
  13308. }
  13309. const raw = song.duration.trim();
  13310. if (!raw) {
  13311. return 0;
  13312. }
  13313. const parts = raw.split(':').map((part) => Number(part));
  13314. if (parts.some((part) => Number.isNaN(part))) {
  13315. return 0;
  13316. }
  13317. let seconds = 0;
  13318. if (parts.length === 3) {
  13319. seconds = parts[0] * 3600 + parts[1] * 60 + parts[2];
  13320. } else if (parts.length === 2) {
  13321. seconds = parts[0] * 60 + parts[1];
  13322. } else if (parts.length === 1) {
  13323. seconds = parts[0];
  13324. }
  13325. return seconds > 0 ? seconds * 1000 : 0;
  13326. }
  13327. private updateCastProgress(position: number): void {
  13328. const duration = this.getActiveDuration();
  13329. if (duration <= 0) {
  13330. return;
  13331. }
  13332. this.slideEnable = true;
  13333. let pos = (position / duration) * 100;
  13334. if (pos > this.PROGRESS_MAX_VALUE) {
  13335. this.progressValue = this.PROGRESS_MAX_VALUE;
  13336. } else if (pos < 0) {
  13337. this.progressValue = 0;
  13338. } else {
  13339. this.progressValue = pos;
  13340. }
  13341. this.totalTime = this.stringForTime(duration);
  13342. if (position > duration) {
  13343. position = duration;
  13344. }
  13345. this.isCurrentTime = true;
  13346. this.currentTime = this.stringForTime(position);
  13347. this.isCurrentTime = false;
  13348. this.lyricController.updatePosition(position + this.timeOffset * 1000);
  13349. if(this.showPipLyric){
  13350. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000);
  13351. }
  13352. if(this.isShowSingleLineLyric){
  13353. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000);
  13354. }
  13355. }
  13356. /**
  13357. * Gesture method onActionUpdate.
  13358. *
  13359. * @param event Gesture event.手势拖动设置快进和后退
  13360. */
  13361. private setSeekToActionProgress(position: number) {
  13362. // 投播模式使用this.duration,本地模式使用播放器获取
  13363. let duration = this.getActiveDuration();
  13364. let pos = 0;
  13365. if (duration > 0) {
  13366. this.slideEnable = true;
  13367. let curPercent = position / duration;
  13368. pos = curPercent * 100;
  13369. if (pos > this.PROGRESS_MAX_VALUE) {
  13370. this.progressValue = this.PROGRESS_MAX_VALUE
  13371. } else {
  13372. this.progressValue = pos;
  13373. }
  13374. }
  13375. // LogUtils.getInstance()
  13376. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  13377. this.totalTime = this.stringForTime(duration);
  13378. if (position > duration) {
  13379. position = duration;
  13380. }
  13381. this.isCurrentTime = true;
  13382. this.currentTime = this.stringForTime(position);
  13383. this.isCurrentTime = false
  13384. }
  13385. private sessionRewindCallback = async (time?: number) => {
  13386. if (!time) {
  13387. return;
  13388. }
  13389. let curPosition: number;
  13390. if (this.castController && this.isCastPlaying) {
  13391. // 投播模式,使用UI显示的时间
  13392. curPosition = this.currentTime2 * 1000;
  13393. } else if (this.mIjkMediaPlayer != null) {
  13394. // 本地播放器模式
  13395. curPosition = this.mIjkMediaPlayer.getCurrentPosition();
  13396. } else {
  13397. return;
  13398. }
  13399. let seeTime = curPosition - time * 1000;
  13400. // 限制 seekValue 在合法范围内
  13401. if (seeTime < 0) {
  13402. seeTime = 0;
  13403. } else if (seeTime > this.duration) {
  13404. seeTime = this.duration;
  13405. }
  13406. Logger.info('heanup sessionRewindCallback', `快退: ${time}秒, 目标位置: ${seeTime}ms`);
  13407. this.setSeekToActionProgress(seeTime);
  13408. await this.seekTo(seeTime + "");
  13409. };
  13410. private sessionSeekCallback = async (seekTime: number) => {
  13411. Logger.info('heanup sessionSeekCallback', `收到seek请求: ${seekTime}ms, 投播模式: ${this.isCastPlaying}`);
  13412. // 投播模式直接调用seekTo,它会自动处理投播控制器的seek命令
  13413. await this.seekTo(seekTime + "");
  13414. };
  13415. private async getFileSize(filePath: string): Promise<number> {
  13416. try {
  13417. const stat = await fs.stat(filePath);
  13418. return stat.size;
  13419. } catch (err) {
  13420. console.error('Failed to get file size: ' + err.message);
  13421. return 0;
  13422. }
  13423. }
  13424. private async pause() {
  13425. // 如果是投播模式,使用 CastController 的 pause 方法
  13426. if (this.castControllerWrapper && this.isCastPlaying) {
  13427. try {
  13428. Logger.info('heanup pause', '投播模式暂停');
  13429. await this.castControllerWrapper.setPause();
  13430. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  13431. this.setIsPlaying(false);
  13432. this.updateSessionPlayState(false);
  13433. Logger.info('heanup pause', '投播暂停成功');
  13434. } catch (error) {
  13435. Logger.error('heanup pause', `投播暂停失败: ${error}`);
  13436. }
  13437. } else if (this.mIjkMediaPlayer.isPlaying()) {
  13438. // 本地播放器模式
  13439. this.savePlaybackPosition();
  13440. this.mIjkMediaPlayer.pause();
  13441. this.setProgress();
  13442. this.mDestroyPage = true;
  13443. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  13444. this.updateSessionPlayState(false)
  13445. this.playChange()
  13446. if (this.pipController) {
  13447. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  13448. PiPWindow.PiPControlStatus.PAUSE);
  13449. }
  13450. }
  13451. }
  13452. private stop() {
  13453. this.savePlaybackPosition();
  13454. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13455. this.mIjkMediaPlayer.stop();
  13456. this.mIjkMediaPlayer.release();
  13457. this.stopProgressTask();
  13458. this.updateSessionPlayState(false)
  13459. this.playChange()
  13460. this.watchStatus();
  13461. }
  13462. //保持记忆播放功能
  13463. private savePlaybackPosition() {
  13464. if (this.mIjkMediaPlayer != null) {
  13465. const position = this.mIjkMediaPlayer.getCurrentPosition();
  13466. // ToastUtil.showToast('保存记忆播放 = ' + position)
  13467. const duration = this.mIjkMediaPlayer.getDuration();
  13468. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  13469. // 如果播放位置接近视频末尾,则保存 position 为 0
  13470. const playbackPosition = (duration - position < threshold) ? 0 : position;
  13471. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  13472. }
  13473. }
  13474. //获取记忆播放功能
  13475. private restorePlaybackPosition() {
  13476. const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  13477. if (this.mIjkMediaPlayer != null && position > 0) {
  13478. this.seekTo(position + "");
  13479. }
  13480. }
  13481. private async seekTo(value: string) {
  13482. if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  13483. ToastUtil.showToast('wma格式不支持拖动快进。')
  13484. return
  13485. }
  13486. // 如果是投播模式,使用 CastController 的 seek 方法
  13487. if (this.castControllerWrapper && this.isCastPlaying) {
  13488. try {
  13489. let seekPos = Number.parseInt(value);
  13490. this.isSeekTo = true;
  13491. Logger.info('heanup seekTo', `投播模式seek到: ${seekPos}ms, 当前时长: ${this.duration}ms`);
  13492. // 检查是否接近末尾
  13493. if (this.duration > 0 && seekPos >= this.duration - 500) {
  13494. Logger.warn('heanup seekTo', `快进位置接近末尾(${seekPos}ms >= ${this.duration}ms),可能触发播放完成`);
  13495. }
  13496. await this.castControllerWrapper.seek(seekPos);
  13497. Logger.info('heanup seekTo', `投播seek命令发送成功,位置: ${seekPos}ms`);
  13498. } catch (error) {
  13499. Logger.error('heanup seekTo', `投播seek失败: ${error}`);
  13500. }
  13501. } else {
  13502. // 本地播放器模式
  13503. this.isSeekTo = true
  13504. this.mIjkMediaPlayer.seekTo(value);
  13505. this.setProgress()
  13506. this.isSeekTo = false
  13507. }
  13508. }
  13509. // 添加到下一首播放
  13510. private addToNextPlay(song: VideoItem) {
  13511. if (!this.debounce()) {
  13512. return;
  13513. }
  13514. if (this.currentSong) {
  13515. if (this.currentSong === song) {
  13516. ToastUtil.showToast('当前已经在播放这首歌了!')
  13517. return
  13518. }
  13519. }
  13520. // 如果未开始播放或队列为空
  13521. if (this.curIndex === -1 || this.songList.length === 0) {
  13522. this.songList = [song];
  13523. this.curIndex = 0;
  13524. this.doPlay(song)
  13525. return;
  13526. }
  13527. // 插入到当前索引+1的位置
  13528. const insertPos = this.curIndex + 1;
  13529. this.songList.splice(insertPos, 0, song);
  13530. this.songList = [...this.songList]; // 触发状态更新
  13531. this.sonDataSource.pushArrayData(this.songList)
  13532. ToastUtil.showToast('已添加至下一首播放')
  13533. }
  13534. //后退10s,可再设置设置默认几秒
  13535. async backForward() {
  13536. // 如果是投播模式,从currentTime2获取当前位置
  13537. let pos: number;
  13538. if (this.castController && this.isCastPlaying) {
  13539. pos = this.currentTime2 * 1000; // 使用秒转毫秒
  13540. Logger.info('heanup backForward', `投播模式当前位置: ${pos}ms`);
  13541. } else if (this.mIjkMediaPlayer) {
  13542. pos = this.mIjkMediaPlayer.getCurrentPosition();
  13543. } else {
  13544. return;
  13545. }
  13546. let value = pos - Number(this.fastForwardSeconds) * 1000;
  13547. if (value < 0) {
  13548. value = 0;
  13549. }
  13550. await this.seekTo(value + "");
  13551. }
  13552. //快进10s,可再设置设置默认几秒
  13553. async fastForward() {
  13554. // 如果是投播模式,从currentTime2获取当前位置
  13555. let pos: number;
  13556. if (this.castController && this.isCastPlaying) {
  13557. pos = this.currentTime2 * 1000; // 使用秒转毫秒
  13558. Logger.info('heanup fastForward', `投播模式当前位置: ${pos}ms`);
  13559. } else if (this.mIjkMediaPlayer) {
  13560. pos = this.mIjkMediaPlayer.getCurrentPosition();
  13561. } else {
  13562. return;
  13563. }
  13564. let value = pos + Number(this.fastForwardSeconds) * 1000;
  13565. // 限制不超过总时长
  13566. if (this.duration > 0 && value > this.duration) {
  13567. value = this.duration;
  13568. }
  13569. await this.seekTo(value + "");
  13570. }
  13571. //下一个
  13572. private async playNext() {
  13573. Logger.info('heanup playNext', '========== playNext 开始 ==========');
  13574. Logger.info('heanup playNext', `isCastPlaying=${this.isCastPlaying}, castControllerWrapper存在=${!!this.castControllerWrapper}`);
  13575. if (!this.debounce()) {
  13576. Logger.warn('heanup playNext', 'debounce() 返回 false,退出');
  13577. return;
  13578. }
  13579. Logger.info('heanup playNext', `playType=${this.playType}`);
  13580. if (this.playType == 3) { //3:随机播放
  13581. Logger.info('heanup playNext', '随机播放模式');
  13582. await this.randomPlay()
  13583. return;
  13584. }
  13585. if (ArrayUtil.isNotEmpty(this.songList)) {
  13586. if (this.curIndex >= this.songList.length - 1) {
  13587. await this.tryLoadNextPageForPlayback();
  13588. }
  13589. if (this.curIndex >= this.songList.length - 1) {
  13590. this.curIndex = 0;
  13591. } else {
  13592. this.curIndex++;
  13593. }
  13594. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  13595. this.currentSong = this.songList[this.curIndex];
  13596. console.info('heanup playNext', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  13597. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13598. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13599. context: this.context,
  13600. autoParseMusicName: this.autoParseMusicName
  13601. });
  13602. this.artist = this.songList[this.curIndex].artist
  13603. this.name = this.songList[this.curIndex].name
  13604. //this.cover = this.songList[this.curIndex].pixelMapPath
  13605. console.info('heanup playNext 1 ', `this.isCastPlaying: ${ this.isCastPlaying}`)
  13606. console.info('heanup playNext 2 ', `this.castControllerWrapper: ${this.castControllerWrapper}`)
  13607. // 如果是投播模式,使用 CastController 播放下一首
  13608. if (this.castControllerWrapper) {
  13609. console.info('heanup playNext', '使用 CastController 播放下一首');
  13610. try {
  13611. const nextDuration = this.getSongDurationMs(this.currentSong);
  13612. if (nextDuration > 0) {
  13613. this.duration = nextDuration;
  13614. this.durationTime = Math.floor(nextDuration / 1000);
  13615. this.durationStringTime = secondToTime(this.durationTime);
  13616. this.totalTime = this.stringForTime(nextDuration);
  13617. this.avSessionController.setAVMetadataMusic(this.currentSong, nextDuration, this.lyricContent);
  13618. }
  13619. this.updateCastProgress(0);
  13620. await this.castControllerWrapper.playNext(this.songList, this.curIndex, this.videoUrl, nextDuration);
  13621. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  13622. console.info('heanup playNext', 'CastController 播放下一首成功');
  13623. return;
  13624. } catch (error) {
  13625. console.error('heanup playNext', `CastController 播放下一首失败: ${error}`);
  13626. // 如果投播失败,回退到本地播放
  13627. this.isCastPlaying = false;
  13628. }
  13629. }
  13630. // 本地播放器模式,需要先stop
  13631. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13632. this.stop();
  13633. this.changeImageAnimation()
  13634. }
  13635. }
  13636. changeImageAnimation() {
  13637. if(this.openSkipSongAnimate){
  13638. // 第一步:淡出动画
  13639. this.getUIContext()?.animateTo({
  13640. duration: 500,
  13641. curve: Curve.EaseOut,
  13642. }, () => {
  13643. this.opacityValueImage = 0.1;
  13644. if(this.isCoverRectangle){
  13645. this.scaleValueImage = 0.88
  13646. }
  13647. });
  13648. // 第二步:切换图片后淡入
  13649. setTimeout(() => {
  13650. this.cover = this.songList[this.curIndex].pixelMapPath
  13651. this.getUIContext()?.animateTo({
  13652. duration: 500,
  13653. curve: Curve.EaseIn,
  13654. }, () => {
  13655. this.opacityValueImage = 1;
  13656. this.scaleValueImage = 1 // 图标恢复到原始大小
  13657. this.startPlayOrResumePlay()
  13658. });
  13659. }, 500);
  13660. }else{
  13661. this.cover = this.songList[this.curIndex].pixelMapPath
  13662. this.startPlayOrResumePlay()
  13663. }
  13664. }
  13665. // 内部方法:提前缓存下一首
  13666. private async preloadNextSongInternal(): Promise<void> {
  13667. // 随机模式下传递已播放索引集合
  13668. if (this.playType === 3) {
  13669. this.preloadNextRandomIndex = await preloadNextSongIfNeeded(
  13670. this.songList,
  13671. this.curIndex,
  13672. this.playType,
  13673. this.playedIndices
  13674. );
  13675. } else {
  13676. this.preloadNextRandomIndex = await preloadNextSongIfNeeded(
  13677. this.songList,
  13678. this.curIndex,
  13679. this.playType
  13680. );
  13681. }
  13682. }
  13683. // 存储已播放的歌曲索引
  13684. private playedIndices: Set<number> = new Set();
  13685. // 存储已播放的本地歌曲路径(随机播放去重用)
  13686. private playedLocalFilePaths: Set<string> = new Set();
  13687. // 随机播放模式下的播放历史栈(记录实际播放顺序,用于"上一首"功能)
  13688. private randomPlayHistory: VideoItem[] = [];
  13689. //随机播放
  13690. private async randomPlay() {
  13691. // if (!this.debounce()) {
  13692. // return;
  13693. // }
  13694. if (this.currentSong) {
  13695. // 将当前歌加入到随机播放历史栈(在切换到新歌之前)
  13696. this.randomPlayHistory.unshift(this.currentSong);
  13697. // 限制历史栈大小,避免无限增长
  13698. if (this.randomPlayHistory.length > 50) {
  13699. this.randomPlayHistory = this.randomPlayHistory.slice(0, 50);
  13700. }
  13701. Logger.info(TAG, `randomPlay: 将当前歌加入历史栈, 栈大小: ${this.randomPlayHistory.length}`);
  13702. const isCurrentRemote = isRemoteCloudType(this.currentSong.type);
  13703. const currentFilePath = this.currentSong.filePath;
  13704. if (isCurrentRemote) {
  13705. const remoteOptions: RandomSongQueryOptions = {
  13706. type: this.currentSong.type,
  13707. excludeFilePaths: currentFilePath ? [currentFilePath] : []
  13708. };
  13709. const randomRemoteSong = await this.table.queryRandomSong(remoteOptions);
  13710. if (randomRemoteSong) {
  13711. // 验证并修正webdav_account_id
  13712. if (randomRemoteSong.webdav_account_id) {
  13713. const manager = RemoteDriveManager.getInstance();
  13714. const account = await manager.getWebDavAccountById(randomRemoteSong.webdav_account_id);
  13715. if (!account) {
  13716. Logger.warn(TAG, `随机播放的歌曲账号ID无效: ${randomRemoteSong.webdav_account_id}, 尝试查找同类型账号`);
  13717. // 获取所有账号,查找相同类型的账号
  13718. const allAccounts = manager.getAllWebDavAccounts();
  13719. let foundAccount: WebDavAccount | null = null;
  13720. for (let i = 0; i < allAccounts.length; i++) {
  13721. if (allAccounts[i].webType === randomRemoteSong.type) {
  13722. foundAccount = allAccounts[i];
  13723. break;
  13724. }
  13725. }
  13726. if (foundAccount && foundAccount.id) {
  13727. Logger.info(TAG, `找到同类型账号,更新webdav_account_id: ${randomRemoteSong.webdav_account_id} -> ${foundAccount.id}`);
  13728. randomRemoteSong.webdav_account_id = foundAccount.id.toString();
  13729. // 更新数据库记录
  13730. await this.table.updateWebDavAccountId(randomRemoteSong.filePath, foundAccount.id.toString());
  13731. } else {
  13732. Logger.error(TAG, `无法找到类型为${randomRemoteSong.type}的账号,跳过此歌曲`);
  13733. return;
  13734. }
  13735. }
  13736. }
  13737. let nextIndex = this.songList.findIndex(song => song.filePath === randomRemoteSong.filePath);
  13738. if (nextIndex < 0) {
  13739. this.songList = [...this.songList, randomRemoteSong];
  13740. this.sonDataSource.pushArrayData(this.songList);
  13741. nextIndex = this.songList.length - 1;
  13742. }
  13743. this.curIndex = nextIndex;
  13744. this.playedIndices.add(this.curIndex);
  13745. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13746. this.stop();
  13747. this.currentSong = randomRemoteSong;
  13748. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13749. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13750. context: this.context,
  13751. autoParseMusicName: this.autoParseMusicName
  13752. });
  13753. this.name = this.currentSong.name;
  13754. this.artist = this.currentSong.artist;
  13755. this.changeImageAnimation();
  13756. return;
  13757. }
  13758. Logger.warn(TAG, '随机播放未获取到网盘歌曲,回退到列表随机');
  13759. } else {
  13760. if (currentFilePath) {
  13761. this.playedLocalFilePaths.add(currentFilePath);
  13762. }
  13763. const localOptions: RandomSongQueryOptions = {
  13764. type: CommonConstants.TYPE_LOCAL,
  13765. excludeFilePaths: Array.from(this.playedLocalFilePaths)
  13766. };
  13767. let randomLocalSong = await this.table.queryRandomSong(localOptions);
  13768. if (!randomLocalSong) {
  13769. this.playedLocalFilePaths.clear();
  13770. if (currentFilePath) {
  13771. this.playedLocalFilePaths.add(currentFilePath);
  13772. }
  13773. const fallbackLocalOptions: RandomSongQueryOptions = {
  13774. type: CommonConstants.TYPE_LOCAL,
  13775. excludeFilePaths: currentFilePath ? [currentFilePath] : []
  13776. };
  13777. randomLocalSong = await this.table.queryRandomSong(fallbackLocalOptions);
  13778. }
  13779. if (randomLocalSong !== null) {
  13780. const selectedLocalSong = randomLocalSong;
  13781. let nextIndex = this.songList.findIndex(song => song.filePath === selectedLocalSong.filePath);
  13782. if (nextIndex < 0) {
  13783. this.songList = [...this.songList, selectedLocalSong];
  13784. this.sonDataSource.pushArrayData(this.songList);
  13785. nextIndex = this.songList.length - 1;
  13786. }
  13787. this.curIndex = nextIndex;
  13788. this.playedIndices.add(this.curIndex);
  13789. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13790. this.stop();
  13791. this.currentSong = selectedLocalSong;
  13792. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13793. context: this.context,
  13794. autoParseMusicName: this.autoParseMusicName
  13795. });
  13796. this.name = this.currentSong.name;
  13797. this.artist = this.currentSong.artist;
  13798. this.changeImageAnimation();
  13799. return;
  13800. }
  13801. Logger.warn(TAG, '随机播放未获取到本地歌曲,回退到列表随机');
  13802. }
  13803. }
  13804. if (ArrayUtil.isNotEmpty(this.songList)) {
  13805. if (this.curIndex >= 0 && this.curIndex < this.songList.length) {
  13806. this.playedIndices.add(this.curIndex);
  13807. }
  13808. if (this.songList.length > 3) {
  13809. // 优先使用预缓存的随机索引(仅网盘播放时)
  13810. const nextSong = this.songList[this.preloadNextRandomIndex >= 0 ? this.preloadNextRandomIndex : 0];
  13811. const isNextRemote = nextSong && isRemoteCloudType(nextSong.type);
  13812. const isCurrentRemote = this.currentSong && isRemoteCloudType(this.currentSong.type);
  13813. if (this.preloadNextRandomIndex >= 0 && this.preloadNextRandomIndex < this.songList.length && isNextRemote && isCurrentRemote) {
  13814. Logger.info('heanup randomPlay', `使用预缓存的随机索引: ${this.preloadNextRandomIndex} (网盘播放)`);
  13815. this.curIndex = this.preloadNextRandomIndex;
  13816. this.playedIndices.add(this.curIndex);
  13817. this.preloadNextRandomIndex = -1; // 重置预缓存索引
  13818. } else {
  13819. // 如果没有预缓存索引,则正常随机选择
  13820. // 如果所有歌曲都播放过一次,清空已播放索引集合
  13821. if (this.playedIndices.size === this.songList.length) {
  13822. this.playedIndices.clear();
  13823. }
  13824. // 随机选择一个未播放的歌曲索引
  13825. let newIndex: number;
  13826. // 添加超时机制防止无限循环
  13827. let attempt = 0;
  13828. const maxAttempts = 100; // 根据需求调整
  13829. do {
  13830. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  13831. attempt++;
  13832. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  13833. if (attempt >= maxAttempts) {
  13834. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  13835. newIndex = Math.floor(Math.random() * this.songList.length);
  13836. }
  13837. this.curIndex = newIndex;
  13838. this.playedIndices.add(newIndex);
  13839. }
  13840. } else {
  13841. // 当歌曲数量小于或等于3时,直接播放下一首
  13842. if (this.curIndex == this.songList.length - 1) {
  13843. this.curIndex = 0;
  13844. } else {
  13845. this.curIndex++;
  13846. }
  13847. }
  13848. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13849. this.stop();
  13850. this.currentSong = this.songList[this.curIndex];
  13851. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13852. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13853. context: this.context,
  13854. autoParseMusicName: this.autoParseMusicName
  13855. });
  13856. this.name = this.songList[this.curIndex].name;
  13857. this.artist = this.songList[this.curIndex].artist
  13858. // this.cover = this.songList[this.curIndex].pixelMapPath
  13859. this.changeImageAnimation()
  13860. }
  13861. }
  13862. private async playIndex(index: number) {
  13863. if (!this.debounce()) {
  13864. return;
  13865. }
  13866. if (ArrayUtil.isNotEmpty(this.songList)) {
  13867. this.curIndex = index;
  13868. this.currentSong = this.songList[index];
  13869. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13870. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13871. context: this.context,
  13872. autoParseMusicName: this.autoParseMusicName
  13873. });
  13874. this.name = this.currentSong.name
  13875. this.artist = this.currentSong.artist
  13876. // 如果是投播模式,需要为投播设备准备当前歌曲
  13877. if (this.castController && this.isCastPlaying) {
  13878. Logger.info('heanup playIndex', '投播模式播放指定歌曲,不调用本地stop()');
  13879. this.initQueueItem();
  13880. await this.prepare();
  13881. this.cover = this.currentSong.pixelMapPath;
  13882. return;
  13883. }
  13884. // 本地播放器模式,需要先stop
  13885. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13886. this.stop();
  13887. this.changeImageAnimation()
  13888. }
  13889. }
  13890. //上一个
  13891. private async playPrevious() {
  13892. if (!this.debounce()) {
  13893. return;
  13894. }
  13895. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  13896. this.randomModePlayFromHistory()
  13897. return;
  13898. }
  13899. if (this.curIndex == 0) {
  13900. this.curIndex = this.songList.length - 1;
  13901. } else {
  13902. this.curIndex--;
  13903. }
  13904. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  13905. this.currentSong = this.songList[this.curIndex];
  13906. Logger.info('heanup playPrevious', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  13907. // 验证并修正webdav_account_id(针对远程类型歌曲)
  13908. if (isRemoteCloudType(this.currentSong.type) && this.currentSong.webdav_account_id) {
  13909. const manager = RemoteDriveManager.getInstance();
  13910. const account = await manager.getWebDavAccountById(this.currentSong.webdav_account_id);
  13911. if (!account) {
  13912. Logger.warn(TAG, `playPrevious: 歌曲账号ID无效: ${this.currentSong.webdav_account_id}, 尝试查找同类型账号`);
  13913. // 获取所有账号,查找相同类型的账号
  13914. const allAccounts = manager.getAllWebDavAccounts();
  13915. let foundAccount: WebDavAccount | null = null;
  13916. for (let i = 0; i < allAccounts.length; i++) {
  13917. if (allAccounts[i].webType === this.currentSong.type) {
  13918. foundAccount = allAccounts[i];
  13919. break;
  13920. }
  13921. }
  13922. if (foundAccount && foundAccount.id) {
  13923. Logger.info(TAG, `playPrevious: 找到同类型账号,更新webdav_account_id: ${this.currentSong.webdav_account_id} -> ${foundAccount.id}`);
  13924. this.currentSong.webdav_account_id = foundAccount.id.toString();
  13925. // 更新数据库记录
  13926. await this.table.updateWebDavAccountId(this.currentSong.filePath, foundAccount.id.toString());
  13927. } else {
  13928. Logger.error(TAG, `playPrevious: 无法找到类型为${this.currentSong.type}的账号,跳过此歌曲`);
  13929. // 跳过无效账号的歌曲,继续查找上一首
  13930. if (this.curIndex == 0) {
  13931. this.curIndex = this.songList.length - 1;
  13932. } else {
  13933. this.curIndex--;
  13934. }
  13935. this.currentSong = this.songList[this.curIndex];
  13936. }
  13937. }
  13938. }
  13939. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13940. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13941. context: this.context,
  13942. autoParseMusicName: this.autoParseMusicName
  13943. });
  13944. this.name = this.songList[this.curIndex].name
  13945. this.artist = this.songList[this.curIndex].artist
  13946. // 如果是投播模式,使用 CastController 切换上一首
  13947. if (this.castControllerWrapper) {
  13948. Logger.info('heanup playPrevious', '投播模式播放上一首,不调用本地stop()');
  13949. try {
  13950. const prevDuration = this.getSongDurationMs(this.currentSong);
  13951. if (prevDuration > 0) {
  13952. this.duration = prevDuration;
  13953. this.durationTime = Math.floor(prevDuration / 1000);
  13954. this.durationStringTime = secondToTime(this.durationTime);
  13955. this.totalTime = this.stringForTime(prevDuration);
  13956. this.avSessionController.setAVMetadataMusic(this.currentSong, prevDuration, this.lyricContent);
  13957. }
  13958. this.updateCastProgress(0);
  13959. await this.castControllerWrapper.playPrevious(this.songList, this.curIndex, this.videoUrl, prevDuration);
  13960. this.isCastPlaying = this.castControllerWrapper.getIsCastPlaying();
  13961. } catch (error) {
  13962. Logger.error('heanup playPrevious', `CastController 播放上一首失败: ${error}`);
  13963. this.isCastPlaying = false;
  13964. }
  13965. this.cover = this.songList[this.curIndex].pixelMapPath;
  13966. return;
  13967. }
  13968. // 本地播放器模式,需要先stop
  13969. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13970. this.stop();
  13971. this.changeImageAnimation()
  13972. }
  13973. //随机播放模式下点击上一首: 播放刚刚播放过的那一首
  13974. private async randomModePlayFromHistory() {
  13975. if (this.randomPlayHistory.length >= 1) {
  13976. // 播放历史栈的第一首(刚刚播放过的)
  13977. const prevSong = this.randomPlayHistory[0];
  13978. Logger.info('heanup randomModePlayFromHistory', `从随机播放历史栈获取歌曲: ${prevSong.name}, type: ${prevSong.type}, 栈大小: ${this.randomPlayHistory.length}`);
  13979. // 从栈中移除这首歌(因为即将播放它,它应该成为当前歌,而不是历史)
  13980. this.randomPlayHistory.shift();
  13981. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  13982. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13983. this.stop();
  13984. // 验证并修正webdav_account_id(针对远程类型歌曲)
  13985. if (isRemoteCloudType(prevSong.type) && prevSong.webdav_account_id) {
  13986. const manager = RemoteDriveManager.getInstance();
  13987. const account = await manager.getWebDavAccountById(prevSong.webdav_account_id);
  13988. if (!account) {
  13989. Logger.warn(TAG, `randomModePlayFromHistory: 歌曲账号ID无效: ${prevSong.webdav_account_id}, 尝试查找同类型账号`);
  13990. const allAccounts = manager.getAllWebDavAccounts();
  13991. let foundAccount: WebDavAccount | null = null;
  13992. for (let i = 0; i < allAccounts.length; i++) {
  13993. if (allAccounts[i].webType === prevSong.type) {
  13994. foundAccount = allAccounts[i];
  13995. break;
  13996. }
  13997. }
  13998. if (foundAccount && foundAccount.id) {
  13999. Logger.info(TAG, `randomModePlayFromHistory: 找到同类型账号,更新webdav_account_id: ${prevSong.webdav_account_id} -> ${foundAccount.id}`);
  14000. prevSong.webdav_account_id = foundAccount.id.toString();
  14001. await this.table.updateWebDavAccountId(prevSong.filePath, foundAccount.id.toString());
  14002. } else {
  14003. Logger.error(TAG, `randomModePlayFromHistory: 无法找到类型为${prevSong.type}的账号`);
  14004. // 无法播放这首歌,继续尝试下一首历史记录
  14005. if (this.randomPlayHistory.length >= 1) {
  14006. this.randomModePlayFromHistory();
  14007. return;
  14008. } else {
  14009. // 历史记录为空,无法继续
  14010. ToastUtil.showToast('没有更多历史记录');
  14011. return;
  14012. }
  14013. }
  14014. }
  14015. }
  14016. this.currentSong = prevSong;
  14017. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  14018. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  14019. context: this.context,
  14020. autoParseMusicName: this.autoParseMusicName
  14021. });
  14022. this.cover = this.currentSong.pixelMapPath
  14023. this.artist = this.currentSong.artist
  14024. this.name = this.currentSong.name;
  14025. console.info('onecold startPlayOrResumePlay randomModePlayFromHistory')
  14026. this.startPlayOrResumePlay();
  14027. } else {
  14028. ToastUtil.showToast('随机播放模式暂无历史记录');
  14029. }
  14030. }
  14031. debounce() {
  14032. const delay = 600;
  14033. let cur = new Date().getTime();
  14034. if (cur - this.last > delay) {
  14035. this.last = cur;
  14036. return true;
  14037. }
  14038. return false;
  14039. }
  14040. /**
  14041. * Sets whether the screen is a constant based on the playback status.
  14042. */
  14043. watchStatus() {
  14044. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  14045. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  14046. this.windowClass.setWindowKeepScreenOn(true);
  14047. } else {
  14048. this.windowClass.setWindowKeepScreenOn(false);
  14049. }
  14050. }
  14051. /**
  14052. * Volume gesture method onActionStart.
  14053. *
  14054. * @param event Gesture event.
  14055. */
  14056. private customDialogComponentIdMM: number = 0
  14057. @Builder
  14058. customDialogComponentMM() {
  14059. Column() {
  14060. Row() {
  14061. Blank()
  14062. Text('验证密码')
  14063. .fontSize(22)
  14064. .fontColor($r('app.color.pri_bg'))
  14065. .margin({ top: 18 })
  14066. Blank()
  14067. Image($r('app.media.close'))
  14068. .fillColor(Color.White)
  14069. .margin({ top: 18, right: 18 })
  14070. .width(20)
  14071. .onClick(() => {
  14072. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  14073. })
  14074. }
  14075. .width('100%') // 使Row占据整个宽度
  14076. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  14077. Verify({
  14078. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  14079. });
  14080. }.height('60%')
  14081. .backgroundColor($r('app.color.index_background'))
  14082. .justifyContent(FlexAlign.SpaceBetween)
  14083. }
  14084. private handleVerifyCompleted(isSuccess: boolean) {
  14085. if (isSuccess) {
  14086. console.log('验证成功');
  14087. // 在这里处理验证成功后的逻辑
  14088. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  14089. this.currentPath = this.lockPath
  14090. this.getSortedFiles(this.currentPath)
  14091. } else {
  14092. // console.log('验证失败');
  14093. ToastUtil.showToast('验证失败')
  14094. }
  14095. }
  14096. private showVerifyDialog() {
  14097. promptAction.openCustomDialog({
  14098. transition: TransitionEffect.asymmetric(
  14099. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  14100. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  14101. ,
  14102. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  14103. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  14104. ),
  14105. builder: () => {
  14106. this.customDialogComponentMM()
  14107. },
  14108. isModal: true,
  14109. autoCancel: true,
  14110. maskColor: Color.Transparent,
  14111. alignment: DialogAlignment.Bottom,
  14112. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  14113. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  14114. console.log("dialog onWillDismiss")
  14115. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  14116. dismissDialogAction.dismiss()
  14117. }
  14118. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  14119. dismissDialogAction.dismiss()
  14120. }
  14121. }
  14122. }).then((dialogId: number) => {
  14123. this.customDialogComponentIdMM = dialogId
  14124. })
  14125. }
  14126. //左滑操作 移动文件 重命名 删除等操作
  14127. @Builder
  14128. DeleteButton(item: VideoItem, index: number, filePath: string) {
  14129. Row() {
  14130. //加入收藏
  14131. Button() {
  14132. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  14133. .fillColor(Color.White)
  14134. .width(20)
  14135. }
  14136. .width(40)
  14137. .height(40)
  14138. .type(ButtonType.Circle)
  14139. .backgroundColor(this.themeColor)
  14140. .margin(5)
  14141. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  14142. .onClick(() => {
  14143. if (item) {
  14144. this.doFav(item)
  14145. }
  14146. })
  14147. //加入下一首播放
  14148. Button() {
  14149. Image($r('app.media.next_to_play'))
  14150. .fillColor(Color.White)
  14151. .width(20)
  14152. }
  14153. .width(40)
  14154. .height(40)
  14155. .type(ButtonType.Circle)
  14156. .backgroundColor(this.themeColor)
  14157. .margin(5)
  14158. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  14159. .onClick(() => {
  14160. this.addToNextPlay(item);
  14161. })
  14162. //复制文件
  14163. Button() {
  14164. Image($r('app.media.copy'))
  14165. .fillColor(Color.White)
  14166. .width(20)
  14167. }
  14168. .width(40)
  14169. .height(40)
  14170. .type(ButtonType.Circle)
  14171. .backgroundColor(this.themeColor)
  14172. .margin(5)
  14173. .id(filePath + 'copy')
  14174. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  14175. .onClick(() => {
  14176. this.showCopyDialog(false, item, index, filePath + 'copy');
  14177. })
  14178. //移动文件
  14179. Button() {
  14180. Image($r('app.media.cut'))
  14181. .fillColor(Color.White)
  14182. .width(20)
  14183. }
  14184. .width(40)
  14185. .height(40)
  14186. .type(ButtonType.Circle)
  14187. .backgroundColor(this.themeColor)
  14188. .margin(5)
  14189. .id(filePath)
  14190. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  14191. .onClick(() => {
  14192. this.showCutDialog(false, item, index, filePath);
  14193. })
  14194. Button() {
  14195. Image($r('app.media.cut_current'))
  14196. .fillColor(Color.White)
  14197. .width(20)
  14198. }
  14199. .width(40)
  14200. .height(40)
  14201. .type(ButtonType.Circle)
  14202. .backgroundColor(this.themeColor)
  14203. .margin(5)
  14204. .id(filePath + 'current')
  14205. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  14206. (this.isHasDir ? Visibility.Visible : Visibility.None))
  14207. .onClick(() => {
  14208. this.showCutDialog(true, item, index, filePath + 'current');
  14209. })
  14210. //重命名
  14211. Button() {
  14212. Image($r('app.media.rename2'))
  14213. .fillColor(Color.White)
  14214. .width(20)
  14215. }
  14216. .width(40)
  14217. .height(40)
  14218. .type(ButtonType.Circle)
  14219. .backgroundColor(this.themeColor)
  14220. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  14221. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  14222. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  14223. .margin(5)
  14224. .onClick(() => {
  14225. this.showReNameDialog(item, index + '', filePath)
  14226. })
  14227. Button() {
  14228. Image($r('app.media.delete2'))
  14229. .fillColor(Color.White)
  14230. .width(20)
  14231. }
  14232. .width(40)
  14233. .height(40)
  14234. .type(ButtonType.Circle)
  14235. .backgroundColor(this.themeColor)
  14236. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  14237. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  14238. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  14239. .margin(5)
  14240. .onClick(() => {
  14241. this.selectedFiles.push(item)
  14242. this.showWarnIsDelete()
  14243. // this.showWarnIsDeleteFile(item, index + '', filePath)
  14244. })
  14245. Button() {
  14246. Image($r('app.media.share2'))
  14247. .fillColor(Color.White)
  14248. .width(20)
  14249. }
  14250. .width(40)
  14251. .height(40)
  14252. .type(ButtonType.Circle)
  14253. .backgroundColor(this.themeColor)
  14254. .margin(5)
  14255. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  14256. .onClick(() => {
  14257. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  14258. })
  14259. }
  14260. }
  14261. /**
  14262. * 穿山甲banner广告
  14263. */
  14264. // private declare bannerAd: CSJNativeExpressAd;
  14265. // @State private status: string = "未加载"
  14266. // @State private isShowAd: boolean = false
  14267. // private declare mAdSlot: AdSlot;
  14268. // private mBiddingAdm = '' //服务端bidding才需要设置
  14269. // private expressLoadAdListener: NativeExpressAdListener = {
  14270. // /**
  14271. // * 加载失败的回调
  14272. // *
  14273. // * @param code
  14274. // * @param message
  14275. // */
  14276. // onError: (code: number, message: string) => {
  14277. // console.error("加载广告失败,code=" + code + ",message=" + message);
  14278. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  14279. // },
  14280. //
  14281. // /**
  14282. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  14283. // *
  14284. // * @param ads 返回的广告列表
  14285. // */
  14286. //
  14287. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  14288. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  14289. // if (ads && ads.length > 0) {
  14290. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  14291. // ad.setExpressInteractionListener({
  14292. // /**
  14293. // *广告的点击回调
  14294. // * @param type 广告的交互类型
  14295. // */
  14296. // onAdClicked: (type: number) => {
  14297. // console.log("BannerExpressAdPage==onAdClicked......");
  14298. // },
  14299. //
  14300. // /**
  14301. // * 广告的展示回调 每个广告仅回调一次
  14302. // * @param type 广告的交互类型
  14303. // */
  14304. // onAdShow: (type: number) => {
  14305. // console.log("BannerExpressAdPage==onAdShow......");
  14306. // },
  14307. //
  14308. // /**
  14309. // * 模板渲染失败
  14310. // */
  14311. // onRenderFail: (code: number, msg: string) => {
  14312. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  14313. // },
  14314. //
  14315. // /**
  14316. // * 模板渲染成功
  14317. // * @param width 返回view的宽 单位 vp
  14318. // * @param height 返回view的高 单位 vp
  14319. // */
  14320. // onRenderSuccess: (width: number, height: number) => {
  14321. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  14322. // this.bannerAd = ad;
  14323. // this.status = "广告加载完成待展示";
  14324. //
  14325. // this.showBannerAd()
  14326. // }
  14327. // })
  14328. // //渲染广告
  14329. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  14330. // this.setDislikeCallback(ad); //设置dislike
  14331. // ad.render(this.getUIContext())
  14332. // this.status = "广告加载中...";
  14333. // });
  14334. // }
  14335. // }
  14336. // }
  14337. //
  14338. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  14339. // ad.setDislikeCallback({
  14340. // /**
  14341. // * dislike show
  14342. // */
  14343. // onShow: () => {
  14344. // console.log("BannerExpressAdPage==dislike......show");
  14345. // },
  14346. //
  14347. // /**
  14348. // * @param position 选择的位置
  14349. // * @param value 选择的内容
  14350. // * @param enforceRemove 是否强制关闭广告
  14351. // */
  14352. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  14353. // this.isShowAd = false;
  14354. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  14355. // ",enforce=" + enforceRemove);
  14356. // },
  14357. //
  14358. // /**
  14359. // * 点击取消
  14360. // */
  14361. // onCancel: () => {
  14362. // console.log("BannerExpressAdPage==dislike......onCancel");
  14363. // }
  14364. //
  14365. // })
  14366. // }
  14367. /**
  14368. * 加载Banner广告
  14369. */
  14370. loadBannerAd(rit: string) {
  14371. // if (Utility.isNoble()) {
  14372. // return
  14373. // }
  14374. // if (!Utility.isPassInstallTime(2)) {
  14375. // return
  14376. // }
  14377. // this.isShowAd = false;
  14378. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  14379. // this.mAdSlot = new AdSlotBuilder()
  14380. // .setCodeId(rit)
  14381. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  14382. // .setAdCount(1)
  14383. // .setBidAdm(this.mBiddingAdm)
  14384. // .build()
  14385. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  14386. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  14387. // this.status = "广告加载中..."
  14388. }
  14389. /**
  14390. * 展示Banner广告
  14391. */
  14392. // showBannerAd() {
  14393. // if (!this.bannerAd) {
  14394. // return
  14395. // }
  14396. // this.isShowAd = true
  14397. // this.status = "已展示"
  14398. // }
  14399. /**
  14400. * 穿山甲广告代码结束
  14401. */
  14402. /**
  14403. * 处理歌单播放请求
  14404. */
  14405. private async handlePlaylistPlayRequest(playlistId: string, playlistName:
  14406. string, songFilePaths: string[], startIndex: number,isJump: boolean) {
  14407. try {
  14408. Logger.info(`heanup 处理歌单播放请求: ${playlistName}, 歌曲数量: ${songFilePaths.length}, 开始索引: ${startIndex}`)
  14409. // 检查是否为WebDAV播放请求
  14410. if (playlistId === 'webdav-playlist') {
  14411. Logger.info(`heanup 检测到WebDAV播放请求,从内存读取videoItems`)
  14412. // 从全局内存读取videoItems数据
  14413. const videoItems = getWebdavVideoItems();
  14414. const currentPlayIndex = getWebdavCurrentPlayIndex();
  14415. Logger.info(`heanup 从内存读取到WebDAV歌曲列表,长度:${videoItems.length},索引:${currentPlayIndex}`)
  14416. if (videoItems && videoItems.length > 0) {
  14417. // 验证webdav_account_id设置情况
  14418. const accountIds = videoItems.map(item => item.webdav_account_id).filter(id => id);
  14419. Logger.info(`heanup 有 ${accountIds.length}/${videoItems.length} 首歌曲设置了webdav_account_id`)
  14420. if(isJump){
  14421. this.setShowPlayTrue()//显示播放页
  14422. }
  14423. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName)
  14424. return
  14425. } else {
  14426. return
  14427. }
  14428. }
  14429. if (playlistId === 'navidrome-playlist') {
  14430. Logger.info(`heanup 检测到Navidrome播放请求,从内存读取videoItems`);
  14431. const videoItems = getNavidromeVideoItems();
  14432. const currentPlayIndex = getNavidromeCurrentPlayIndex();
  14433. Logger.info(`heanup Navidrome歌曲列表长度: ${videoItems.length}`);
  14434. if (videoItems && videoItems.length > 0) {
  14435. if(isJump){
  14436. this.setShowPlayTrue()//显示播放页
  14437. }
  14438. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName);
  14439. return;
  14440. } else {
  14441. Logger.warn('heanup Navidrome播放请求缺少歌曲数据');
  14442. return;
  14443. }
  14444. }
  14445. // 从数据库重新加载这些歌曲,使用索引记录位置以保持顺序
  14446. const songMap: Map<number, VideoItem> = new Map()
  14447. let completedQueries = 0
  14448. Logger.info(`heanup 开始从数据库查询 ${songFilePaths.length} 首歌曲`)
  14449. // 遍历所有文件路径,使用索引记录位置
  14450. for (let i = 0; i < songFilePaths.length; i++) {
  14451. const filePath = songFilePaths[i]
  14452. const index = i
  14453. // Logger.info(`heanup 正在查询歌曲[${index}]: ${filePath}`)
  14454. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  14455. const queryPromise = this.table.queryVideoByFilePath(filePath)
  14456. // Logger.info(`heanup 创建了查询Promise,开始等待结果[${index}]: ${filePath}`)
  14457. queryPromise.then((videoItem) => {
  14458. completedQueries++
  14459. // Logger.info(`heanup 查询Promise返回结果[${index}]: ${filePath}, 找到歌曲: ${videoItem ? videoItem.name : 'null'}`)
  14460. if (videoItem) {
  14461. // 使用索引作为key保存到Map中,保持原始顺序
  14462. songMap.set(index, videoItem)
  14463. // Logger.info(`heanup 从数据库找到歌曲[${index}]: ${videoItem.name} (${completedQueries}/${songFilePaths.length})`)
  14464. } else {
  14465. Logger.warn(`heanup 数据库中未找到歌曲[${index}]: ${filePath} (${completedQueries}/${songFilePaths.length})`)
  14466. }
  14467. // 检查是否所有歌曲都已加载完成
  14468. if (completedQueries === songFilePaths.length) {
  14469. // Logger.info(`heanup 所有数据库查询完成,共找到 ${songMap.size} 首歌曲`)
  14470. // 按照索引顺序重建歌曲数组
  14471. const songs: VideoItem[] = []
  14472. for (let j = 0; j < songFilePaths.length; j++) {
  14473. const song = songMap.get(j)
  14474. if (song) {
  14475. songs.push(song)
  14476. // Logger.info(`heanup 按顺序添加歌曲[${j}]: ${song.name}`)
  14477. }
  14478. }
  14479. Logger.info(`heanup 最终歌曲列表顺序: ${songs.map((s, idx) => `[${idx}]${s.name}`).join(', ')}`)
  14480. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  14481. }
  14482. }).catch((error: Error) => {
  14483. completedQueries++
  14484. Logger.error(`heanup 查询歌曲失败[${index}]: ${filePath}, 错误: ${error.message} (${completedQueries}/${songFilePaths.length})`)
  14485. // 即使出错也要检查是否完成所有查询
  14486. if (completedQueries === songFilePaths.length) {
  14487. Logger.info(`heanup 所有数据库查询完成(包含错误),共找到 ${songMap.size} 首歌曲`)
  14488. // 按照索引顺序重建歌曲数组
  14489. const songs: VideoItem[] = []
  14490. for (let j = 0; j < songFilePaths.length; j++) {
  14491. const song = songMap.get(j)
  14492. if (song) {
  14493. songs.push(song)
  14494. }
  14495. }
  14496. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  14497. }
  14498. })
  14499. }
  14500. } catch (error) {
  14501. Logger.error('heanup 处理简化歌单播放请求失败: ' + error)
  14502. ToastUtil.showToast('播放失败')
  14503. }
  14504. }
  14505. /**
  14506. * 完成歌单加载并开始播放
  14507. */
  14508. private finishLoadingPlaylist(songs: VideoItem[], startIndex: number, playlistName: string) {
  14509. if (songs.length === 0) {
  14510. Logger.error('heanup 没有找到任何可播放的歌曲')
  14511. ToastUtil.showToast('没有找到可播放的歌曲')
  14512. return
  14513. }
  14514. this.songList = songs
  14515. this.sonDataSource.pushArrayData(songs)
  14516. this.sonDataSource.notifyDataReload()
  14517. this.curIndex = startIndex
  14518. if (songs[startIndex]) {
  14519. // 确保当前播放的歌曲也更新到存储
  14520. AppStorage.setOrCreate('currentSong', songs[startIndex])
  14521. // 设置isFromSonPlayList=true,避免doPlay方法重新从全局列表构建播放列表
  14522. this.doPlay(songs[startIndex], startIndex, true)
  14523. }
  14524. PreferencesUtil.putSync('LastMusicList', this.songList)
  14525. // ToastUtil.showToast(`开始播放歌单: ${playlistName}`)
  14526. }
  14527. }
  14528. //视频气泡窗口的布局
  14529. @Builder
  14530. function customPopupBuilder(dataBu: BubbleBean) {
  14531. List() {
  14532. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  14533. ListItem() {
  14534. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  14535. Row() {
  14536. Column() {
  14537. Image(dataBu.imageRes[index])
  14538. .height(28)
  14539. .fillColor(dataBu.color)
  14540. .alignSelf(ItemAlign.Center)
  14541. }
  14542. .width(32)
  14543. Text(item)
  14544. .padding({
  14545. top: 10,
  14546. bottom: 10,
  14547. right: 10,
  14548. left: 10
  14549. })
  14550. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  14551. .textAlign(TextAlign.Start)
  14552. .width("100%")
  14553. }
  14554. }
  14555. .backgroundColor($r('app.color.settings_background_main'))
  14556. .margin({ top: 6, bottom: 6 })
  14557. }
  14558. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  14559. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  14560. TransitionEffect.scale({ x: 0, y: 0 })))
  14561. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  14562. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  14563. .onClick(() => {
  14564. dataBu.onItemClick?.(index)
  14565. })
  14566. })
  14567. }
  14568. .scrollBar(BarState.Off)
  14569. .width(120)
  14570. .divider({
  14571. strokeWidth: 1,
  14572. color: "#22FFFFFF"
  14573. })
  14574. }
  14575. // Function to calculate a hash for the file list
  14576. function simpleHash(fileList: string[]): string {
  14577. let hash = 0;
  14578. const str = fileList.join(',');
  14579. for (let i = 0; i < str.length; i++) {
  14580. const char = str.charCodeAt(i);
  14581. hash = (hash << 5) - hash + char;
  14582. hash |= 0; // Convert to 32bit integer
  14583. }
  14584. return hash.toString();
  14585. }
  14586. interface MoreItem {
  14587. id: number;
  14588. image: Resource;
  14589. title: string;
  14590. }
  14591. //视频气泡窗口的布局
  14592. @Builder
  14593. function cutPopupBuilder(dataBu: BubbleBean) {
  14594. Column() {
  14595. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  14596. .padding({
  14597. top: 10,
  14598. bottom: 10,
  14599. right: 10,
  14600. left: 10
  14601. })
  14602. .textAlign(TextAlign.Start)
  14603. .width(160)
  14604. .fontWeight(666)
  14605. .fontSize(16)
  14606. List() {
  14607. ForEach(dataBu.data, (item: string, index: number) => {
  14608. ListItem() {
  14609. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  14610. Row() {
  14611. Column() {
  14612. Image($r('app.media.music_group'))
  14613. .height(28)
  14614. .fillColor(dataBu.color)
  14615. .alignSelf(ItemAlign.Center)
  14616. }
  14617. .width(32)
  14618. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  14619. .padding({
  14620. top: 10,
  14621. bottom: 10,
  14622. right: 10,
  14623. left: 10
  14624. })
  14625. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  14626. .fontSize(15)
  14627. }
  14628. }
  14629. .backgroundColor(Color.Transparent)
  14630. .margin({ top: 7, bottom: 7 })
  14631. }
  14632. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  14633. .animation({ duration: 500 }),
  14634. TransitionEffect.scale({ x: 0, y: 0 })))
  14635. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  14636. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  14637. .onClick(() => {
  14638. dataBu.onItemClick?.(index)
  14639. })
  14640. })
  14641. }
  14642. .scrollBar(BarState.Off)
  14643. .width(150)
  14644. .divider({
  14645. strokeWidth: 1,
  14646. color: "#22FFFFFF"
  14647. })
  14648. }
  14649. .height(300)
  14650. .padding({
  14651. bottom: 30
  14652. })
  14653. }
  14654. function getFileDirName(filePath: string,rootPath:string): string{
  14655. if(filePath===rootPath){
  14656. return '首页'
  14657. }
  14658. let result = FileUtil.getFileName(filePath)
  14659. if(StrUtil.isEmpty(result))
  14660. return ''
  14661. if(result.startsWith('.'))
  14662. result = result.replace(/\./g, '')
  14663. return result
  14664. }
  14665. //只扫描当前目录下文件(不扫描子文件夹)的方法
  14666. @Concurrent
  14667. async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
  14668. const table: MediaTable = new MediaTable(context);
  14669. try {
  14670. // 直接获取当前目录下的文件列表
  14671. const files = FileUtil.listFileSync(dirPath);
  14672. await Promise.all(files.map(async (file) => {
  14673. const fPath = `${dirPath}/${file}`;
  14674. // 跳过目录,只处理文件
  14675. if (FileUtil.isDirectory(fPath)) {
  14676. return;
  14677. }
  14678. // 跳过特定格式文件
  14679. if (fPath.endsWith('.lrc') || fPath.endsWith('.srt')) {
  14680. return;
  14681. }
  14682. // 检查是否为媒体文件
  14683. if (Utility.isMeidaByExtension(fPath)) {
  14684. let mType = CommonConstants.TYPE_LOCAL;
  14685. if (fPath.includes(lockPath)) {
  14686. mType = CommonConstants.TYPE_LOCK;
  14687. }
  14688. const mediaItem = await Utility.uriGetMusicAssetsFromFile(
  14689. context, fPath, mType, true
  14690. );
  14691. table.insert(mediaItem, (id: number) => {
  14692. // 插入回调函数
  14693. }, cover_api);
  14694. }
  14695. }));
  14696. } catch (error) {
  14697. console.error(' 扫描当前目录失败:', error);
  14698. }
  14699. }
  14700. //内嵌标签后更新库
  14701. @Concurrent
  14702. async function updateInfoDb(
  14703. context: Context,
  14704. filePath: string,
  14705. titleStr: string,
  14706. artistStr: string,
  14707. albumStr: string,
  14708. lyricConStr: string,
  14709. yearStr: string,
  14710. genreStr: string,
  14711. trackStr: string,
  14712. albumArtistStr: string,
  14713. composerStr: string,
  14714. lyricistStr: string,
  14715. commentStr: string,
  14716. discStr: string,
  14717. ): Promise<boolean> {
  14718. const table: MediaTable = new MediaTable(context);
  14719. await new Promise<void>((resolve, reject) => {
  14720. table.getRdbStore(context, (err:Error) => {
  14721. err ? reject(err) : resolve();
  14722. });
  14723. });
  14724. return await new Promise<boolean>((resolve) => {
  14725. table.updateMediaInfo(filePath, titleStr, artistStr, albumStr, lyricConStr,
  14726. yearStr, genreStr, trackStr, albumArtistStr, composerStr, lyricistStr, commentStr, discStr,
  14727. (success: boolean, error?: string) => {
  14728. if (success) {
  14729. console.log("onecold 编辑信息成功,数据库已同步");
  14730. } else {
  14731. console.error("onecold 编辑信息数据库失败原因: " + error);
  14732. }
  14733. resolve(success);
  14734. });
  14735. });
  14736. }