LocalMusic.ets 535 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449
  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 { repairAudioMetadata, convertDsfToWav, getApiLyric,changeMusicCover} from '../common/util/MusicTagUtils';
  52. import { extractHwMediaMetadata, FFMpegTags,Utility } from '../common/util/Utility';
  53. import { TagsContentCover } from '../view/TagsContentCover';
  54. import {
  55. DeviceChangeReason,
  56. IjkMediaPlayer,
  57. InterruptEvent,
  58. InterruptHintType,
  59. LogUtils,
  60. OnBufferingUpdateListener,
  61. OnCompletionListener,
  62. OnErrorListener,
  63. OnInfoListener,
  64. OnPreparedListener,
  65. OnSeekCompleteListener,
  66. OnTimedTextListener,
  67. OnVideoSizeChangedListener
  68. } from '@ohos/ijkplayer';
  69. import { PlayStatus } from '../common/PlayStatus';
  70. import fs from '@ohos.file.fs';
  71. import { image } from '@kit.ImageKit';
  72. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  73. import { UniversalDetector } from '@ohos/juniversalchardet';
  74. import { SettingPage } from '../pages/SettingPage';
  75. import { secondToTime,getTransverterText } from '../common/util/CommUtils';
  76. import { CommonConstants2 } from '../common/util/CommonConstants2';
  77. import { hilog } from '@kit.PerformanceAnalysisKit';
  78. import { LazyDataSource } from '../common/util/LazyDataSource';
  79. import MediaTable, { PageQueryOptions, PageQueryResult } from '../common/util/MediaTable';
  80. import FileDeletionWatcher from '../common/util/FileDeletionWatcher';
  81. import LyricUtil from '../common/util/LyricUtil';
  82. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  83. import { ringtone } from '@kit.RingtoneKit';
  84. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  85. import { resourceManager } from '@kit.LocalizationKit';
  86. import { deviceInfo } from '@kit.BasicServicesKit';
  87. import '../common/network/RemoteCacheRegistry';
  88. import { ServerLogUtil } from '../common/util/ServerLogUtil';
  89. import { lyricService, SongData } from '../common/service/LyricService';
  90. import {
  91. cloneVideoItem,
  92. preloadNextSongIfNeeded,
  93. setVideoUrlForSong,
  94. getTypeOrder,
  95. isWebDavType,
  96. isSmbType,
  97. isNavidromeType,
  98. isFtpType,
  99. isBaiduType,
  100. isJellyfinType,
  101. isEmbyType,
  102. isRemoteCloudType,
  103. WorkerEditMusicResult,
  104. WebDavMetadataUpdatePayload
  105. } from '../common/util/RemotePlayerUtil';
  106. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  107. import app from '@system.app';
  108. import { TextNodeController } from './PipLyricTextBuilder';
  109. import { IndexerView } from './IndexerView';
  110. import { KeyCode } from '@kit.InputKit';
  111. import { KnockController } from '../controller/KnockController';
  112. import { DeleteComptent } from '../view/DeleteComptent';
  113. import { ABLoopComptent } from '../view/ABLoopComptent';
  114. import { FixMessyView } from '../view/FixMessyView';
  115. import { parseCueFile,CueTrack,CueInfo } from '../common/util/CueUtils';
  116. import { CueComptent } from '../view/CueComptent';
  117. import PlaylistTable from '../common/util/PlaylistTable';
  118. import { showAddToPlaylistDialog } from '../dialog/AddToPlaylistDialog';
  119. import { showCreatePlaylistDialog } from '../dialog/PlaylistDialog';
  120. import { convertPlaylistSongsToVideoItems, emptyView,updateAllSongsSortOrder } from '../pages/PlaylistDetailPage';
  121. import { Playlist, PlaylistSong } from '../viewmodel/Playlist';
  122. import { Song } from '../viewmodel/Song';
  123. import { SongType } from '../common/enums/SongType';
  124. import { RemoteDriveManager, WebDavAuthInfo as WebDavManagerAuthInfo,
  125. buildHttpHeadersWithWebDav,
  126. WebDavAuthItem} from '../common/util/RemoteDriveManager';
  127. import PermissionUtil from '../common/util/PermissionUtil'
  128. import { EditAudio, setRingTone } from './EditAudio';
  129. import { ExtractAccompaniment } from './ExtractAccompaniment';
  130. import { ExtractAudioFromVideo } from './ExtractAudioFromVideo';
  131. import { AudioFormatConverter } from './AudioFormatConverter';
  132. import { MergeAudio } from './MergeAudio';
  133. import { AIVoiceSeparation } from './AIVoiceSeparation';
  134. import { WebDavUrlUtil } from '../common/util/WebDavUrlUtil';
  135. import { ChangeTone } from './ChangeTone';
  136. import {
  137. hdsEffect,
  138. HdsVisualComponent,
  139. HdsSceneController,
  140. HdsSceneType,
  141. HdsVisualComponentAttribute,
  142. } from '@kit.UIDesignKit';
  143. import { GlobalAlphabetIndexerModifier } from '../Styels/GlobalStyles'
  144. import { getFirstLetter } from '../Constants';
  145. import { audio } from '@kit.AudioKit';
  146. const TAG = 'LocalMusic';
  147. const HICAR_LOG_TAG = 'HiCarWindow';
  148. function logHiCarWindow(message: string): void {
  149. void ServerLogUtil.info(HICAR_LOG_TAG, message);
  150. }
  151. export interface WorkerMetadataPayload {
  152. originFilePath: string;
  153. originId?: string;
  154. bit_rate?: string;
  155. duration?: string;
  156. sampleRate?: string;
  157. mimeType?: string;
  158. md5Str?: string;
  159. videoSize?: number;
  160. size?: string;
  161. pixelMapPath?: string;
  162. artist?: string;
  163. album?: string;
  164. name?: string;
  165. lyricContent?: string;
  166. bits_per_raw_sample?: string;
  167. channels?: string;
  168. channel_layout?: string;
  169. start_time?: string;
  170. genre?: string;
  171. year?: string;
  172. probe_score?: number;
  173. track?: string;
  174. disc?: string;
  175. ALBUMARTIST?: string;
  176. COMPOSER?: string;
  177. COMMENT?: string;
  178. LYRICIST?: string;
  179. nb_streams?: number;
  180. nb_programs?: number;
  181. error?: string;
  182. }
  183. interface WorkerMessageScanDone {
  184. code: 101;
  185. data: Record<string, never>;
  186. }
  187. interface WorkerMessageMediaList {
  188. code: 102;
  189. data: Array<VideoItem>;
  190. totalCount: number;
  191. }
  192. interface WorkerMessageArtistList {
  193. code: 103;
  194. data1: Map<string, Array<VideoItem>>;
  195. data2: Array<VideoItem>;
  196. totalCount: number;
  197. }
  198. interface WorkerMessageAlbumList {
  199. code: 104;
  200. data1: Map<string, Array<VideoItem>>;
  201. data2: Array<VideoItem>;
  202. totalCount: number;
  203. }
  204. interface WorkerMessageMetadata {
  205. code: 105;
  206. data: WorkerMetadataPayload;
  207. }
  208. interface WorkerMessageEditResult {
  209. code: 106;
  210. data: WorkerEditMusicResult;
  211. }
  212. type LocalMusicWorkerMessage =
  213. WorkerMessageScanDone
  214. | WorkerMessageMediaList
  215. | WorkerMessageArtistList
  216. | WorkerMessageAlbumList
  217. | WorkerMessageMetadata
  218. | WorkerMessageEditResult;
  219. /**
  220. * 歌单播放事件数据
  221. */
  222. interface PlaylistEventData {
  223. playlistId: string;
  224. playlistName: string;
  225. songCount: number;
  226. startIndex: number;
  227. songFilePaths: string[];
  228. isJump: boolean;
  229. webDavAuthInfo?: WebDavAuthItem; // 新增WebDAV认证信息
  230. }
  231. const DEFAULT_INDEX =
  232. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  233. 'X', 'Y', 'Z']
  234. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  235. // 元数据提取状态追踪
  236. const metadataExtractionInFlight: Map<string, Promise<void>> = new Map();
  237. // setVideoUrlForSong 函数已移至 MusicPlayerUtil.ets
  238. // 定义接口
  239. interface HiCarAspectRatio {
  240. ratio: number;
  241. name: string;
  242. }
  243. interface GeneratedObjectLiteralInterface_1 {
  244. assetId: string;
  245. title: string;
  246. artist: string;
  247. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  248. mediaUri: string;
  249. // 该字段大写,音频'AUDIO',视频'VIDEO'
  250. mediaType: string;
  251. mediaSize: number;
  252. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  253. startPosition: number;
  254. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  255. duration: number;
  256. albumCoverUri: string;
  257. albumTitle: string;
  258. appName: string;
  259. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  260. drmScheme: string;
  261. }
  262. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  263. const ITEM_HEIGHT: number = 65; // 列表项中高度
  264. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  265. //功能强大的音乐播放器
  266. @Preview
  267. @Component
  268. export struct LocalMusic {
  269. @State isPaging: boolean = true;//是否分页加载机制
  270. @State isCoverRectangle: boolean = true;
  271. @State showZMIndex: boolean = false //是否右侧显示字母索引
  272. private prevOffsetY: number = 0; // 记录上一次的Y轴偏移量
  273. @State autoHideTitle: boolean = true //滚动自动隐藏标题栏
  274. // 字母表
  275. @State alphaBet: string[] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
  276. 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  277. @State alphaBetStyle: GlobalAlphabetIndexerModifier = new GlobalAlphabetIndexerModifier()
  278. @State selectAlphaBetIndex: number = 0
  279. @State isShowAlphaBet: boolean = false
  280. @State isScrolling: boolean = false
  281. @State isTouchingAlphaBet: boolean = false
  282. @State alphabetHeight: number = 0
  283. public enableShowAlphabet: boolean = true // 是否显示字母表
  284. @State isShowPrecious: boolean = false //播控条显示上一首按钮
  285. //背景两侧流光控制器
  286. @State sceneBgController: HdsSceneController|undefined = deviceInfo.sdkApiVersion>=20
  287. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  288. new HdsSceneController()
  289. .setSceneParams({
  290. backgroundMaskColors: [Color.Green, Color.Red],
  291. firstEdgeFlowLight: {
  292. startPos: 0,
  293. endPos: 0.5,
  294. color: Color.Red
  295. },
  296. secondEdgeFlowLight: {
  297. startPos: 0,
  298. endPos: -0.5,
  299. color: Color.Green
  300. }
  301. }) : undefined;
  302. //背景流光控制器
  303. @State bgController: hdsEffect.ShaderEffectController|undefined = deviceInfo.sdkApiVersion>=20
  304. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  305. new hdsEffect.ShaderEffectController():undefined;
  306. @State showAddSheet:boolean = false
  307. private loadingDialogId: string = ''
  308. private loadingProgressDialogId: string = ''
  309. searchController: SearchController = new SearchController()
  310. @State rightTopImage:Resource = $r('sys.symbol.sort')
  311. @State isEditAudio:boolean = false
  312. @State isExtractAcc:boolean = false
  313. @State isConverter:boolean = false
  314. @State isAIVoiceSeparation:boolean = false
  315. @State isExtractAudio:boolean = false
  316. @State isMergeAudio:boolean = false
  317. @State isCopyFileToDownLoad: boolean = false
  318. @State isChangeTone:boolean = false
  319. @State offHeight: number = 75
  320. @State currentSongList: Array<VideoItem> = []//当前歌单
  321. @Consume currentSongListName:string //当前歌单名称
  322. @Consume @Watch('onIDChange') currentSongListID:string //当前歌单ID
  323. @State isRefreshing: boolean = false;
  324. @State maxRefreshingHeight: number = 100.0;
  325. @State isPlayerLoading: boolean = false; // 播放器加载状态
  326. private contentNode?: ComponentContent<Object> = undefined;
  327. // WebDAV相关实例变量(现在改为从内存读取,不再需要存储)
  328. @State ratioL: number = 1;
  329. @State mediaKuCount: number = 0;
  330. @State albumCount: number = 0;
  331. @State artistCount: number = 0;
  332. @State fastForwardSeconds: string = '10'
  333. @State isShowBackFast: boolean = true//快进快退按钮
  334. @State isCanAuto:boolean = true
  335. @State opacityValueImage: number = 1;
  336. @State tipPopup:boolean = false
  337. @State preloadNextSong: boolean = PreferencesUtil.getBooleanSync('preload_next_song', true) // 是否提前缓存下一首
  338. @Consume mType: number;
  339. @StorageProp('themeColor') themeColor: string =
  340. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  341. themeMode: number = 0;
  342. @State titleName: string = '首页'
  343. @State textStr: string = ''
  344. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  345. // private download_path: string = '';
  346. @Consume rootPath: string //音频根目录
  347. @Consume currentPath: string
  348. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  349. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  350. @State lockPath: string = ''
  351. @State favPath: string = ''
  352. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  353. @State historyPath: string = ''
  354. @State historyList: Array<VideoItem> = []
  355. @Consume isHistory: boolean
  356. static readonly HISTORY_MUSIC: string = 'music_historyList';
  357. private table: MediaTable = new MediaTable(getContext(this))
  358. private playlistTable: PlaylistTable | null = null
  359. private deletionWatcher: FileDeletionWatcher | null = null
  360. @State allPlaylists: Playlist[] = []
  361. @State isZero: boolean = false
  362. @State fileList: Array<string> = []
  363. @State dirList: Array<VideoItem> = []
  364. @Consume videoLocalList:VideoItem[]
  365. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  366. @State listRefreshKey: number = 0
  367. // @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  368. @StorageProp('mediaKuList') mediaKuList: Array<VideoItem> = []; //媒体库文件
  369. @State artistList: Array<VideoItem> = []; //艺术家文件
  370. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  371. @State artistSongCountMap: Map<string, number> = new Map();
  372. @State albumList: Array<VideoItem> = []; //专辑文件
  373. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  374. @State albumSongCountMap: Map<string, number> = new Map();
  375. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  376. @State imageOpacities: number[] = [];
  377. @Consume isCanBack: boolean
  378. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  379. @State showSingleLyric: boolean = false
  380. @State sortType: number = 4 //默认排序方式
  381. @State isShowSimi: boolean = false //是否显示私密音频
  382. @State isShowFAV: boolean = true //是否显示我的收藏
  383. @State isShowTitleBar: boolean = true //是否显示分类导航条
  384. @State isShowAllBar: boolean = true //是否显示播放全部条
  385. @State isShowSingleLineLyric: boolean = false //是否显示单行歌词
  386. @State isShowHistory: boolean = true //是否显示最近播放
  387. @State @Watch('onColorModeChange') isCustomizeBg: boolean = false //自定义背景界面
  388. @State isGridMusic: boolean = false //是否网格布局
  389. @State isCircleBtn: boolean = false //是否圆形播放按钮
  390. @State twoFingerType: number = 3 //双支放大缩小的类型
  391. @State isScrollHide: boolean = false //是否滚动隐藏
  392. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  393. @State isStartAutoPlay: boolean = false //启动后自动播放
  394. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  395. @State isShowHeader: boolean = true
  396. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  397. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  398. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  399. @State isSwipe: boolean = false //listItem的左滑开关
  400. @State openSkipSongAnimate: boolean = true//切歌动画效果
  401. @State customizeBgPath: string | undefined = '';
  402. @State isDarkMode: boolean = false
  403. @State lyricTextWeight: number = 400
  404. @State lyricTextWeightPip: number = 400
  405. @State currentSwiperIndex: number = 0
  406. @State blurValue: number = 0 //背景模糊
  407. @State bgBrightness: number = 0 //背景亮度
  408. private listScroller: ListScroller = new ListScroller()
  409. private playListScroller: Scroller = new Scroller()
  410. @State isOneKeyTags:boolean = false
  411. @State isFixMessy:boolean = false
  412. // 分页相关状态
  413. @State private currentPage: number = 0 // 当前页码
  414. @State private pageSize: number = 50 // 每页数量
  415. @State private totalCount: number = 0 // 总记录数
  416. @State private hasMoreData: boolean = true // 是否还有更多数据
  417. @State private isLoadingPage: boolean = false // 是否正在加载分页数据
  418. private pageCache: Map<number, VideoItem[]> = new Map() // 页面缓存(最多保留3页)
  419. private prefetchingPages: Set<number> = new Set()
  420. private playQueueScope: 'view' | 'history' | 'fav' | 'playlist' | 'single' = 'view'
  421. @StorageProp('isLandscape') @Watch('onIsLandscapeChange') isLandscape: boolean = false;
  422. @StorageProp('topSafeHeight') topSafeHeight: number = 0;
  423. @StorageProp('bottomSafeHeight') bottomSafeHeight: number = 0;
  424. @StorageProp('windowWidth') windowWidth: number = 0;
  425. @StorageProp('windowHeight') windowHeight: number = 0;
  426. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  427. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  428. private UNKONWN:string = '';
  429. private listArea: Area = {
  430. width: 0,
  431. height: 0,
  432. position: {},
  433. globalPosition: {}
  434. }
  435. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  436. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  437. // WebDAV认证信息缓存(作为实例变量,比全局上下文更可靠)
  438. private currentWebDavAuthInfo: WebDavAuthItem | null = null;
  439. //瀑布流的列数横竖屏动态切换
  440. onIsLandscapeChange() {
  441. if(this.isLandscape){
  442. this.columns = 4
  443. }else{
  444. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  445. }
  446. }
  447. onColorModeChange() {
  448. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  449. }
  450. //点击某个歌单id发生变化的时候回调
  451. onIDChange(){
  452. console.log('onecold 歌单id发生变化this.currentSongListID='+this.currentSongListID)
  453. console.log('onecold 歌单id发生变化this.currentSongListName='+this.currentSongListName)
  454. if(this.modeType==4){
  455. this.titleName = this.currentSongListName
  456. this.rightTopImage = $r('sys.symbol.sort')
  457. //获取缓存
  458. const cacheSongs:string =PreferencesUtil.getStringSync(this.currentSongListID+'currentSongList', '')
  459. console.log('onecold 歌单id发生变化获取缓存2 cacheSongs = '+cacheSongs)
  460. if(StrUtil.isNotEmpty(cacheSongs)){
  461. this.currentSongList = JSON.parse(cacheSongs) as VideoItem[]
  462. this.updateListData(this.currentSongList, true)
  463. }
  464. this.doSongListTask()//获取歌单信息
  465. }
  466. }
  467. async doSongListTask() {
  468. // 初始化歌单数据库
  469. const playlistTable = new PlaylistTable(this.context);
  470. // 查询歌单中的所有歌曲
  471. const playlistSongs: PlaylistSong[] = await playlistTable.queryPlaylistSongs(this.currentSongListID);
  472. console.log('onecold 歌单id发生变化获取缓存7 playlistSongs='+playlistSongs.length)
  473. if (ArrayUtil.isEmpty(playlistSongs)) {
  474. this.updateListData([], true)
  475. } else {
  476. this.currentSongList = await convertPlaylistSongsToVideoItems(this.context, playlistSongs);
  477. console.log('onecold 从数据库读取的歌曲为 playlistSongs='+this.currentSongList.length)
  478. this.updateListData(this.currentSongList, true)
  479. if (ArrayUtil.isNotEmpty(this.currentSongList)&&this.currentSongList.length > 100) {
  480. // 只保存前100条记录到缓存中
  481. let canceList = this.currentSongList.slice(0, 100);
  482. PreferencesUtil.putSync(this.currentSongListID+'currentSongList',
  483. JSON.stringify(canceList))
  484. } else {
  485. PreferencesUtil.putSync(this.currentSongListID+'currentSongList', JSON.stringify(this.currentSongList));
  486. }
  487. }
  488. this.isRefreshing = false
  489. }
  490. async onModeChange(): Promise<void> {
  491. this.isFavMusic = false
  492. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  493. Logger.info('heanup LocalMusic', `onModeChange: 切换模式 modeType=${this.modeType}`);
  494. // 模式切换时重置分页状态并加载第一页
  495. await this.resetAndLoadFirstPage();
  496. switch (this.modeType) {
  497. case 0:
  498. // 首页模式已在 resetAndLoadFirstPage 中处理
  499. break
  500. case 1:
  501. this.rightTopImage = $r('sys.symbol.sort')
  502. this.titleName = Utility.resourceToString(this.context,$r('app.string.media_ku'))
  503. break
  504. case 2:
  505. this.rightTopImage = $r('sys.symbol.sort')
  506. if (this.sortType === 4) {
  507. this.sortType = 9
  508. PreferencesUtil.putSync(SettingPage.SORT_TYPE, 9)
  509. }
  510. this.titleName = Utility.resourceToString(this.context,$r('app.string.artist'))
  511. break
  512. case 3:
  513. this.rightTopImage = $r('sys.symbol.sort')
  514. if (this.sortType === 4) {
  515. this.sortType = 9
  516. PreferencesUtil.putSync(SettingPage.SORT_TYPE, 9)
  517. }
  518. this.titleName = Utility.resourceToString(this.context,$r('app.string.album'))
  519. break
  520. }
  521. }
  522. // @Consume currentSong: VideoItem | undefined;
  523. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  524. // @StorageLink('isPlay') isPlay: boolean = false;
  525. @Consume isShowPlay: boolean ;
  526. @StorageLink('songList') songList: Array<VideoItem> = [];
  527. @State translateY: number = 0;
  528. @State isShowSheet: boolean = false;
  529. @State isShowSheetView: boolean = false;
  530. @State isShowTimeCloseView: boolean = false;
  531. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  532. @StorageLink('currIndex') curIndex: number = 0;
  533. @Consume isShowDrawer: boolean;
  534. @Consume offsetX: number;
  535. @State isFac: boolean = false;
  536. @State favList: Array<VideoItem> = []
  537. @Consume isFavMusic: boolean
  538. @State isClickedPLayAll: boolean = false;
  539. private scrollerForlist: ListScroller = new ListScroller();
  540. private knockController: KnockController | undefined = undefined;
  541. // 修改为:
  542. imagesF: ImageFrameInfo[] = CommonConstants.IMAGE_FRAME_INFO;
  543. @StorageProp('animationState') animationState: AnimationStatus = AnimationStatus.Initial
  544. // 缓存机制
  545. private cache: Map<string, Array<VideoItem>> = new Map();
  546. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  547. // 持久化缓存
  548. private async saveCacheToStorage() {
  549. const cacheArray = Array.from(this.cache.entries());
  550. const stringCacheArray = Array.from(this.stringCache.entries());
  551. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  552. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  553. }
  554. // 载入缓存
  555. private async loadCacheFromStorage() {
  556. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  557. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  558. if (cacheString) {
  559. const parsedCache: Object | null = JSON.parse(cacheString);
  560. if (parsedCache && Array.isArray(parsedCache)) {
  561. const cacheArray: [string, Array<VideoItem>][] = parsedCache;
  562. this.cache = new Map(cacheArray);
  563. }
  564. }
  565. if (stringCacheString) {
  566. const parsedStringCache: Object | null = JSON.parse(stringCacheString);
  567. if (parsedStringCache && Array.isArray(parsedStringCache)) {
  568. const stringCacheArray: [string, string][] = parsedStringCache;
  569. this.stringCache = new Map(stringCacheArray);
  570. }
  571. }
  572. }
  573. // 查找缓存
  574. private findCache(key: string): Array<VideoItem> | undefined {
  575. return this.cache.get(key);
  576. }
  577. // 查找字符串缓存
  578. private findStringCache(key: string): string | undefined {
  579. return this.stringCache.get(key);
  580. }
  581. // 添加缓存
  582. private addCache(key: string, value: Array<VideoItem>) {
  583. this.cache.set(key, value);
  584. }
  585. // 添加字符串缓存
  586. private addStringCache(key: string, value: string) {
  587. this.stringCache.set(key, value);
  588. }
  589. // 删除缓存
  590. private deleteCache(key: string) {
  591. this.cache.delete(key);
  592. this.saveCacheToStorage()
  593. }
  594. // 删除字符串缓存
  595. private deleteStringCache(key: string) {
  596. this.stringCache.delete(key);
  597. }
  598. // 多选机制
  599. @State selectedFiles: Array<VideoItem> = [];
  600. @Consume isMultiSelect: boolean;
  601. @State isAllSelected: boolean = false;
  602. @State appName: string = ''
  603. @State isHasDir: boolean = false
  604. @State packName: string = ''
  605. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  606. doSwipBack() {
  607. if(this.isSearchMode){
  608. console.info('onecold doSwipBack = ' +this.isSearchMode)
  609. this.isSearchMode = false
  610. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  611. this.searchText = ''
  612. this.getSortedFiles(this.currentPath)
  613. return
  614. }
  615. this.onSearchInput('')
  616. return
  617. }
  618. this.isZero = false
  619. if (this.modeType !== 0 && this.isCanBack) {
  620. this.onModeChange()
  621. this.isCanBack = false
  622. // 返回专辑列表时恢复滚动偏移量,支持列表和网格
  623. setTimeout(() => {
  624. if (this.modeType == 2) {
  625. if (this.isGridMusic||this.twoFingerType==4) {
  626. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  627. let lastWaterOffset = this.mScrollMap.get('lastWaterArtistScrollOffset') ?? 0
  628. if(this.twoFingerType==4){
  629. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  630. }else{
  631. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  632. }
  633. } else {
  634. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  635. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  636. }
  637. } else if (this.modeType == 3) {
  638. if (this.isGridMusic||this.twoFingerType==4) {
  639. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  640. let lastWaterOffset = this.mScrollMap.get('lastWaterAlBumScrollOffset') ?? 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('lastListAlBumScrollOffset') ?? 0
  648. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  649. }
  650. }
  651. }, 200)
  652. return
  653. }
  654. if (this.isHistory || this.isFavMusic) {
  655. this.isHistory = false
  656. this.getSortedFiles(this.currentPath)
  657. return
  658. }
  659. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  660. animateTo({ duration: 555 }, () => {
  661. // 动画闭包内控制Image组件的出现和消失
  662. this.isShowDrawer = !this.isShowDrawer
  663. this.offsetX = 0
  664. })
  665. return
  666. }
  667. //返回上一级歌单的滚动位置
  668. setTimeout(() => {
  669. if (this.modeType == 0) {
  670. if (this.isGridMusic||this.twoFingerType==4) {
  671. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  672. let lastWaterOffset = this.mScrollMap.get('lastWaterDirScrollOffset') ?? 0
  673. if(this.twoFingerType==4){
  674. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  675. }else{
  676. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  677. }
  678. } else {
  679. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  680. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  681. }
  682. }
  683. }, 100)
  684. this.currentPath = Utility.getParentDirectory(this.currentPath)
  685. Logger.info('this.currentPath2 = ' + this.currentPath)
  686. this.getSortedFiles(this.currentPath)
  687. }
  688. // 组件生命周期
  689. aboutToAppear() {
  690. console.info('onecold aboutToAppear sdkApiVersion = '+deviceInfo.sdkApiVersion)
  691. if(ArrayUtil.isNotEmpty(this.videoLocalList)&&this.modeType==0){
  692. this.updateListData(this.videoLocalList)
  693. }
  694. // 初始化 PlaylistTable
  695. this.playlistTable = new PlaylistTable(getContext(this))
  696. this.sonTwoFingerType = PreferencesUtil.getNumberSync('sonTwoFingerType', 3);
  697. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  698. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  699. this.tipPopup = !this.tipPopup
  700. PreferencesUtil.putSync('isFirstTiped',false)
  701. }
  702. this.initSetting()
  703. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  704. Utility.getAppName(getContext(this)).then((appName: string) => {
  705. this.appName = appName
  706. })
  707. this.packName = AppUtil.getBundleName()
  708. this.tabSelectedIndexes[0] = this.modeType//SegmentButton的索引
  709. this.loadCacheFromStorage(); // 加载文件夹缓存
  710. // 在首页初始化时读取媒体库,艺术家,专辑等缓存数据
  711. this.initLoadCache()
  712. this.mkDownLoadDir()
  713. let eventMusic: emitter.InnerEvent = { eventId: EventConstants.EVENT_AUDIO_OPEN }
  714. // 监听广播事件(打开其他应用处理)
  715. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  716. this.saveVideoDatas([eventData.data?.message], true)
  717. });
  718. //侧滑广播接收时间
  719. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_UPDATE }
  720. // 监听广播事件(手势返回处理)
  721. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  722. animateTo({ duration: 555 }, () => {
  723. this.doSwipBack()
  724. })
  725. });
  726. //ScanFilePage广播接收时间
  727. let eventScanUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_SCAN_UPDATE }
  728. // 监听ScanFilePage广播事件(更新数据库)
  729. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  730. this.doUpdateData()
  731. });
  732. // 监听歌单播放请求事件
  733. let eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY }
  734. emitter.on(eventPlaylistPlay, async (eventData: emitter.EventData) => {
  735. const data = eventData.data as Record<string, Object>
  736. if (!data) {
  737. Logger.error('heanup eventPlaylistPlay: eventData.data is undefined or null')
  738. return
  739. }
  740. // 检查歌单播放数据结构
  741. if (data.playlistId && data.songFilePaths && data.startIndex !== undefined) {
  742. const playlistData: PlaylistEventData = {
  743. playlistId: data.playlistId as string,
  744. playlistName: data.playlistName as string,
  745. songCount: data.songCount as number,
  746. startIndex: data.startIndex as number,
  747. isJump: data.isJump as boolean,
  748. songFilePaths: data.songFilePaths as string[]
  749. }
  750. await this.handlePlaylistPlayRequest(
  751. playlistData.playlistId,
  752. playlistData.playlistName,
  753. playlistData.songFilePaths,
  754. playlistData.startIndex,
  755. playlistData.isJump,
  756. )
  757. return
  758. }
  759. Logger.error('heanup eventPlaylistPlay: 接收到无效的数据结构')
  760. });
  761. let eventRefreshSort: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_REFRESH_SORT }
  762. // 监听广播事件(通用设置配置更新)
  763. emitter.on(eventRefreshSort, (eventData: emitter.EventData) => {
  764. if(this.modeType ==4){
  765. this.doSongListTask()//获取歌单信息
  766. }
  767. });
  768. let eventSetting: emitter.InnerEvent = { eventId: EventConstants.EVENT_SETTING_UPDATE }
  769. // 监听广播事件(通用设置配置更新)
  770. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  771. this.doChangeSetting()
  772. });
  773. let event: Callback<InterruptEvent> = (event) => {
  774. // LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  775. console.info(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`)
  776. this.savePlaybackPosition()
  777. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  778. this.pause();
  779. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  780. console.info(`onecold audioInterrupt startPlayOrResumePlay: ${JSON.stringify(event)}`)
  781. console.info('onecold startPlayOrResumePlay 514')
  782. this.startPlayOrResumePlay();
  783. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  784. console.info(`onecold 与其他应用音频冲突 被截断点 INTERRUPT_HINT_STOP`)
  785. if(!this.isSameTimePlay){
  786. this.stop();
  787. }
  788. }
  789. }
  790. this.mIjkMediaPlayer.on('audioInterrupt', event);
  791. // 音频设备断连回调处理比如蓝牙耳机断开
  792. let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  793. LogUtils.getInstance().LOGI(`Heanup deviceChange event: ${JSON.stringify(event)}`);
  794. if (event.reason === DeviceChangeReason.REASON_NEW_DEVICE_AVAILABLE) { // 音频设备连接
  795. } else if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  796. console.info('onecold 音频设备断开连接, 暂停播放')
  797. this.pause();
  798. }
  799. }
  800. // 订阅音频设备断开和连接事件
  801. this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  802. const eventPause: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAY_PAUSE }
  803. // 监听广播事件(hicar断开暂停播放)
  804. emitter.on(eventPause, (eventData: emitter.EventData) => {
  805. this.pause();
  806. });
  807. // 有线耳机断开和连接的监听。监听音频设备状态变化。
  808. let audioManager = audio.getAudioManager(); // 需要先创建AudioManager实例。
  809. let audioRoutingManager = audioManager.getRoutingManager(); // 再调用AudioManager的方法创建AudioRoutingManager实例。
  810. audioRoutingManager.on('deviceChange', audio.DeviceFlag.INPUT_DEVICES_FLAG, (deviceChanged: audio.DeviceChangeAction) => {
  811. console.info('device change type : ' + deviceChanged.type); // 设备连接状态变化,0为连接,1为断开连接。
  812. // 设备类型 22是USB耳机,带麦克风,3是有线耳机。
  813. if(deviceChanged.type==1&&
  814. (deviceChanged.deviceDescriptors[0].deviceType== 22||
  815. deviceChanged.deviceDescriptors[0].deviceType==3)){
  816. this.pause();
  817. }
  818. });
  819. this.makeWorker()
  820. //折叠屏的屏幕显示模式变化
  821. display.on('foldDisplayModeChange', (data) => {
  822. this.doChangeBarHeight()
  823. });
  824. display.on('foldStatusChange', (data) => {
  825. Logger.info('onecold foldStatusChange ')
  826. });
  827. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  828. // 读取 themeMode 并同步 currentColorMode
  829. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  830. this.applyThemeMode(this.themeMode)
  831. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  832. AppStorage.setOrCreate('themeColor', themeColor);
  833. this.themeColor = themeColor;
  834. this.doChangeSetting()
  835. this.windowClass.on('windowSizeChange', (size: window.Size) => {
  836. LogUtil.info('onecold windowSizeChange')
  837. this.doChangeBarHeight()
  838. let viewWidth = px2vp(size.width);
  839. let viewHeight = px2vp(size.height);
  840. if(this.isPhoneLan()){
  841. this.is_auto_hide_progress = false
  842. if(this.isHiCar()){
  843. return
  844. }
  845. setTimeout(() => {
  846. this.is_auto_hide_progress = true
  847. }, 6000)
  848. }else{
  849. this.startAutoHide()
  850. }
  851. });
  852. this.eventHub.on('onStateChange', (fg: boolean) => {
  853. if (fg && this.curState === 'STARTED') {
  854. this.stopPip();
  855. }
  856. });
  857. //NewIndex的博空调收到eventHub消息控制播放
  858. this.getUIContext().getHostContext()!.eventHub.on('playOrPause', () => {
  859. if (ArrayUtil.isNotEmpty(this.songList)) {
  860. this.playOrPause();
  861. } else {
  862. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  863. }
  864. });
  865. this.getUIContext().getHostContext()!.eventHub.on('playPrevious', () => {
  866. if (ArrayUtil.isNotEmpty(this.songList)) {
  867. this.playPrevious();
  868. } else {
  869. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  870. }
  871. });
  872. this.getUIContext().getHostContext()!.eventHub.on('playNext', () => {
  873. if (ArrayUtil.isNotEmpty(this.songList)) {
  874. this.playNext();
  875. } else {
  876. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  877. }
  878. });
  879. this.getUIContext().getHostContext()!.eventHub.on('showPlayerView', () => {
  880. this.showPlayerView();
  881. });
  882. this.getUIContext().getHostContext()!.eventHub.on('openPlayList', () => {
  883. this.openPlayList();
  884. });
  885. }
  886. //载入媒体库,艺术家,专辑等缓存
  887. initLoadCache(){
  888. this.mediaKuCount = PreferencesUtil.getNumberSync('mediaKuCount', 0)
  889. this.artistCount = PreferencesUtil.getNumberSync('artistCount', 0)
  890. this.albumCount = PreferencesUtil.getNumberSync('albumCount', 0)
  891. let cachedListStr:string = PreferencesUtil.getStringSync('mediaKuList', '[]');
  892. let cachedList = JSON.parse(cachedListStr) as Array<VideoItem>;
  893. if(ArrayUtil.isNotEmpty(cachedList)){
  894. this.mediaKuList = cachedList
  895. if(this.modeType==1){
  896. this.updateListData(this.mediaKuList)
  897. }
  898. }
  899. let artistListStr:string = PreferencesUtil.getStringSync('artistList', '[]');
  900. let artistCachedList = JSON.parse(artistListStr) as Array<VideoItem>;
  901. if(ArrayUtil.isNotEmpty(artistCachedList)){
  902. this.artistList = artistCachedList
  903. let artistMapStr:string = PreferencesUtil.getStringSync('artistMap', '[]');
  904. const parsedArray = JSON.parse(artistMapStr) as [string, VideoItem[]][];
  905. this.artistMap = new Map(parsedArray);
  906. // this.artistMap = JSON.parse(artistMapStr) as Map<string, VideoItem[]>;
  907. if(this.modeType==2){
  908. this.updateListData(this.artistList)
  909. }
  910. }
  911. let albumListStr:string = PreferencesUtil.getStringSync('albumList', '[]');
  912. let albumCachedList = JSON.parse(albumListStr) as Array<VideoItem>;
  913. if(ArrayUtil.isNotEmpty(albumCachedList)){
  914. this.albumList = albumCachedList
  915. let albumMapStr:string = PreferencesUtil.getStringSync('albumMap', '[]');
  916. const parsedArray = JSON.parse(albumMapStr) as [string, VideoItem[]][];
  917. this.albumMap = new Map(parsedArray);
  918. if(this.modeType==3){
  919. this.updateListData(this.albumList)
  920. }
  921. }
  922. }
  923. startAutoHide() {
  924. if(this.isHiCar()){
  925. return
  926. }
  927. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  928. console.info('onecold startAutoHide')
  929. this.is_auto_hide_progress = false
  930. setTimeout(() => {
  931. this.is_auto_hide_progress = true
  932. }, 6000)
  933. }
  934. }
  935. applyThemeMode(mode: number) {
  936. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  937. if (mode === 1) {
  938. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  939. } else if (mode === 2) {
  940. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  941. }
  942. AppStorage.setOrCreate('currentColorMode', colorMode)
  943. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  944. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  945. AppStorage.setOrCreate('themeMode', mode)
  946. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  947. // 只有强制浅色/深色时才主动设置
  948. const context = getContext(this) as common.UIAbilityContext
  949. context.getApplicationContext().setColorMode(colorMode)
  950. }
  951. initSetting() {
  952. this.showZMIndex = PreferencesUtil.getBooleanSync('showZMIndex', false)
  953. this.autoHideTitle = PreferencesUtil.getBooleanSync('autoHideTitle', true)
  954. this.isShowPrecious = PreferencesUtil.getBooleanSync('isShowPrecious', false)
  955. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  956. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  957. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  958. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, false)
  959. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  960. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  961. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  962. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  963. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  964. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  965. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  966. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  967. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  968. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 2)
  969. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  970. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  971. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  972. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  973. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  974. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  975. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  976. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  977. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  978. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  979. this.volumeSmall = PreferencesUtil.getBooleanSync('volumeSmall', false)
  980. this.autoParseMusicName = PreferencesUtil.getBooleanSync('autoParseMusicName', true)
  981. this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
  982. this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
  983. this.fastForwardSeconds = PreferencesUtil.getStringSync('fastForwardSeconds', '10')
  984. this.isShowBackFast = PreferencesUtil.getBooleanSync('isShowBackFast', false)
  985. this.isCopyFileToDownLoad = PreferencesUtil.getBooleanSync(SettingPage.IS_COPYFILE_TO_DOWNLOAD, false)
  986. let audioManager = audio.getAudioManager();
  987. let audioSessionManager: audio.AudioSessionManager = audioManager.getSessionManager();
  988. if(this.isSameTimePlay){
  989. //与其他应用同时播放,关键代码
  990. let strategy: audio.AudioSessionStrategy = {
  991. concurrencyMode: audio.AudioConcurrencyMode.CONCURRENCY_MIX_WITH_OTHERS
  992. };
  993. audioSessionManager.activateAudioSession(strategy).then(() => {
  994. console.info('onecold Succeeded in doing activateAudioSession.');
  995. }).catch((err: BusinessError) => {
  996. console.error(`Failed to activateAudioSession. Code: ${err.code}, message: ${err.message}`);
  997. });
  998. }else{
  999. let isActivated = audioSessionManager.isAudioSessionActivated();
  1000. if(isActivated){
  1001. audioSessionManager.deactivateAudioSession().then(() => {
  1002. console.info('Succeeded in doing deactivateAudioSession.');
  1003. }).catch((err: BusinessError) => {
  1004. console.error(`Failed to deactivateAudioSession. Code: ${err.code}, message: ${err.message}`);
  1005. });
  1006. }
  1007. }
  1008. if(this.volumeSmall){
  1009. this.volume = 0.5
  1010. }else{
  1011. this.volume = 1
  1012. }
  1013. //如果是hicar连接状态,这些都是false
  1014. if(this.isHiCar()){
  1015. this.autoHideTitle = false
  1016. this.isCoverRectangle= true
  1017. this.columns=4
  1018. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  1019. {
  1020. this.isGridMusic= false//用list不用网格
  1021. this.isCoverTopBig = false
  1022. }
  1023. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  1024. }
  1025. if (this.isSavePlayMode) {
  1026. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  1027. }
  1028. }
  1029. doChangeSetting() {
  1030. this.initSetting()
  1031. this.deleteCache(this.currentPath)
  1032. if (this.modeType === 0) {
  1033. this.getSortedFiles(this.currentPath)
  1034. }
  1035. }
  1036. doChangeBarHeight() {
  1037. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  1038. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  1039. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  1040. this.setBarHeightNormal()
  1041. }
  1042. }
  1043. onPageShow() {
  1044. this.knockController?.immersiveListening();
  1045. app.setImageCacheCount(100);
  1046. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  1047. app.setImageRawDataCacheSize(104857600);
  1048. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  1049. }
  1050. //开启线程查看各个数据库
  1051. makeWorker() {
  1052. setTimeout(() => {
  1053. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  1054. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  1055. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  1056. // workerInstance.postMessage({
  1057. // code: 1,
  1058. // data1: this.context,
  1059. // data2: this.rootPath,
  1060. // data3: this.lockPath,
  1061. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  1062. // data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  1063. // });
  1064. PreferencesUtil.putSync('isFirstApp', false)
  1065. } else {
  1066. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1067. workerInstance.postMessage({ code: 3, data: this.context });
  1068. workerInstance.postMessage({ code: 4, data: this.context });
  1069. this.getHistoryList(false)
  1070. }
  1071. }, 1000)
  1072. workerInstance.onmessage = (e: MessageEvents): void => {
  1073. const message = e.data as LocalMusicWorkerMessage;
  1074. switch (message.code) {
  1075. case 101: //第一次扫描文件夹入库
  1076. ToastUtil.showToast('刷新同步数据库成功!')
  1077. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  1078. this.doAllUpdateData()
  1079. break;
  1080. case 102: //查询媒体库列表
  1081. this.isRefreshing = false
  1082. this.mediaKuList = message.data // 只包含前100条
  1083. const mediaTotalCount: number = message.totalCount ?? this.mediaKuList.length;
  1084. this.mediaKuCount = mediaTotalCount;
  1085. Logger.info(`heanup 查询媒体库列表 缓存数=${this.mediaKuList.length}, 总数=${mediaTotalCount}`)
  1086. Utility.doSortListAscending(this.mediaKuList)
  1087. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  1088. // 媒体库模式下重新加载第一页(分页查询)
  1089. if (this.modeType === 1) {
  1090. this.resetAndLoadFirstPage();
  1091. }
  1092. PreferencesUtil.putSync('mediaKuCount', mediaTotalCount)
  1093. // 只保存前100条记录到缓存中
  1094. PreferencesUtil.putSync('mediaKuList', JSON.stringify(this.mediaKuList));
  1095. break;
  1096. case 103: //收到查询艺术家列表
  1097. this.isRefreshing = false
  1098. this.artistMap = message.data1; // 只包含前60个艺术家的歌曲
  1099. this.artistList = message.data2; // 只包含前100个艺术家
  1100. const artistTotalCount: number = message.totalCount ?? this.artistList.length;
  1101. this.artistCount = artistTotalCount;
  1102. const nextArtistCountMap = new Map(this.artistSongCountMap);
  1103. this.artistMap.forEach((songs, artist) => {
  1104. nextArtistCountMap.set(artist, songs.length);
  1105. });
  1106. this.artistSongCountMap = nextArtistCountMap;
  1107. Logger.info(`heanup 查询艺术家列表 缓存数=${this.artistList.length}, 总数=${artistTotalCount}`)
  1108. PreferencesUtil.putSync('artistCount', artistTotalCount)
  1109. // 艺术家模式下重新加载第一页(分页查询)
  1110. if (this.modeType === 2) {
  1111. this.resetAndLoadFirstPage();
  1112. }
  1113. // 保存前100条艺术家列表
  1114. PreferencesUtil.putSync('artistList', JSON.stringify(this.artistList));
  1115. // 保存前60条艺术家的歌曲Map
  1116. const sortedEntries = Array.from(this.artistMap.entries());
  1117. PreferencesUtil.putSync('artistMap', JSON.stringify(sortedEntries));
  1118. break;
  1119. case 104: //收到查询专辑列表
  1120. this.isRefreshing = false
  1121. this.albumMap = message.data1;
  1122. this.albumList = message.data2
  1123. const albumTotalCount: number = message.totalCount ?? this.albumList.length;
  1124. this.albumCount = albumTotalCount;
  1125. const nextAlbumCountMap = new Map(this.albumSongCountMap);
  1126. this.albumMap.forEach((songs, album) => {
  1127. nextAlbumCountMap.set(album, songs.length);
  1128. });
  1129. this.albumSongCountMap = nextAlbumCountMap;
  1130. Logger.info(`heanup 查询专辑列表 缓存数=${this.albumList.length}, 总数=${albumTotalCount}`)
  1131. // 专辑模式下重新加载第一页(分页查询)
  1132. if (this.modeType === 3) {
  1133. this.resetAndLoadFirstPage();
  1134. }
  1135. //查询完毕在启动是否自动播放
  1136. if (this.isStartAutoPlay&&this.isCanAuto) {
  1137. this.isCanAuto = false
  1138. console.info('onecold startPlayOrResumePlay 757')
  1139. this.startPlayOrResumePlay()
  1140. }
  1141. PreferencesUtil.putSync('albumCount', albumTotalCount)
  1142. // 保存前100条专辑列表(Worker已经只发送了100条)
  1143. PreferencesUtil.putSync('albumList', JSON.stringify(this.albumList));
  1144. // 保存前60条专辑Map(Worker已经只发送了60条)
  1145. const mapArrayAlbum = Array.from(this.albumMap.entries());
  1146. PreferencesUtil.putSync('albumMap', JSON.stringify(mapArrayAlbum));
  1147. break;
  1148. case 105: // 缓存完成后返回的元数据
  1149. this.handleWorkerMetadataPayload(message.data);
  1150. break;
  1151. case 106: // 编辑音乐元数据和封面完成
  1152. this.handleEditMusicResult(message.data);
  1153. break;
  1154. }
  1155. };
  1156. // 在调用terminate后,执行onexit
  1157. workerInstance.onexit = (code) => {
  1158. metadataExtractionInFlight.clear();
  1159. Logger.info(TAG, 'workerInstance 线程已退出,code: ' + code);
  1160. }
  1161. workerInstance.onerror = (err: ErrorEvent) => {
  1162. metadataExtractionInFlight.clear();
  1163. console.error('workerInstance 线程执行发生异常: ' + err.message)
  1164. }
  1165. }
  1166. private handleWorkerMetadataPayload(payload: WorkerMetadataPayload | undefined): void {
  1167. if (!payload || !payload.originFilePath) {
  1168. return;
  1169. }
  1170. metadataExtractionInFlight.delete(payload.originFilePath);
  1171. if (payload.error) {
  1172. Logger.warn(TAG, `缓存文件元数据解析失败: ${payload.error}`);
  1173. return;
  1174. }
  1175. this.applyMetadataToCollections(payload.originFilePath, payload);
  1176. }
  1177. private applyMetadataToCollections(filePath: string, payload: WorkerMetadataPayload): void {
  1178. const targets: Array<VideoItem> = [];
  1179. let mainListUpdated = false;
  1180. let playlistUpdated = false;
  1181. if (this.currentSong && this.currentSong.filePath === filePath) {
  1182. targets.push(this.currentSong);
  1183. }
  1184. const collectFromList = (list?: Array<VideoItem>, markUpdated?: () => void) => {
  1185. if (!list || list.length === 0) {
  1186. return;
  1187. }
  1188. const found = Utility.getItemByFilePath(list, filePath);
  1189. if (found) {
  1190. markUpdated?.();
  1191. targets.push(found);
  1192. }
  1193. };
  1194. collectFromList(this.videoLocalList, () => {
  1195. mainListUpdated = true;
  1196. });
  1197. collectFromList(this.songList, () => {
  1198. playlistUpdated = true;
  1199. });
  1200. collectFromList(this.historyList);
  1201. collectFromList(this.favList);
  1202. const remoteManager = RemoteDriveManager.getInstance();
  1203. collectFromList(remoteManager.webDavSongs);
  1204. const updated = new Set<VideoItem>();
  1205. const remoteMetadataUpdates: Map<string, WebDavMetadataUpdatePayload> = new Map();
  1206. for (let i = 0; i < targets.length; i++) {
  1207. const target = targets[i];
  1208. if (!target || updated.has(target)) {
  1209. continue;
  1210. }
  1211. updated.add(target);
  1212. this.mergeVideoItemWithPayload(target, payload);
  1213. if (isRemoteCloudType(target.type) && StrUtil.isNotEmpty(target.filePath)) {
  1214. remoteMetadataUpdates.set(target.filePath, {
  1215. filePath: target.filePath,
  1216. pixelMapPath: target.pixelMapPath,
  1217. name: target.name,
  1218. artist: target.artist
  1219. });
  1220. }
  1221. }
  1222. if (this.currentSong && this.currentSong.filePath === filePath) {
  1223. this.mergeVideoItemWithPayload(this.currentSong, payload);
  1224. if (payload.name) {
  1225. this.name = payload.name;
  1226. }
  1227. if (payload.artist) {
  1228. this.artist = payload.artist;
  1229. }
  1230. if (payload.pixelMapPath) {
  1231. this.cover = payload.pixelMapPath;
  1232. }
  1233. if (payload.lyricContent) {
  1234. this.applyInlineLyricContent(payload.lyricContent);
  1235. }
  1236. let avSessionDurationMs: number = this.duration;
  1237. if (payload.duration) {
  1238. const durationSeconds = Number(payload.duration);
  1239. if (!Number.isNaN(durationSeconds) && durationSeconds > 0) {
  1240. avSessionDurationMs = durationSeconds * 1000;
  1241. this.duration = avSessionDurationMs;
  1242. this.durationTime = Math.floor(avSessionDurationMs / 1000);
  1243. this.durationStringTime = secondToTime(this.durationTime);
  1244. }
  1245. }
  1246. if (avSessionDurationMs > 0) {
  1247. this.avSessionController.setAVMetadataMusic(this.currentSong, avSessionDurationMs, this.lyricContent);
  1248. }
  1249. this.currentSong = cloneVideoItem(this.currentSong);
  1250. AppStorage.setOrCreate('currentSong', this.currentSong);
  1251. }
  1252. const primaryTarget = targets.length > 0 ? targets[0] : undefined;
  1253. if (primaryTarget) {
  1254. this.persistRemoteMetadataToDb(primaryTarget).catch((error: Error) => {
  1255. Logger.error(TAG, `缓存元数据持久化失败: ${error.message}`);
  1256. });
  1257. }
  1258. if (remoteMetadataUpdates.size > 0) {
  1259. const eventUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
  1260. emitter.emit(eventUpdate, { data: Array.from(remoteMetadataUpdates.values()) });
  1261. }
  1262. this.refreshLazyListViews(mainListUpdated, playlistUpdated);
  1263. }
  1264. private handleEditMusicResult(result: WorkerEditMusicResult): void {
  1265. // 关闭进度条
  1266. DialogHelper.closeDialog(this.loadingDialogId)
  1267. if (result.success) {
  1268. console.log("heanup 编辑信息成功,数据库已同步");
  1269. if (result.coverResult) {
  1270. ToastUtil.showToast('内嵌封面成功');
  1271. }
  1272. ToastUtil.showToast('内嵌音乐标签成功');
  1273. this.isShowMoreView = false;
  1274. this.name = this.titleStr;
  1275. // 同步当前播放的歌曲信息
  1276. if (this.editingItem && this.currentSong && this.editingItem.filePath == this.currentSong.filePath) {
  1277. this.currentSong.name = this.titleStr;
  1278. this.artist = this.artistStr;
  1279. this.currentSong.artist = this.artistStr;
  1280. this.currentSong.album = this.ablumStr;
  1281. this.currentSong.year = this.yearStr;
  1282. this.currentSong.genre = this.genreStr;
  1283. this.currentSong.track = this.trackStr;
  1284. this.currentSong.lyricContent = this.lyricConStr;
  1285. this.currentSong.ALBUMARTIST = this.albumArtistStr;
  1286. this.currentSong.COMPOSER = this.composerStr;
  1287. this.currentSong.LYRICIST = this.lyricistStr;
  1288. this.currentSong.COMMENT = this.commentStr;
  1289. }
  1290. // if (result.needRefreshList && this.modeType == 0) {
  1291. // this.deleteCache(this.currentPath);
  1292. // this.getSortedFiles(this.currentPath);
  1293. // }
  1294. // 同步编辑字段到本地列表
  1295. if (this.editingItem) {
  1296. this.syncEditedFields(this.editingItem);
  1297. this.syncListsAfterEdit(this.editingItem.filePath);
  1298. this.doUpateEditedFields(this.editingItem);
  1299. }
  1300. // 清理临时变量
  1301. this.longItemFilePath = '';
  1302. this.tempLyricContent = '';
  1303. this.isShowEdit = false;
  1304. this.imagePathStr = '';
  1305. } else {
  1306. console.error("heanup 编辑信息失败: " + result.error);
  1307. ToastUtil.showToast('编辑失败: ' + (result.error || '未知错误'));
  1308. // 清理临时变量
  1309. this.longItemFilePath = '';
  1310. this.tempLyricContent = '';
  1311. this.isShowEdit = false;
  1312. this.imagePathStr = '';
  1313. }
  1314. }
  1315. private assignStringMetadata(target: VideoItem, key: keyof VideoItem, value?: string | null, allowEmpty = false): void {
  1316. if (value === undefined || value === null) {
  1317. return;
  1318. }
  1319. const text = value.toString();
  1320. if (!allowEmpty && text.trim().length === 0) {
  1321. return;
  1322. }
  1323. Reflect.set(target, key as string, value);
  1324. }
  1325. private assignNumberMetadata(target: VideoItem, key: keyof VideoItem, value?: number | null): void {
  1326. if (value === undefined || value === null || Number.isNaN(value)) {
  1327. return;
  1328. }
  1329. Reflect.set(target, key as string, value);
  1330. }
  1331. private mergeVideoItemWithPayload(target: VideoItem, payload: WorkerMetadataPayload): void {
  1332. if (!target || !payload) {
  1333. return;
  1334. }
  1335. this.assignStringMetadata(target, 'name', payload.name);
  1336. this.assignStringMetadata(target, 'artist', payload.artist);
  1337. this.assignStringMetadata(target, 'album', payload.album);
  1338. this.assignStringMetadata(target, 'bit_rate', payload.bit_rate);
  1339. this.assignStringMetadata(target, 'duration', payload.duration);
  1340. this.assignStringMetadata(target, 'sampleRate', payload.sampleRate);
  1341. this.assignStringMetadata(target, 'mimeType', payload.mimeType);
  1342. this.assignStringMetadata(target, 'size', payload.size);
  1343. this.assignStringMetadata(target, 'pixelMapPath', payload.pixelMapPath);
  1344. this.assignStringMetadata(target, 'lyricContent', payload.lyricContent, true);
  1345. this.assignStringMetadata(target, 'genre', payload.genre);
  1346. this.assignStringMetadata(target, 'track', payload.track);
  1347. this.assignStringMetadata(target, 'bits_per_raw_sample', payload.bits_per_raw_sample);
  1348. this.assignStringMetadata(target, 'channels', payload.channels);
  1349. this.assignStringMetadata(target, 'channel_layout', payload.channel_layout);
  1350. this.assignStringMetadata(target, 'start_time', payload.start_time);
  1351. this.assignStringMetadata(target, 'year', payload.year);
  1352. this.assignStringMetadata(target, 'disc', payload.disc);
  1353. this.assignStringMetadata(target, 'ALBUMARTIST', payload.ALBUMARTIST);
  1354. this.assignStringMetadata(target, 'COMPOSER', payload.COMPOSER);
  1355. this.assignStringMetadata(target, 'LYRICIST', payload.LYRICIST);
  1356. this.assignStringMetadata(target, 'COMMENT', payload.COMMENT, true);
  1357. this.assignNumberMetadata(target, 'videoSize', payload.videoSize);
  1358. this.assignNumberMetadata(target, 'probe_score', payload.probe_score);
  1359. this.assignNumberMetadata(target, 'nb_streams', payload.nb_streams);
  1360. this.assignNumberMetadata(target, 'nb_programs', payload.nb_programs);
  1361. }
  1362. private mergeVideoItemFromSource(target: VideoItem, source: VideoItem): void {
  1363. if (!target || !source) {
  1364. return;
  1365. }
  1366. this.assignStringMetadata(target, 'name', source.name);
  1367. this.assignStringMetadata(target, 'artist', source.artist);
  1368. this.assignStringMetadata(target, 'album', source.album);
  1369. this.assignStringMetadata(target, 'bit_rate', source.bit_rate);
  1370. this.assignStringMetadata(target, 'duration', source.duration);
  1371. this.assignStringMetadata(target, 'sampleRate', source.sampleRate);
  1372. this.assignStringMetadata(target, 'trackCount', source.trackCount);
  1373. this.assignStringMetadata(target, 'mimeType', source.mimeType);
  1374. this.assignStringMetadata(target, 'size', source.size);
  1375. this.assignStringMetadata(target, 'pixelMapPath', source.pixelMapPath);
  1376. this.assignStringMetadata(target, 'lyricContent', source.lyricContent, true);
  1377. this.assignStringMetadata(target, 'genre', source.genre);
  1378. this.assignStringMetadata(target, 'track', source.track);
  1379. this.assignStringMetadata(target, 'bits_per_raw_sample', source.bits_per_raw_sample);
  1380. this.assignStringMetadata(target, 'channels', source.channels);
  1381. this.assignStringMetadata(target, 'channel_layout', source.channel_layout);
  1382. this.assignStringMetadata(target, 'start_time', source.start_time);
  1383. this.assignStringMetadata(target, 'year', source.year);
  1384. this.assignStringMetadata(target, 'disc', source.disc);
  1385. this.assignStringMetadata(target, 'ALBUMARTIST', source.ALBUMARTIST);
  1386. this.assignStringMetadata(target, 'COMPOSER', source.COMPOSER);
  1387. this.assignStringMetadata(target, 'LYRICIST', source.LYRICIST);
  1388. this.assignStringMetadata(target, 'COMMENT', source.COMMENT, true);
  1389. this.assignNumberMetadata(target, 'videoSize', source.videoSize);
  1390. this.assignNumberMetadata(target, 'probe_score', source.probe_score);
  1391. this.assignNumberMetadata(target, 'nb_streams', source.nb_streams);
  1392. this.assignNumberMetadata(target, 'nb_programs', source.nb_programs);
  1393. if (source.remote_rel_path && StrUtil.isEmpty(target.remote_rel_path)) {
  1394. target.remote_rel_path = source.remote_rel_path;
  1395. }
  1396. }
  1397. private async hydrateRemoteSongFromDb(item: VideoItem | undefined): Promise<void> {
  1398. if (!item || !isRemoteCloudType(item.type)) {
  1399. return;
  1400. }
  1401. const storagePath = item.remote_rel_path || WebDavUrlUtil.toStoragePath(item.filePath);
  1402. if (!storagePath) {
  1403. return;
  1404. }
  1405. try {
  1406. const cached = await this.table.queryVideoByFilePath(storagePath);
  1407. if (!cached) {
  1408. return;
  1409. }
  1410. this.mergeVideoItemFromSource(item, cached);
  1411. if (StrUtil.isEmpty(item.remote_rel_path)) {
  1412. item.remote_rel_path = storagePath;
  1413. }
  1414. if (item === this.currentSong) {
  1415. if (StrUtil.isNotEmpty(item.name)) {
  1416. this.name = item.name;
  1417. }
  1418. if (StrUtil.isNotEmpty(item.artist)) {
  1419. this.artist = item.artist!;
  1420. }
  1421. if (StrUtil.isNotEmpty(item.pixelMapPath)) {
  1422. this.cover = item.pixelMapPath!;
  1423. }
  1424. if (StrUtil.isNotEmpty(item.lyricContent) && StrUtil.isEmpty(this.lyricContent)) {
  1425. this.applyInlineLyricContent(item.lyricContent as string);
  1426. }
  1427. }
  1428. } catch (error) {
  1429. Logger.error(TAG, `hydrateRemoteSongFromDb 失败: ${(error as Error).message}`);
  1430. }
  1431. }
  1432. private applyInlineLyricContent(content: string): void {
  1433. if (StrUtil.isEmpty(content)) {
  1434. return;
  1435. }
  1436. this.lyricContent = content;
  1437. const lines: string[] = content.split('\n').map((line: string) => line.trim());
  1438. const lyric: Lyric = this.parser.parse(lines);
  1439. this.lyricController.setLyric(lyric);
  1440. this.lyricControllerXF.setLyric(lyric);
  1441. this.lyricControllerSingle.setLyric(lyric);
  1442. }
  1443. private extractParentPathFromStoragePath(path: string): string {
  1444. if (!path) {
  1445. return '';
  1446. }
  1447. const lastSlash = path.lastIndexOf('/');
  1448. if (lastSlash <= 0) {
  1449. return '';
  1450. }
  1451. return path.substring(0, lastSlash);
  1452. }
  1453. private resolveRemoteStoragePath(target: VideoItem): string | null {
  1454. if (!target || !isRemoteCloudType(target.type)) {
  1455. return null;
  1456. }
  1457. if (isWebDavType(target.type)) {
  1458. const storagePath = target.remote_rel_path || WebDavUrlUtil.toStoragePath(target.filePath);
  1459. if (storagePath) {
  1460. target.remote_rel_path = storagePath;
  1461. return storagePath;
  1462. }
  1463. return null;
  1464. }
  1465. if (target.remote_rel_path && target.remote_rel_path.length > 0) {
  1466. return target.remote_rel_path;
  1467. }
  1468. return null;
  1469. }
  1470. private async persistRemoteMetadataToDb(target: VideoItem): Promise<void> {
  1471. if (!this.context || !target || !isRemoteCloudType(target.type)) {
  1472. return;
  1473. }
  1474. const storagePath = this.resolveRemoteStoragePath(target);
  1475. if (!storagePath) {
  1476. return;
  1477. }
  1478. const table = new MediaTable(this.context);
  1479. await new Promise<void>((resolve) => {
  1480. table.getRdbStore(this.context as Context, () => resolve());
  1481. });
  1482. const cloneItem = cloneVideoItem(target);
  1483. cloneItem.filePath = storagePath;
  1484. cloneItem.remote_rel_path = storagePath;
  1485. cloneItem.parentPath = this.extractParentPathFromStoragePath(storagePath);
  1486. await table.saveOrUpdateWebDavItem(cloneItem);
  1487. }
  1488. onPageHide(): void {
  1489. this.knockController?.immersiveDisableListening();
  1490. }
  1491. @State isFirstStartPlay: boolean = false
  1492. private async startFileDeletionWatcher(): Promise<void> {
  1493. if (!this.rootPath) {
  1494. return;
  1495. }
  1496. if (!this.deletionWatcher) {
  1497. this.deletionWatcher = new FileDeletionWatcher(this.context, this.table);
  1498. }
  1499. try {
  1500. await this.deletionWatcher.watchDirectories([
  1501. this.rootPath,
  1502. this.lockPath,
  1503. this.favPath,
  1504. this.historyPath
  1505. ]);
  1506. } catch (error) {
  1507. Logger.error(TAG, `初始化文件删除监听失败: ${(error as Error).message}`);
  1508. }
  1509. }
  1510. //获取download_path
  1511. async mkDownLoadDir() {
  1512. const documentViewPicker = new picker.DocumentViewPicker()
  1513. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  1514. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  1515. PreferencesUtil.putSync('download_path', this.rootPath+'/')
  1516. this.currentPath = this.rootPath
  1517. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  1518. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  1519. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  1520. Logger.info('onecold rootPath = ' + this.rootPath)
  1521. Logger.info('onecold lockPath = ' + this.lockPath)
  1522. if (!FileUtil.accessSync(this.lockPath)) {
  1523. FileUtil.mkdirSync(this.lockPath)
  1524. }
  1525. if (!FileUtil.accessSync(this.favPath)) {
  1526. FileUtil.mkdirSync(this.favPath)
  1527. }
  1528. if (!FileUtil.accessSync(this.historyPath)) {
  1529. FileUtil.mkdirSync(this.historyPath)
  1530. }
  1531. // await this.startFileDeletionWatcher();
  1532. this.getSortedFiles(this.rootPath).then(async () => {
  1533. this.isFavMusic = false
  1534. //穿山甲
  1535. // this.loadBannerAd(CSJUtil.getBannerID())
  1536. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  1537. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  1538. if (ArrayUtil.isEmpty(this.songList)) {
  1539. this.songList = this.getCurFileList()
  1540. } else {
  1541. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  1542. }
  1543. if (ArrayUtil.isNotEmpty(this.songList)) {
  1544. this.isFirstStartPlay = true
  1545. this.sonDataSource.pushArrayData(this.songList)
  1546. if (this.currentSong === undefined) {
  1547. this.isFirstStartPlay = false
  1548. this.currentSong = this.songList[0]
  1549. }
  1550. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  1551. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  1552. context: this.context,
  1553. autoParseMusicName: this.autoParseMusicName
  1554. });
  1555. Logger.info(TAG, `WebDAV URL同步构建完成: ${this.videoUrl}`);
  1556. this.name = this.currentSong.name
  1557. this.cover = this.currentSong.pixelMapPath
  1558. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  1559. } else {
  1560. this.name = '空空如也'
  1561. }
  1562. })
  1563. this.getFavList(false)
  1564. }
  1565. getFavList(isFavRefresh: boolean) {
  1566. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  1567. this.favList = result
  1568. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  1569. this.videoLocalList = this.favList
  1570. this.updateListData(this.videoLocalList, true)
  1571. }
  1572. })
  1573. }
  1574. getHistoryList(isRefresh: boolean) {
  1575. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  1576. this.historyList = result
  1577. // for (let i = 0; i < this.historyList.length; i++) {
  1578. //
  1579. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  1580. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  1581. // }
  1582. if (isRefresh) {
  1583. this.videoLocalList = this.historyList
  1584. this.updateListData(this.videoLocalList, true)
  1585. }
  1586. })
  1587. }
  1588. // 组件消失生命周期
  1589. aboutToDisappear() {
  1590. console.info('LifeCycleComponent aboutToDisappear');
  1591. this.deletionWatcher?.stop();
  1592. this.knockController?.immersiveDisableListening();
  1593. this.curIndex = 0
  1594. emitter.off(EventConstants.EVENT_AUDIO_OPEN);
  1595. emitter.off(EventConstants.EVENT_SCAN_UPDATE);
  1596. emitter.off(EventConstants.EVENT_SWIPE_BACK_UPDATE);
  1597. emitter.off(EventConstants.EVENT_SETTING_UPDATE);
  1598. this.mDestroyPage = true;
  1599. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  1600. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  1601. this.stop();
  1602. }
  1603. this.mIjkMediaPlayer.off('audioInterrupt');
  1604. this.mIjkMediaPlayer.off('deviceChange');
  1605. if (workerInstance) {
  1606. workerInstance.terminate();
  1607. }
  1608. this.stopPip();
  1609. this.destroyPipController()
  1610. this.getUIContext().getHostContext()!.eventHub.off('playOrPause');
  1611. this.getUIContext().getHostContext()!.eventHub.off('playPrevious');
  1612. this.getUIContext().getHostContext()!.eventHub.off('playNext');
  1613. this.getUIContext().getHostContext()!.eventHub.off('showPlayerView');
  1614. this.getUIContext().getHostContext()!.eventHub.off('openPlayList');
  1615. }
  1616. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean,openItem?:VideoItem) {
  1617. this.isFavMusic = false
  1618. console.info('onecold getSortedFiles 1 curPath '+curPath)
  1619. if (isWorkerPost) {
  1620. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1621. }
  1622. if (this.modeType !== 0) {
  1623. return
  1624. }
  1625. console.info('onecold getSortedFiles 2')
  1626. this.isCanBack = false
  1627. this.currentPath = curPath
  1628. console.info('onecold getSortedFiles this.currentPath ='+this.currentPath)
  1629. this.titleName = getFileDirName(this.currentPath,this.rootPath)
  1630. if (curPath === this.rootPath) {
  1631. this.rightTopImage = $r('sys.symbol.sort')
  1632. } else {
  1633. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  1634. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  1635. this.rightTopImage = $r('sys.symbol.chevron_left')
  1636. }
  1637. }
  1638. // Get the current file list and calculate its hash
  1639. this.fileList = FileUtil.listFileSync(curPath);
  1640. const currentHash = simpleHash(this.fileList);
  1641. // Check cache
  1642. const cachedValue = this.findCache(curPath);
  1643. Logger.info('onecold cachedValue = ' + cachedValue)
  1644. const cachedHash = this.findStringCache(curPath + '_hash');
  1645. const cachedDirList = this.findCache(curPath + "_dirList");
  1646. if (cachedValue !== undefined&&!this.isRefreshing) {
  1647. // this.videoLocalList = cachedValue;
  1648. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  1649. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  1650. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  1651. }
  1652. this.isRefreshing = false
  1653. this.updateListData(cachedValue)
  1654. }
  1655. if (cachedDirList !== undefined) {
  1656. this.dirList = cachedDirList
  1657. }
  1658. //通过当前hash值和缓存hash判断list有没有变化
  1659. if (cachedValue && cachedHash === currentHash) {
  1660. return;
  1661. }
  1662. // this.fileList = FileUtil.listFileSync(curPath)
  1663. let directories: Array<VideoItem> = [];
  1664. let files: Array<VideoItem> = [];
  1665. for (let i = 0; i < this.fileList.length; i++) {
  1666. // console.info(`The name of file: ${this.fileList[i]}`);
  1667. let path = curPath + '/' + this.fileList[i]
  1668. if (FileUtil.isDirectory(path)) {
  1669. let item: VideoItem =
  1670. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  1671. '')
  1672. if (this.isShowDir(item.name)) {
  1673. directories.push(item);
  1674. }
  1675. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1676. // Utility.doSortListAscending(directories)
  1677. } else {
  1678. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  1679. let item: VideoItem =
  1680. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  1681. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  1682. files.push(item);
  1683. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1684. // this.doSortListAscending(files)
  1685. }
  1686. }
  1687. }
  1688. }
  1689. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  1690. if (this.currentPath !== this.lockPath) {
  1691. files = result;
  1692. }
  1693. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1694. Utility.doSortListAscending(files)
  1695. if (this.currentPath === this.rootPath) {
  1696. this.dirList = directories
  1697. this.addCache(curPath + "_dirList", this.dirList);
  1698. }
  1699. //插入广告先注释掉
  1700. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  1701. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  1702. // directories.push(adItem)
  1703. // }
  1704. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  1705. this.videoLocalList = directories.concat(files);
  1706. this.updateListData(this.videoLocalList)
  1707. if (ArrayUtil.isNotEmpty(files)) {
  1708. if (this.currentPath != this.rootPath) {
  1709. if (files) {
  1710. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  1711. }
  1712. }
  1713. // 缓存结果
  1714. this.addCache(curPath, this.videoLocalList);
  1715. await this.saveCacheToStorage(); // 保存缓存至本地存储
  1716. this.addStringCache(curPath + '_hash', currentHash);
  1717. }
  1718. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  1719. for (let i = 0; i < this.videoLocalList.length; i++) {
  1720. console.info(`onecold gengxin 1: ${this.videoLocalList[i].name}`);
  1721. }
  1722. // this.setButtonStatus()
  1723. this.openMusic(isOpen, destPath,openItem)
  1724. this.isRefreshing = false
  1725. });
  1726. }
  1727. //第三方app打开天天静听导入音乐后播放
  1728. openMusic(isOpen?: boolean, destPath?: string,openItem?:VideoItem){
  1729. if (isOpen&&destPath) {
  1730. if (destPath === undefined) {
  1731. // 处理 destPath 为 undefined 的情况
  1732. return
  1733. }
  1734. if (destPath.endsWith('.lrc')) {
  1735. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  1736. if (StrUtil.isNotEmpty(this.videoUrl)) {
  1737. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  1738. this.initLyric(lyricPath);
  1739. }
  1740. return
  1741. }
  1742. if(openItem){
  1743. this.doPlay(openItem,0,false,true)
  1744. // this.isShowPlay = true
  1745. this.setShowPlayTrue()
  1746. }
  1747. }
  1748. }
  1749. //扫描文件夹入库
  1750. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  1751. const files = FileUtil.listFileSync(curPath);
  1752. let mediaItems: VideoItem[] = [];
  1753. Logger.info('onecold scanDirectory start ')
  1754. for (const file of files) {
  1755. const fPath = `${curPath}/${file}`;
  1756. if (fPath === this.lockPath) {
  1757. Logger.info(`Skipping locked path: ${fPath}`);
  1758. continue;
  1759. }
  1760. if (FileUtil.isDirectory(fPath)) {
  1761. // Recursively scan subdirectories
  1762. const subDirItems = await this.scanDirectory(fPath);
  1763. mediaItems = mediaItems.concat(subDirItems);
  1764. } else {
  1765. Logger.info('onecold scanDirectory filePath = ' + fPath)
  1766. // Process media files
  1767. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  1768. let mediaItem: VideoItem =
  1769. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1770. mediaItems.push(mediaItem);
  1771. this.table.insert(mediaItem, (id: number) => {
  1772. });
  1773. }
  1774. }
  1775. }
  1776. return mediaItems;
  1777. }
  1778. updateListData(mList: Array<VideoItem>, noSort?: boolean) {
  1779. this.isShowTitleBar = true
  1780. animateTo({ duration: 666 }, () => {
  1781. this.opacityItem = 0.5;
  1782. });
  1783. setTimeout(() => {
  1784. this.videoLocalList = mList;
  1785. if (!noSort) {
  1786. if (this.modeType === 0 || this.modeType === 1) {
  1787. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1788. this.doSortType(this.sortType)
  1789. }
  1790. }
  1791. this.dataSource.pushArrayData(this.videoLocalList)
  1792. animateTo({ duration: 666 }, () => {
  1793. this.opacityItem = 1;
  1794. });
  1795. this.setButtonStatus()
  1796. //添加到字母索引表
  1797. this.setAlphaBet()
  1798. }, 200);
  1799. }
  1800. getCurFileList(): Array<VideoItem> {
  1801. if(this.isSearchMode){
  1802. return this.filteredList
  1803. }
  1804. let files: Array<VideoItem> = [];
  1805. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1806. for (let i = 0; i < this.videoLocalList.length; i++) {
  1807. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  1808. files.push(this.videoLocalList[i]);
  1809. }
  1810. }
  1811. }
  1812. return files
  1813. }
  1814. setButtonStatus() {
  1815. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1816. this.isZero = false
  1817. } else {
  1818. this.isZero = true
  1819. }
  1820. if (this.currentPath !== this.rootPath &&
  1821. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  1822. this.isHasDir = true //不为空,说明有子文件夹
  1823. } else {
  1824. this.isHasDir = false
  1825. }
  1826. }
  1827. @Builder
  1828. SortMenuBuilder() {
  1829. Menu() {
  1830. MenuItem({
  1831. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  1832. content: "按艺术家升序"
  1833. })
  1834. .onClick(async () => {
  1835. await this.doSortType(0)
  1836. })
  1837. MenuItem({
  1838. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  1839. content: "按艺术家降序"
  1840. })
  1841. .onClick(async () => {
  1842. await this.doSortType(1)
  1843. })
  1844. MenuItem({
  1845. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat_size_square')),
  1846. content: "按专辑升序"
  1847. })
  1848. .onClick(async () => {
  1849. await this.doSortType(2)
  1850. })
  1851. MenuItem({
  1852. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.character_arrow_clockwise')),
  1853. content: "按专辑降序"
  1854. })
  1855. .onClick(async () => {
  1856. await this.doSortType(3)
  1857. })
  1858. MenuItem({
  1859. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  1860. content: $r('app.string.sort_by_name')
  1861. })
  1862. .onClick(async () => {
  1863. await this.doSortType(4)
  1864. })
  1865. MenuItem({
  1866. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  1867. content: '按名称降序'
  1868. })
  1869. .onClick(async () => {
  1870. await this.doSortType(5)
  1871. })
  1872. MenuItem({
  1873. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  1874. content: $r('app.string.sort_by_time')
  1875. })
  1876. .onClick(async () => {
  1877. await this.doSortType(6)
  1878. })
  1879. MenuItem({
  1880. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
  1881. content: '按添加时间降序'
  1882. })
  1883. .onClick(async () => {
  1884. await this.doSortType(7)
  1885. })
  1886. }.attributeModifier(new MenuModifier())
  1887. }
  1888. @Builder
  1889. SortMenuForArtistAblumBuilder() {
  1890. Menu() {
  1891. MenuItem({
  1892. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  1893. content: $r('app.string.sort_by_name')
  1894. })
  1895. .onClick(async () => {
  1896. await this.doSortType(4)
  1897. })
  1898. MenuItem({
  1899. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  1900. content: '按名称降序'
  1901. })
  1902. .onClick(async () => {
  1903. await this.doSortType(5)
  1904. })
  1905. MenuItem({
  1906. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  1907. content: '按数量升序'
  1908. })
  1909. .onClick(async () => {
  1910. await this.doSortType(8)
  1911. })
  1912. MenuItem({
  1913. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
  1914. content: '按数量降序'
  1915. })
  1916. .onClick(async () => {
  1917. await this.doSortType(9)
  1918. })
  1919. }.attributeModifier(new MenuModifier())
  1920. }
  1921. async doSortType(index: number): Promise<void> {
  1922. Logger.info('heanup LocalMusic', `doSortType: 切换排序方式 sortType=${index}, mode=${this.modeType}`);
  1923. this.sortType = index;
  1924. PreferencesUtil.putSync(SettingPage.SORT_TYPE, index);
  1925. // 分页模式下,排序需要重新从数据库查询
  1926. await this.resetAndLoadFirstPage();
  1927. }
  1928. showSheelDialog() {
  1929. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  1930. // this.showTips()
  1931. // return
  1932. // }
  1933. this.showAddDialog()
  1934. }
  1935. showAddDialog() {
  1936. if (this.modeType === 2 || this.modeType === 3) {
  1937. return
  1938. }
  1939. DialogHelper.showActionSheetDialog({
  1940. title: "请选择添加方式(建议歌词文件一起导入)",
  1941. sheets: [
  1942. { value: "新建文件夹", fontColor: $r('app.color.text_color') },
  1943. { value: "手动导入", fontColor: $r('app.color.text_color') },
  1944. { value: "自动导入", fontColor: $r('app.color.text_color') },
  1945. { value: "全选导入", fontColor: $r('app.color.text_color') },
  1946. ],
  1947. maskColor: Color.Transparent,
  1948. backgroundColor: $r('app.color.bg_card'),
  1949. transition: AnimationHelper.transitionInDown(555),
  1950. onAction: (index) => {
  1951. switch (index) {
  1952. case 0:
  1953. if (this.modeType === 0) {
  1954. this.showMkDialog()
  1955. } else {
  1956. ToastUtil.showToast('请切换到首页才能新建文件夹!')
  1957. }
  1958. break;
  1959. case 1:
  1960. this.callFilePickerSelectFile()
  1961. break;
  1962. case 2:
  1963. this.showTips()
  1964. break;
  1965. case 3:
  1966. this.goSelectMusic()
  1967. break;
  1968. }
  1969. }
  1970. })
  1971. }
  1972. //拉起音频
  1973. goSelectMusic() {
  1974. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  1975. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  1976. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  1977. ) {
  1978. ToastUtil.showToast('暂时不支持该设备')
  1979. return
  1980. }
  1981. try {
  1982. let documentSelectOptions = new picker.DocumentSelectOptions();
  1983. documentSelectOptions.authMode = true
  1984. documentSelectOptions.multiAuthMode = true
  1985. if( deviceInfo.sdkApiVersion>=21){//如果api大于21 ,可以支持1w首歌以上
  1986. documentSelectOptions.maxSelectNumber = 20000
  1987. }
  1988. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  1989. let documentPicker = new picker.DocumentViewPicker(this.context);
  1990. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  1991. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  1992. this.saveVideoDatas(documentSelectResult)
  1993. }
  1994. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  1995. JSON.stringify(documentSelectResult));
  1996. }).catch((err: BusinessError) => {
  1997. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  1998. });
  1999. } catch (error) {
  2000. let err: BusinessError = error as BusinessError;
  2001. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2002. }
  2003. }
  2004. async showTips() {
  2005. try {
  2006. this.getUIContext().getPromptAction().showDialog({
  2007. title: '导入指南',
  2008. message:'用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  2009. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  2010. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  2011. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后去文件扫描一下。\n',
  2012. buttons: [
  2013. {
  2014. text: '知道了',
  2015. color: '#000000'
  2016. },
  2017. ]
  2018. }, (err, data) => {
  2019. if (err) {
  2020. console.error('showDialog err: ' + err);
  2021. return;
  2022. }
  2023. console.info('showDialog success callback, click button: ' + data.index);
  2024. });
  2025. } catch (error) {
  2026. let message = (error as BusinessError).message;
  2027. let code = (error as BusinessError).code;
  2028. console.error(`showDialog args error code is ${code}, message is ${message}`);
  2029. };
  2030. }
  2031. showMkDialog() {
  2032. DialogHelper.showTextInputDialog({
  2033. title: '新建歌单',
  2034. maskColor: Color.Transparent,
  2035. text: '',
  2036. transition: AnimationHelper.transitionInDown(666),
  2037. onChange: (text) => {
  2038. console.error("onChange: " + text);
  2039. },
  2040. onAction: (action, dialogId, content) => {
  2041. // ToastUtil.showToast('content = ' +content)
  2042. if (action == DialogAction.TWO) {
  2043. const newName = content
  2044. const newPath = this.currentPath + '/' + newName
  2045. FileUtil.mkdir(newPath, true).then(() => {
  2046. this.cache.delete(this.currentPath); // 删除目标路径缓存
  2047. this.getSortedFiles(this.currentPath)
  2048. }).catch((error: BusinessError) => {
  2049. console.error(error.message);
  2050. });
  2051. }
  2052. }
  2053. })
  2054. }
  2055. @State progress: number = 0;
  2056. async saveVideoDatas(uris:string[],isOpen?:boolean){
  2057. if (ArrayUtil.isEmpty(uris)) {
  2058. return;
  2059. }
  2060. console.info('onecold this.isCopyFileToDownLoad = ' + this.isCopyFileToDownLoad);
  2061. if(this.isCopyFileToDownLoad||this.currentPath==this.lockPath||isOpen){
  2062. this.saveVideoDatasToDownLoad(uris,isOpen)
  2063. return
  2064. }
  2065. // 初始化进度条
  2066. this.progress = 0;
  2067. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  2068. progress: this.progress,
  2069. backCancel: false,
  2070. autoCancel: false,
  2071. loadColor: $r('app.color.title_bar_bg'),
  2072. fontColor: $r('app.color.title_bar_bg')
  2073. });
  2074. // 计算处理总数用于进度计算
  2075. const totalItems = uris.length;
  2076. let processedItems = 0;
  2077. for (let i = 0; i < uris.length; i++) {
  2078. let filePath = uris[i];
  2079. try {
  2080. if (this.currentPath !== this.lockPath) { // 判断不是私密音乐,才入库
  2081. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2082. let mediaItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context,
  2083. filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2084. console.info('onecold saveVideoDatas filePath = ' + filePath)
  2085. if (!filePath.includes(this.rootPath)) {
  2086. console.info('onecold saveVideoDatas mediaItem.parentPath111 = ' + mediaItem.parentPath)
  2087. mediaItem.parentPath = this.currentPath;
  2088. }
  2089. console.info('onecold saveVideoDatas mediaItem.parentPath = ' + mediaItem.parentPath)
  2090. this.table.insert(mediaItem, (id: number) => {
  2091. // 插入完成回调
  2092. });
  2093. }
  2094. }
  2095. // 更新进度
  2096. processedItems++;
  2097. this.progress = Math.floor((processedItems / totalItems) * 100);
  2098. DialogHelper.updateLoading(this.loadingProgressDialogId,` 正在处理 ${this.progress}%`, this.progress);
  2099. } catch (error) {
  2100. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2101. // 即使出错也更新进度
  2102. processedItems++;
  2103. this.progress = Math.floor((processedItems / totalItems) * 100);
  2104. DialogHelper.updateLoading(this.loadingProgressDialogId,` 正在处理 ${this.progress}%`, this.progress);
  2105. }
  2106. }
  2107. // 关闭进度条
  2108. DialogHelper.closeDialog(this.loadingProgressDialogId)
  2109. this.isZero = false
  2110. // 删除目标路径缓存
  2111. setTimeout(() => {
  2112. this.cache.delete(this.currentPath);
  2113. this.getSortedFiles(this.currentPath,false,uris[0],isOpen)
  2114. this.setButtonStatus()
  2115. }, 500);
  2116. }
  2117. async saveVideoDatasToDownLoad(uris: string[], isOpen?: boolean) {
  2118. if (ArrayUtil.isEmpty(uris)) {
  2119. return;
  2120. }
  2121. let newUris: string[] = [];
  2122. this.progress = 0
  2123. this.loadingProgressDialogId = DialogHelper.showLoadingProgress({
  2124. progress: this.progress,
  2125. backCancel: false,
  2126. autoCancel: false,
  2127. loadColor: this.themeColor,
  2128. fontColor: this.themeColor
  2129. });
  2130. // 计算所有文件的总大小
  2131. let totalSize = 0;
  2132. for (let uri of uris) {
  2133. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  2134. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  2135. await fileIo.close(sourceFile.fd);
  2136. }
  2137. let totalRead = 0;
  2138. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  2139. Logger.info(TAG, 'destPath uri: ' + destPath);
  2140. for (let i = 0; i < uris.length; i++) {
  2141. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  2142. Logger.info(TAG, 'filePath uri: ' + filePath);
  2143. newUris.push(filePath);
  2144. try {
  2145. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  2146. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  2147. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  2148. const buffer = new ArrayBuffer(buffSize);
  2149. let len = await fileIo.read(sourceFile.fd, buffer);
  2150. while (len > 0) {
  2151. await fileIo.write(destFile.fd, buffer.slice(0, len));
  2152. totalRead += len;
  2153. // 计算总进度
  2154. this.progress = Math.floor((totalRead / totalSize) * 100);
  2155. DialogHelper.updateLoading( this.loadingProgressDialogId,`正在导入 ${this.progress}%`, this.progress);
  2156. len = await fileIo.read(sourceFile.fd, buffer);
  2157. }
  2158. await fileIo.close(sourceFile.fd);
  2159. await fileIo.close(destFile.fd);
  2160. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  2161. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2162. let mediaItem: VideoItem =
  2163. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2164. this.table.insert(mediaItem, (id: number) => {
  2165. // 删除目标路径缓存
  2166. this.cache.delete(this.currentPath);
  2167. this.getSortedFiles(this.currentPath, true, destPath, isOpen,mediaItem)
  2168. });
  2169. }
  2170. }
  2171. } catch (error) {
  2172. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2173. }
  2174. }
  2175. DialogHelper.closeDialog(this.loadingProgressDialogId);
  2176. this.isZero = false
  2177. Logger.info(TAG, 'scan select video result:' + newUris)
  2178. }
  2179. //拉起音频
  2180. // goSelectMusic(){
  2181. //
  2182. // try {
  2183. // let audioSelectOptions = new picker.AudioSelectOptions();
  2184. // let audioPicker = new picker.AudioViewPicker(this.context);
  2185. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  2186. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  2187. // this.saveVideoDatas(audioSelectResult)
  2188. // }
  2189. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  2190. // }).catch((err: BusinessError) => {
  2191. //
  2192. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  2193. // });
  2194. // } catch (error) {
  2195. // let err: BusinessError = error as BusinessError;
  2196. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2197. // }
  2198. //
  2199. //
  2200. //
  2201. // }
  2202. async goSelectImage(item: VideoItem): Promise<string | undefined> {
  2203. if (!item) {
  2204. return undefined;
  2205. }
  2206. try {
  2207. let selectUris: Array<string> = [];
  2208. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  2209. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  2210. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  2211. photoSelectOptions.maxSelectNumber = 1;
  2212. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  2213. selectUris = photoSelectResult.photoUris;
  2214. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  2215. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  2216. console.info('file fd: ' + file.fd);
  2217. let name = await MD5.digestSync(this.videoUrl)+'.jpg'
  2218. let imagePath = this.context.filesDir + FileUtil.separator + name
  2219. imagePath = fileUri.getUriFromPath(imagePath)
  2220. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  2221. fileIo.copyFileSync(file.fd, file2.fd)
  2222. fileIo.closeSync(file);
  2223. fileIo.closeSync(file2);
  2224. if (item.filePath == this.currentSong?.filePath) {
  2225. this.cover = imagePath
  2226. }
  2227. if (item) {
  2228. item.pixelMapPath = imagePath
  2229. }
  2230. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  2231. if (success) {
  2232. this.doUpdateData()
  2233. console.log("onecold 更新音乐封面成功,数据库已同步");
  2234. } else {
  2235. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  2236. }
  2237. });
  2238. LogUtil.debug("onecold this.cover =" + this.cover)
  2239. return FileUtil.getFilePath(imagePath); // Return the image path here
  2240. } catch (err) {
  2241. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  2242. return undefined;
  2243. }
  2244. }
  2245. // 拉起picker选择文件管理器
  2246. async callFilePickerSelectFile(): Promise<void> {
  2247. try {
  2248. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  2249. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  2250. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  2251. } else {
  2252. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  2253. }
  2254. let documentPicker = new picker.DocumentViewPicker();
  2255. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  2256. Logger.info(TAG,
  2257. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  2258. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  2259. this.saveVideoDatas(DocumentSelectResult)
  2260. }
  2261. }).catch((err: BusinessError) => {
  2262. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  2263. });
  2264. } catch (err) {
  2265. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  2266. }
  2267. }
  2268. //重命名的对话框
  2269. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  2270. if(!item.filePath.includes(this.packName)){
  2271. ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限重命名')
  2272. return
  2273. }
  2274. DialogHelper.showTextInputDialog({
  2275. title: '重命名',
  2276. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  2277. maskColor: Color.Transparent,
  2278. backgroundColor: Color.Grey,
  2279. transition: AnimationHelper.transitionInDown(666),
  2280. onChange: (text) => {
  2281. console.error("onChange: " + text);
  2282. },
  2283. onAction: (action, dialogId, content) => {
  2284. // ToastUtil.showToast('content = ' +content)
  2285. if (action == DialogAction.TWO) {
  2286. const newName = content
  2287. const newPath = this.currentPath + '/' + newName
  2288. console.log("onecold item = " + item.type);
  2289. this.doReName(index, newName, filePath, newPath, item)
  2290. }
  2291. }
  2292. })
  2293. }
  2294. //剪切 移动到另个文件夹的对话框
  2295. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  2296. Logger.info('onecold showCutDialog')
  2297. let mList: Array<string> = []
  2298. let rPath = this.rootPath
  2299. if (isCurrent) {
  2300. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2301. rPath = this.currentPath
  2302. } else {
  2303. mList = Utility.getNameList(this.dirList);
  2304. rPath = this.rootPath
  2305. }
  2306. let dataBean = new BubbleBean()
  2307. dataBean.data = mList
  2308. dataBean.color = this.themeColor
  2309. dataBean.onItemClick = (i) => {
  2310. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  2311. Logger.info('newPath = ' + newPath)
  2312. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  2313. ToastUtil.showToast('移动成功')
  2314. this.table.deleteData(item, () => {
  2315. });
  2316. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2317. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2318. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2319. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2320. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2321. this.table.insert(newItem, (id: number) => {
  2322. //加入数据库
  2323. });
  2324. }
  2325. this.cache.delete(this.currentPath); // 删除原路径缓存
  2326. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  2327. this.getSortedFiles(this.currentPath, true)
  2328. }).catch((error: BusinessError) => {
  2329. console.error(error.message);
  2330. });
  2331. XPopup.dismissTop()
  2332. }
  2333. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  2334. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  2335. popupPosition = PopupPosition.TOP
  2336. }
  2337. if (index <= 3) {
  2338. popupPosition = PopupPosition.BOTTOM
  2339. }
  2340. let pup: XPopup
  2341. if (this.isDarkMode) {
  2342. pup = XPopup.Builder()
  2343. .setPopupPosition(popupPosition)
  2344. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  2345. .setBackgroundColor(Color.Black)
  2346. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2347. .show()
  2348. } else {
  2349. pup = XPopup.Builder()
  2350. .setPopupPosition(popupPosition)
  2351. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  2352. .setBackgroundColor(Color.White)
  2353. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2354. .show()
  2355. }
  2356. }
  2357. //复制 到另个文件夹的对话框
  2358. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  2359. Logger.info('onecoldv showCopyDialog')
  2360. let mList: Array<string> = []
  2361. let rPath = this.rootPath
  2362. if (isCurrent) {
  2363. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2364. rPath = this.currentPath
  2365. } else {
  2366. mList = Utility.getNameList(this.dirList);
  2367. rPath = this.rootPath
  2368. }
  2369. let dataBean = new BubbleBean()
  2370. dataBean.data = mList
  2371. dataBean.isCopy = true
  2372. dataBean.color = this.themeColor
  2373. dataBean.onItemClick = (i) => {
  2374. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  2375. Logger.info('newPath = ' + newPath)
  2376. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  2377. ToastUtil.showToast('复制成功')
  2378. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  2379. this.getSortedFiles(this.currentPath)
  2380. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2381. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2382. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2383. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2384. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2385. this.table.insert(newItem, (id: number) => {
  2386. //加入数据库
  2387. });
  2388. }
  2389. }).catch((error: BusinessError) => {
  2390. console.error(error.message);
  2391. });
  2392. XPopup.dismissTop()
  2393. }
  2394. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  2395. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  2396. popupPosition = PopupPosition.TOP
  2397. }
  2398. if (index <= 3) {
  2399. popupPosition = PopupPosition.BOTTOM
  2400. }
  2401. let pup: XPopup
  2402. if (this.isDarkMode) {
  2403. pup = XPopup.Builder()
  2404. .setPopupPosition(popupPosition)
  2405. .atView(id)
  2406. .setMaxHeight('60%')
  2407. .setBackgroundColor(Color.Black)
  2408. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2409. .show();
  2410. } else {
  2411. pup = XPopup.Builder()
  2412. .setPopupPosition(popupPosition)
  2413. .atView(id)
  2414. .setMaxHeight('60%')
  2415. .setBackgroundColor(Color.White)
  2416. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2417. .show();
  2418. }
  2419. }
  2420. //重命名索引index的视频
  2421. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  2422. FileUtil.rename(oldPath, newPath).then(async () => {
  2423. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2424. if (info.type === CommonConstants.TYPE_IS_DIR) {
  2425. //如果是文件夹先删除源数据,再添加新数据
  2426. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  2427. if (success) {
  2428. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  2429. } else {
  2430. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  2431. }
  2432. });
  2433. this.scanDirectory(newPath)
  2434. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  2435. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  2436. if (success) {
  2437. console.log(" onecold 重命名成功,数据库已同步");
  2438. } else {
  2439. console.error(" onecold 重命名数据库失败原因: " + error);
  2440. }
  2441. });
  2442. }
  2443. let mediaItem: VideoItem =
  2444. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2445. this.videoLocalList[index] = mediaItem;
  2446. }
  2447. this.cache.delete(this.currentPath)
  2448. this.getSortedFiles(this.currentPath, true)
  2449. }).catch((error: BusinessError) => {
  2450. console.error(error.message);
  2451. });
  2452. }
  2453. build() {
  2454. Stack() {
  2455. this.ContentBuild()
  2456. Stack() {
  2457. Column()
  2458. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  2459. height: '95%',
  2460. dragBar: true,
  2461. showClose: true,
  2462. blurStyle: BlurStyle.Thin,
  2463. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  2464. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  2465. title: {
  2466. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  2467. + `(${this.songList.length}首)`
  2468. }
  2469. })
  2470. }
  2471. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  2472. modalTransition:ModalTransition.DEFAULT,
  2473. onWillDisappear: () => {
  2474. this.setShowPlayFalse()
  2475. },
  2476. })
  2477. }
  2478. .alignContent(Alignment.Bottom)
  2479. .width('100%')
  2480. .height('100%')
  2481. }
  2482. @Builder
  2483. ContentBuild() {
  2484. Scroll() {
  2485. Column() {
  2486. Stack() {
  2487. //libraryname加上去后onKeyEvent监听不了,因为目前的解决方案是上面的XComponent,去掉libraryname
  2488. XComponent({ id: 'for_onKeyEvent',type: XComponentType.SURFACE,
  2489. controller: this.xcomponentController })
  2490. .onLoad(async (event?: object) => {
  2491. })
  2492. .focusable(true)
  2493. .height(0)
  2494. .focusOnTouch(true)
  2495. .defaultFocus(true) // 自动获取键盘焦点
  2496. .onKeyEvent((event?: KeyEvent) => {
  2497. console.info('onecold点击 onKeyEvent')
  2498. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  2499. if (!event || event.type !== KeyType.Down) {
  2500. return;
  2501. }
  2502. console.info('onecold点击 onKeyEvent event.keyCode: ' + event.keyCode)
  2503. //空格键 Space key controls pause/play
  2504. if (event.keyCode === KeyCode.KEYCODE_SPACE|| event.keyCode === KeyCode.KEYCODE_MEDIA_PLAY_PAUSE) {
  2505. this.playOrPause()
  2506. }
  2507. if (event.keyCode === KeyCode.KEYCODE_DPAD_UP) {
  2508. this.playPrevious()
  2509. }
  2510. if (event.keyCode === KeyCode.KEYCODE_DPAD_DOWN) {
  2511. this.playNext()
  2512. }
  2513. // Right-click to fast forward
  2514. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  2515. this.fastForward()
  2516. }
  2517. // Left-click to rewind
  2518. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  2519. this.backForward()
  2520. }
  2521. })
  2522. Column() {
  2523. XComponent({
  2524. id: 'xcomponentId',
  2525. type: 'surface',
  2526. libraryname: 'ijkplayer_napi',
  2527. controller: this.xcomponentController
  2528. })
  2529. .onLoad((event?: object) => {
  2530. if (!!event) {
  2531. this.initDelayPlay(event);
  2532. }
  2533. })
  2534. .onDestroy(() => {
  2535. })
  2536. .width('100%')// .width(this.videoWidth)
  2537. .aspectRatio(this.videoAspectRatio)
  2538. }
  2539. .aspectRatio(this.videoAspectRatio)
  2540. .justifyContent(FlexAlign.Center)
  2541. .backgroundColor(Color.Transparent)
  2542. .visibility(Visibility.Hidden)
  2543. .height(CommonConstants.FULL_PERCENT)
  2544. .width(CommonConstants.FULL_PERCENT)
  2545. .bindSheet($$this.isABSheet, this.ABLoopSheet(), {
  2546. height:this.isLandscape?'80%': '43%',
  2547. dragBar: true,
  2548. showClose: true,
  2549. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  2550. blurStyle:BlurStyle.Thin,
  2551. backgroundColor:Color.Transparent,
  2552. title: { title: 'AB循环' }
  2553. })
  2554. Stack() {
  2555. Column() {
  2556. if(this.twoFingerType==4){
  2557. this.getWaterView()
  2558. }else{
  2559. if(this.isGridMusic){
  2560. this.getGridView()
  2561. }else {
  2562. this.getListView()
  2563. }
  2564. }
  2565. if (this.modeType ==0||this.modeType==4) {
  2566. Column() {
  2567. emptyView(this.themeColor)
  2568. }
  2569. .onClick(()=>{
  2570. this.asyncCurrentPathOnlyFile()
  2571. })
  2572. .position({ top: 200 })
  2573. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  2574. .animation({ duration: 500 }),
  2575. TransitionEffect.scale({ x: 0, y: 0 })))
  2576. .justifyContent(FlexAlign.Center)
  2577. .opacity(this.isZero ? 1 : 0)
  2578. .visibility(this.isZero && !this.isFavMusic && !this.isHistory
  2579. ? Visibility.Visible : Visibility.None)
  2580. .animation({
  2581. duration: 500,
  2582. curve: Curve.Friction // 可选动画曲线
  2583. })
  2584. .width('100%')
  2585. }
  2586. }
  2587. .layoutWeight(1)
  2588. .height('100%')
  2589. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  2590. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  2591. .onDrop((event?: DragEvent) => {
  2592. try {
  2593. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  2594. if (dragData !== undefined) {
  2595. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  2596. if (records.length > 0) {
  2597. for (let i = 0; i < records.length; i++) {
  2598. let types = records[i].getTypes();
  2599. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  2600. const fileUriUds =
  2601. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  2602. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  2603. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  2604. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  2605. this.targetFile = fileUriUds.oriUri;
  2606. this.saveVideoDatas([this.targetFile])
  2607. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  2608. }
  2609. }
  2610. }
  2611. } else {
  2612. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  2613. }
  2614. } else {
  2615. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  2616. }
  2617. } catch (error) {
  2618. const err = error as BusinessError;
  2619. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  2620. }
  2621. })
  2622. // 右侧居中的字母表索引
  2623. if(this.showZMIndex){
  2624. this.indexBuilder()
  2625. }
  2626. this.topTitleBar()
  2627. }
  2628. .alignContent(Alignment.Top)
  2629. .layoutWeight(1)
  2630. .height('100%')
  2631. Row() {
  2632. Button(this.isAllSelected ? '反选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  2633. .width(45)
  2634. .height(45)
  2635. .fontSize(10)
  2636. .margin({ top: 10, bottom: 10, right: 6 })
  2637. .backgroundColor(this.themeColor)
  2638. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2639. .onClick(() => {
  2640. if (this.isAllSelected) {
  2641. // 全不选
  2642. this.selectedFiles = [];
  2643. } else {
  2644. // 全选
  2645. this.selectedFiles = [...this.getCurFileList()];
  2646. }
  2647. this.isAllSelected = !this.isAllSelected;
  2648. })
  2649. Button('内嵌标签', { type: ButtonType.Capsule, stateEffect: true })
  2650. .width(72)
  2651. .height(45)
  2652. .fontSize(10)
  2653. .margin({ top: 10, bottom: 10, right: 6 })
  2654. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2655. .backgroundColor(this.themeColor)
  2656. .bindContentCover($$this.isOneKeyTags, this.TagsContentCoverBuilder(), {
  2657. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2658. })
  2659. .onClick(() => {
  2660. // if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  2661. this.isOneKeyTags = !this.isOneKeyTags
  2662. // }else{
  2663. // ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限批量内嵌标签,导入的时候请勾选复制一份。')
  2664. // }
  2665. })
  2666. Button('合并', { type: ButtonType.Circle, stateEffect: true })
  2667. .width(45)
  2668. .height(45)
  2669. .fontSize(10)
  2670. .margin({ top: 10, bottom: 10, right: 6 })
  2671. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2672. .backgroundColor(this.themeColor)
  2673. .bindContentCover($$this.isMergeAudio, this.MergeAudioBuilder(), {
  2674. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2675. })
  2676. .onClick(() => {
  2677. if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  2678. this.isMergeAudio = !this.isMergeAudio
  2679. }else{
  2680. ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限合并')
  2681. }
  2682. })
  2683. Button('+歌单', { type: ButtonType.Circle, stateEffect: true })
  2684. .width(45)
  2685. .height(45)
  2686. .fontSize(10)
  2687. .margin({ top: 10, bottom: 10, right: 6 })
  2688. .backgroundColor(this.themeColor)
  2689. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2690. .onClick(async () => {
  2691. this.longItemFilePath = ''
  2692. await this.openAddToPlaylistDialog(this.selectedFiles)
  2693. })
  2694. // Button('乱码', { type: ButtonType.Circle, stateEffect: true })
  2695. // .width(45)
  2696. // .height(45)
  2697. // .fontSize(10)
  2698. // .margin({ top: 10, bottom: 10, right: 6 })
  2699. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2700. // .backgroundColor(this.themeColor)
  2701. // .bindContentCover($$this.isFixMessy, this.FixMessyViewBuilder(), {
  2702. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2703. // })
  2704. // .onClick(() => {
  2705. // this.isFixMessy = !this.isFixMessy
  2706. // })
  2707. // Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  2708. // .width('35%')
  2709. // .height(60)
  2710. // .id('music_cut')
  2711. // .margin({ top: 10, bottom: 10, right: 6 })
  2712. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2713. // .backgroundColor(this.themeColor)
  2714. // .onClick(() => {
  2715. // this.showCutDialogForMultipleFiles(false, 'music_cut')
  2716. // })
  2717. //
  2718. // Button('移动', { type: ButtonType.Circle, stateEffect: true })
  2719. // .width('35%')
  2720. // .height(60)
  2721. // .id('music_cut_current')
  2722. // .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  2723. // .margin({ top: 10, bottom: 10, right: 6 })
  2724. // .backgroundColor(this.themeColor)
  2725. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2726. // .onClick(() => {
  2727. //
  2728. // this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  2729. // })
  2730. // Button('复制', { type: ButtonType.Circle, stateEffect: true })
  2731. // .width('35%')
  2732. // .height(60)
  2733. // .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  2734. // .margin({ top: 10, bottom: 10, right: 6 })
  2735. // .backgroundColor(this.themeColor)
  2736. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2737. // .onClick(() => {
  2738. // this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  2739. // })
  2740. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  2741. .width(45)
  2742. .height(45)
  2743. .fontSize(10)
  2744. .margin({ top: 10, bottom: 10, right: 6 })
  2745. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  2746. .backgroundColor(this.themeColor)
  2747. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2748. .onClick(() => {
  2749. this.showWarnIsDelete()
  2750. })
  2751. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  2752. .width(45)
  2753. .height(45)
  2754. .fontSize(10)
  2755. .margin({ top: 10, bottom: 10, right: 6 })
  2756. .backgroundColor(this.themeColor)
  2757. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2758. .onClick(() => {
  2759. this.selectedFiles = [];
  2760. this.isAllSelected = false
  2761. this.isMultiSelect = false
  2762. })
  2763. }
  2764. .width('100%')
  2765. .justifyContent(FlexAlign.Center)
  2766. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  2767. .opacity(this.isMultiSelect ? 1 : 0)
  2768. .animation({
  2769. duration: 666,
  2770. curve: 'ease-in-out' // 可选动画曲线
  2771. })
  2772. .position({ bottom: 20 }) // 将 Row 固定在底部
  2773. }
  2774. .width('100%')
  2775. .height('100%')
  2776. .alignContent(Alignment.Top)
  2777. }
  2778. .width('100%')
  2779. .height('100%')
  2780. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  2781. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  2782. .backgroundImagePosition(Alignment.Center)
  2783. .backdropBlur(this.blurValue)
  2784. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  2785. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  2786. }
  2787. }
  2788. //字母表索引
  2789. @Builder
  2790. indexBuilder(){
  2791. if(this.enableShowAlphabet){
  2792. Column({space: 5}){
  2793. if(this.isShowAlphaBet&&!(this.modeType==2&&!this.isCanBack)
  2794. &&!(this.modeType==3&&!this.isCanBack)){
  2795. AlphabetIndexer({arrayValue: this.alphaBet,selected: this.selectAlphaBetIndex})
  2796. .attributeModifier(this.alphaBetStyle)
  2797. .usingPopup(this.isTouchingAlphaBet)
  2798. .onAreaChange((old_value,new_value)=>{
  2799. this.alphabetHeight = new_value.height as number
  2800. })
  2801. .popupPosition({
  2802. x: 40,
  2803. y: this.alphabetHeight / 2
  2804. })
  2805. .onSelect((index: number) => {
  2806. this.onSelectIndexItem(this.alphaBet[index])
  2807. })
  2808. .onTouch((event: TouchEvent) =>{
  2809. this.isShowAlphaBet = true
  2810. if(event.type === TouchType.Up || event.type === TouchType.Cancel){
  2811. this.isTouchingAlphaBet = false
  2812. }else{
  2813. this.isTouchingAlphaBet = true
  2814. }
  2815. })
  2816. .transition(
  2817. TransitionEffect.translate({x: 10})
  2818. .combine(TransitionEffect.opacity(0.1))
  2819. .animation({
  2820. duration: 150,
  2821. curve: Curve.EaseInOut,
  2822. })
  2823. )
  2824. }else{
  2825. Blank()
  2826. .layoutWeight(1)
  2827. }
  2828. // ListLocateButton()
  2829. // .onClick(() =>{
  2830. // this.locateSong()
  2831. // })
  2832. // .clickEffect({level:ClickEffectLevel.LIGHT,scale: 0.5})
  2833. // .margin({
  2834. // bottom: 10
  2835. // })
  2836. }
  2837. .padding({
  2838. bottom: 0
  2839. })
  2840. .position({x:'92%'})
  2841. .height('100%')
  2842. .justifyContent(FlexAlign.Center)
  2843. }
  2844. }
  2845. onSelectIndexItem(letter: string) {
  2846. let songs = this.videoLocalList
  2847. let targetIndex = -1;
  2848. for (let i = 0; i < songs.length; i++) {
  2849. let song = songs[i]
  2850. let text = this.isShowFileName?song.fileName:
  2851. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  2852. if(this.sortType === 0||this.sortType==1){
  2853. text = song.artist
  2854. }else if(this.sortType === 2||this.sortType==3){
  2855. text = song.album
  2856. }
  2857. if(text){
  2858. let firstPinyin = getFirstLetter(text)
  2859. if (firstPinyin&&firstPinyin === letter) {
  2860. targetIndex = i;
  2861. break;
  2862. }
  2863. }
  2864. }
  2865. if (targetIndex !== -1) {
  2866. this.listScroller.scrollToIndex(targetIndex);
  2867. }
  2868. }
  2869. // 找到对应字母表的索引
  2870. findAlphaBetIndex(song: VideoItem):number{
  2871. let text = this.isShowFileName?song.fileName:
  2872. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  2873. if(this.sortType === 0||this.sortType==1){
  2874. text = song.artist
  2875. }else if(this.sortType === 2||this.sortType==3){
  2876. text = song.album
  2877. }
  2878. if(text){
  2879. let firstLetter = getFirstLetter(text)
  2880. for(let i=0;i<this.alphaBet.length;i++){
  2881. if(this.alphaBet[i] === firstLetter){
  2882. return i
  2883. }
  2884. }
  2885. }
  2886. return 0
  2887. }
  2888. async setAlphaBet(){
  2889. if(!this.showZMIndex){
  2890. return
  2891. }
  2892. return new Promise<void>((resolve,reject) => {
  2893. try {
  2894. let songs = this.videoLocalList
  2895. if(songs.length > 40000){
  2896. this.alphaBet = []
  2897. resolve()
  2898. return
  2899. }
  2900. let alphabetSet = new Set<string>();
  2901. for (let song of songs) {
  2902. let text = this.isShowFileName?song.fileName:
  2903. (song.type!=CommonConstants.TYPE_IS_DIR&&song.pyStr)?song.pyStr:song.name
  2904. if(this.sortType === 0||this.sortType==1){
  2905. text = song.artist
  2906. }else if(this.sortType === 2||this.sortType==3){
  2907. text = song.album
  2908. }
  2909. if(text){
  2910. let firstPinyin = getFirstLetter(text)
  2911. if(!alphabetSet.has(firstPinyin)){
  2912. alphabetSet.add(firstPinyin)
  2913. }
  2914. }
  2915. // const pyStr = song.pyStr
  2916. // if(pyStr){
  2917. // if(!alphabetSet.has(pyStr)){
  2918. // alphabetSet.add(pyStr)
  2919. // }
  2920. // }
  2921. }
  2922. this.alphaBet = Array.from(alphabetSet).sort((a,b)=>{
  2923. if(this.sortType ===4||this.sortType==0||this.sortType==2||this.sortType==6){
  2924. return a.localeCompare(b)
  2925. }else{
  2926. return b.localeCompare(a)
  2927. }
  2928. })
  2929. if(this.videoLocalList.length > 0){
  2930. this.listScroller.scrollToIndex(0)
  2931. this.selectAlphaBetIndex = 0
  2932. }
  2933. resolve()
  2934. }catch (e) {
  2935. console.error('testTag','排序字母表出错',JSON.stringify(e))
  2936. resolve()
  2937. }
  2938. })
  2939. }
  2940. @Builder
  2941. topTitleBar(){
  2942. Column() {
  2943. Row({ space: 15 }) {
  2944. if (!this.isSearchMode ) {
  2945. //左侧滑动按钮
  2946. Button({ type: ButtonType.Circle, stateEffect: true }) {
  2947. SymbolGlyph(this.rightTopImage)
  2948. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  2949. }
  2950. .attributeModifier(new ButtonFancyModifier(40, 40))
  2951. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  2952. .animation({ duration: 300, curve: Curve.Ease })
  2953. .onClick(() => {
  2954. this.doSwipBack()
  2955. })
  2956. .attributeModifier(new ShadowModifier())
  2957. .zIndex(0)
  2958. }else{
  2959. //左侧搜索返回按钮
  2960. Button({ type: ButtonType.Circle, stateEffect: true }) {
  2961. SymbolGlyph($r('sys.symbol.chevron_left'))
  2962. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  2963. }
  2964. .attributeModifier(new ButtonFancyModifier(40, 40))
  2965. .margin({bottom:5})
  2966. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  2967. .animation({ duration: 300, curve: Curve.Ease })
  2968. .onClick(() => {
  2969. this.isSearchMode = false
  2970. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  2971. this.searchText = ''
  2972. this.getSortedFiles(this.currentPath)
  2973. return
  2974. }
  2975. this.onSearchInput('')
  2976. })
  2977. .attributeModifier(new ShadowModifier())
  2978. .zIndex(0)
  2979. }
  2980. if (!this.isSearchMode) {
  2981. Text(this.modeType==1?`${this.titleName}(${this.mediaKuCount}首)`:this.titleName)
  2982. .margin({left:3,right:10})
  2983. .fontColor($r('app.color.text_color'))
  2984. .fontSize(this.twoFingerType==3?17:16)
  2985. .maxLines(1)
  2986. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  2987. .layoutWeight(1)
  2988. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  2989. }
  2990. //搜索框
  2991. Search({ controller: this.searchController,value: this.searchText, placeholder: '搜索标题、艺术家...' })
  2992. .searchButton('搜索',{fontColor:this.themeColor})
  2993. .searchIcon({
  2994. src: $r('sys.media.ohos_ic_public_search_filled')
  2995. })
  2996. .cancelButton({
  2997. style: CancelButtonStyle.CONSTANT,
  2998. icon: {
  2999. src: $r('sys.media.ohos_ic_public_cancel_filled')
  3000. }
  3001. })
  3002. .layoutWeight(1)
  3003. .height(40)
  3004. .maxLength(20)
  3005. .backgroundColor(this.isDarkMode?Color.Black:'#F5F5F5')
  3006. .placeholderColor(Color.Grey)
  3007. .placeholderFont({ size: 14, weight: 400 })
  3008. .textFont({ size: 14, weight: 400 })
  3009. .onSubmit((value: string) => {
  3010. console.log('onecold onSubmit ='+value)
  3011. this.searchController.stopEditing()
  3012. this.onSearchInput(this.searchText);
  3013. })
  3014. .onChange((value: string) => {
  3015. console.log('onecold onChange ='+value)
  3016. this.onSearchInput(value);
  3017. })
  3018. .visibility(this.isSearchMode?Visibility.Visible:Visibility.None)
  3019. .animation({ duration: 300, curve: Curve.Ease })
  3020. //搜索按钮
  3021. if (!this.isSearchMode) {
  3022. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3023. SymbolGlyph($r('sys.symbol.magnifyingglass'))
  3024. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3025. }
  3026. .attributeModifier(new ButtonFancyModifier(40, 40))
  3027. .animation({ duration: 300, curve: Curve.Ease })
  3028. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3029. .attributeModifier(new ShadowModifier())
  3030. .zIndex(0)
  3031. .onClick(()=>{
  3032. this.isSearchMode = true
  3033. })
  3034. //排序按钮
  3035. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3036. SymbolGlyph($r('sys.symbol.list_number'))
  3037. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3038. }
  3039. .attributeModifier(new ButtonFancyModifier(40, 40))
  3040. .animation({ duration: 300, curve: Curve.Ease })
  3041. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3042. .bindMenu((this.modeType==2&&!this.isCanBack)||(this.modeType==3&&!this.isCanBack)
  3043. ?this.SortMenuForArtistAblumBuilder:this.SortMenuBuilder)
  3044. .attributeModifier(new ShadowModifier())
  3045. .zIndex(0)
  3046. //添加按钮
  3047. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3048. SymbolGlyph($r('sys.symbol.plus'))
  3049. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3050. }
  3051. .attributeModifier(new ButtonFancyModifier(40, 40))
  3052. .animation({ duration: 300, curve: Curve.Ease })
  3053. .visibility(this.modeType==0||this.modeType==1?Visibility.Visible:Visibility.None)
  3054. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3055. .bindSheet($$this.showAddSheet, this.addSheet(), {
  3056. height: SheetSize.FIT_CONTENT,
  3057. dragBar: true,
  3058. showClose: true,
  3059. preferType: SheetType.CENTER ,
  3060. title: {
  3061. title: '导入音乐'
  3062. }
  3063. })
  3064. .onClick(() => {
  3065. this.showAddSheet = !this.showAddSheet;
  3066. })
  3067. .attributeModifier(new ShadowModifier())
  3068. .zIndex(0)
  3069. }
  3070. }
  3071. }
  3072. .padding({ top: this.topSafeHeight+10, left: 10, right: 10 })
  3073. .width('100%')
  3074. .visibility(this.isShowTitleBar?Visibility.Visible:
  3075. this.autoHideTitle?Visibility.None:Visibility.Visible)
  3076. .animation({
  3077. duration: 500,
  3078. curve: Curve.Friction // 可选动画曲线
  3079. })
  3080. }
  3081. @Builder
  3082. addSheet() {
  3083. Scroll() {
  3084. Column() {
  3085. Column() {
  3086. Row() {
  3087. SymbolGlyph($r('sys.symbol.info_circle'))
  3088. .fontSize(22)
  3089. .fontColor([this.themeColor])
  3090. .alignSelf(ItemAlign.Center)
  3091. .margin({ left: 8 })
  3092. Text('导入音乐复制到DownLoad目录')
  3093. .margin({ left: 8 })
  3094. .fontSize(14)
  3095. .fontColor($r('app.color.text_color'))
  3096. .fontWeight(480)
  3097. .layoutWeight(1)
  3098. Toggle({ type: ToggleType.Switch, isOn: this.isCopyFileToDownLoad })
  3099. .selectedColor(this.themeColor)
  3100. .switchPointColor(Color.White)
  3101. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  3102. .margin({ right: 2 })
  3103. .onChange((checked: boolean) => {
  3104. this.isCopyFileToDownLoad = checked;
  3105. PreferencesUtil.put(SettingPage.IS_COPYFILE_TO_DOWNLOAD, this.isCopyFileToDownLoad)
  3106. })
  3107. .width(50)
  3108. .height(30);
  3109. }
  3110. .height(72)
  3111. .padding({ left:8,right:8 })
  3112. }
  3113. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3114. .backgroundColor($r('app.color.start_window_background'))
  3115. .borderRadius(15)
  3116. .width('85%')
  3117. .margin({
  3118. top: 10,
  3119. bottom: 10
  3120. })
  3121. .padding(0)
  3122. .border({
  3123. color: Color.White,
  3124. width: 1.8
  3125. })
  3126. Menu() {
  3127. MenuItem({
  3128. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder_badge_plus')),
  3129. content: "新建文件夹"
  3130. })
  3131. .backgroundColor($r('app.color.silvery'))
  3132. .border({
  3133. width: { bottom: 1 },
  3134. color: '#12ec5c87'
  3135. })
  3136. .margin(10)
  3137. .height(60)
  3138. .padding({left:15,right:15})
  3139. .onClick(async () => {
  3140. this.showMkDialog()
  3141. this.showAddSheet = !this.showAddSheet
  3142. })
  3143. MenuItem({
  3144. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder')),
  3145. content: $r('app.string.import_from_files')
  3146. })
  3147. .padding({left:15,right:15})
  3148. .backgroundColor($r('app.color.silvery'))
  3149. .border({
  3150. width: { bottom: 1 },
  3151. color: '#12ec5c87'
  3152. })
  3153. .margin(10)
  3154. .height(60)
  3155. .onClick(async () => {
  3156. this.callFilePickerSelectFile()
  3157. this.showAddSheet = !this.showAddSheet
  3158. })
  3159. MenuItem({
  3160. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square')),
  3161. content: '全选导入'
  3162. // content: '从下载文件夹导入(路径:Download/' +
  3163. // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
  3164. })
  3165. .padding({left:15,right:15})
  3166. .backgroundColor($r('app.color.silvery'))
  3167. .border({
  3168. width: { bottom: 1 },
  3169. color: '#12ec5c87'
  3170. })
  3171. .margin(10)
  3172. .height(60)
  3173. .onClick(async () => {
  3174. this.goSelectMusic()
  3175. this.showAddSheet = !this.showAddSheet
  3176. })
  3177. MenuItem({
  3178. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.save')),
  3179. content: '自动导入教程'
  3180. })
  3181. .padding({left:15,right:15})
  3182. .backgroundColor($r('app.color.silvery'))
  3183. .border({
  3184. width: { bottom: 1 },
  3185. color: '#12ec5c87'
  3186. })
  3187. .margin(10)
  3188. .height(60)
  3189. .onClick(async () => {
  3190. this.showTips()
  3191. this.showAddSheet = !this.showAddSheet
  3192. })
  3193. MenuItem({
  3194. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.questionmark_circle')),
  3195. content: '导入疑问'
  3196. })
  3197. .height(60)
  3198. .padding({left:15,right:15})
  3199. .backgroundColor($r('app.color.silvery'))
  3200. .border({
  3201. width: { bottom: 1 },
  3202. color: '#12ec5c87'
  3203. })
  3204. .margin(10)
  3205. .onClick(async () => {
  3206. this.showProblomTips()
  3207. this.showAddSheet = !this.showAddSheet
  3208. })
  3209. }.attributeModifier(new MenuModifier())
  3210. .margin({bottom:30})
  3211. .width('90%')
  3212. .borderRadius(15)
  3213. }
  3214. .layoutWeight(1)
  3215. }
  3216. }
  3217. async showProblomTips() {
  3218. try {
  3219. this.getUIContext().getPromptAction().showDialog({
  3220. title: '导入疑问',
  3221. message:'为什么有些歌曲导入成功后,内嵌标签或者其他功能不能用?:\n\n1、由于鸿蒙系统的安全策略,文件权限不够,请将文件移动到Download/天天静听目录下。' +
  3222. '这样内嵌标签功能就没有权限问题。\n\n2、导入可以也选择不复制,这样可以省略空间。\n\n',
  3223. buttons: [
  3224. {
  3225. text: '知道了',
  3226. color: '#000000'
  3227. },
  3228. ]
  3229. }, (err, data) => {
  3230. if (err) {
  3231. console.error('showDialog err: ' + err);
  3232. return;
  3233. }
  3234. console.info('showDialog success callback, click button: ' + data.index);
  3235. });
  3236. } catch (error) {
  3237. let message = (error as BusinessError).message;
  3238. let code = (error as BusinessError).code;
  3239. console.error(`showDialog args error code is ${code}, message is ${message}`);
  3240. };
  3241. }
  3242. @Builder
  3243. TagsContentCoverBuilder() {
  3244. Scroll() {
  3245. Column() {
  3246. TagsContentCover(
  3247. {
  3248. selectedFiles:this.selectedFiles,
  3249. isOneKeyTags:this.isOneKeyTags,
  3250. onSeePath:(path:string)=>{
  3251. this.modeType = 0
  3252. this.deleteCache(path)
  3253. this.getSortedFiles(path)
  3254. },
  3255. onTagsResult:(result: boolean,deleteCache_path?:string)=>{
  3256. this.isMultiSelect = false
  3257. if(result){//如果嵌入成功,更新数据
  3258. this.listRefreshKey++
  3259. setTimeout(()=>{
  3260. this.doUpdateData()
  3261. },500)
  3262. }
  3263. console.info('onecold onTagsResult deleteCache_path =' +deleteCache_path)
  3264. if(deleteCache_path){
  3265. this.deleteCache(deleteCache_path)
  3266. }
  3267. }
  3268. }
  3269. )
  3270. }
  3271. }
  3272. .width('100%')
  3273. .height('100%')
  3274. }
  3275. @Builder
  3276. FixMessyViewBuilder() {
  3277. Scroll() {
  3278. Column() {
  3279. FixMessyView(
  3280. {
  3281. selectedFiles:this.selectedFiles,
  3282. isFixMessy:this.isFixMessy,
  3283. onFixResult:(result: boolean)=>{
  3284. this.isMultiSelect = false
  3285. if(result){//如果嵌入成功,更新数据
  3286. this.deleteCache(this.currentPath)
  3287. this.doUpdateData()
  3288. }
  3289. }
  3290. }
  3291. )
  3292. }
  3293. }
  3294. .width('100%')
  3295. .height('100%')
  3296. }
  3297. //剪辑音频
  3298. @Builder
  3299. EditAudioBuilder(item:VideoItem) {
  3300. Scroll() {
  3301. Column() {
  3302. EditAudio(
  3303. {
  3304. mVideoItem:item,
  3305. currentPath:this.currentPath,
  3306. videoUrl:this.videoUrl,
  3307. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3308. currentTime:this.currentTime,
  3309. progressValue:this.progressValue,
  3310. onBack:()=>{
  3311. this.isEditAudio = !this.isEditAudio
  3312. },
  3313. onSeeOutputPath:(outPutPath:string)=>{
  3314. this.isEditAudio = !this.isEditAudio
  3315. this.longItemFilePath = ''
  3316. this.modeType = 0
  3317. this.isShowFileName = true
  3318. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3319. },
  3320. onPlayOrPause:()=>{
  3321. if(this.videoUrl==item.filePath){
  3322. this.playOrPause()
  3323. }else{//如果不是当前播放的,则播放该文件
  3324. this.videoUrl==item.filePath
  3325. this.doPlay(item,0,false,true)
  3326. }
  3327. },
  3328. onSliderChange:(value:number)=>{
  3329. if(this.videoUrl!=item.filePath){
  3330. this.videoUrl==item.filePath
  3331. return
  3332. }
  3333. this.isSeekTo = true;
  3334. this.mDestroyPage = false;
  3335. this.showLoadIng();
  3336. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  3337. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3338. this.seekTo(seekValue + "");
  3339. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  3340. this.isSeekTo = false;
  3341. },
  3342. onResult:(result: boolean,outPath:string)=>{
  3343. if(result){//如果剪辑成功,更新数据
  3344. this.doUpdateData()
  3345. }else{
  3346. ToastUtil.showToast('剪辑失败')
  3347. }
  3348. }
  3349. }
  3350. )
  3351. }
  3352. }
  3353. .width('100%')
  3354. .height('100%')
  3355. }
  3356. //提取伴奏
  3357. @Builder
  3358. ConverterBuilder(item:VideoItem) {
  3359. Scroll() {
  3360. Column() {
  3361. AudioFormatConverter(
  3362. {
  3363. mVideoItem:item,
  3364. videoUrl:this.videoUrl,
  3365. currentPath:this.currentPath,
  3366. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3367. currentTime:this.currentTime,
  3368. progressValue:this.progressValue,
  3369. onBack:()=>{
  3370. this.isConverter = !this.isConverter
  3371. this.longItemFilePath = ''
  3372. },
  3373. onPlayOrPause:()=>{
  3374. if(this.videoUrl==item.filePath){
  3375. this.playOrPause()
  3376. }else{//如果不是当前播放的,则播放该文件
  3377. this.videoUrl==item.filePath
  3378. this.doPlay(item,0,false,true)
  3379. }
  3380. },
  3381. onSeeOutputPath:(outPutPath:string)=>{
  3382. this.isConverter = !this.isConverter
  3383. this.longItemFilePath = ''
  3384. this.modeType = 0
  3385. this.isShowFileName = true
  3386. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3387. },
  3388. onSliderChange:(value:number)=>{
  3389. if(this.videoUrl!=item.filePath){
  3390. this.videoUrl==item.filePath
  3391. return
  3392. }
  3393. this.isSeekTo = true;
  3394. this.mDestroyPage = false;
  3395. this.showLoadIng();
  3396. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3397. this.seekTo(seekValue + "");
  3398. this.isSeekTo = false;
  3399. },
  3400. onResult:(result: boolean,outPath:string)=>{
  3401. if(result){//如果成功,更新数据
  3402. this.doUpdateData()
  3403. }else{
  3404. ToastUtil.showToast('格式转化失败')
  3405. }
  3406. }
  3407. }
  3408. )
  3409. }
  3410. }
  3411. .width('100%')
  3412. .height('100%')
  3413. }
  3414. //提取伴奏
  3415. @Builder
  3416. ExtractAccBuilder(item:VideoItem) {
  3417. Scroll() {
  3418. Column() {
  3419. ExtractAccompaniment(
  3420. {
  3421. mVideoItem:item,
  3422. currentPath:this.currentPath,
  3423. videoUrl:this.videoUrl,
  3424. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3425. currentTime:this.currentTime,
  3426. progressValue:this.progressValue,
  3427. onBack:()=>{
  3428. this.isExtractAcc = !this.isExtractAcc
  3429. this.longItemFilePath = ''
  3430. },
  3431. onPlayOrPause:()=>{
  3432. if(this.videoUrl==item.filePath){
  3433. this.playOrPause()
  3434. }else{//如果不是当前播放的,则播放该文件
  3435. this.videoUrl==item.filePath
  3436. this.doPlay(item,0,false,true)
  3437. }
  3438. },
  3439. onSeeOutputPath:(outPutPath:string)=>{
  3440. this.isExtractAcc = !this.isExtractAcc
  3441. this.longItemFilePath = ''
  3442. this.modeType = 0
  3443. this.isShowFileName = true
  3444. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3445. },
  3446. onSliderChange:(value:number)=>{
  3447. if(this.videoUrl!=item.filePath){
  3448. this.videoUrl==item.filePath
  3449. return
  3450. }
  3451. this.isSeekTo = true;
  3452. this.mDestroyPage = false;
  3453. this.showLoadIng();
  3454. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3455. this.seekTo(seekValue + "");
  3456. this.isSeekTo = false;
  3457. },
  3458. onResult:(result: boolean,outPath:string)=>{
  3459. if(result){//如果成功,更新数据
  3460. this.doUpdateData()
  3461. }else{
  3462. ToastUtil.showToast('提取伴奏失败')
  3463. }
  3464. }
  3465. }
  3466. )
  3467. }
  3468. }
  3469. .width('100%')
  3470. .height('100%')
  3471. }
  3472. //AI人声分离
  3473. @Builder
  3474. AiBuilder(item:VideoItem) {
  3475. Scroll() {
  3476. Column() {
  3477. AIVoiceSeparation(
  3478. {
  3479. mVideoItem:item,
  3480. videoUrl:this.videoUrl,
  3481. currentPath:this.currentPath,
  3482. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3483. currentTime:this.currentTime,
  3484. progressValue:this.progressValue,
  3485. onBack:()=>{
  3486. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  3487. this.longItemFilePath = ''
  3488. },
  3489. onPlayOrPause:()=>{
  3490. if(this.videoUrl==item.filePath||this.isPlaying){
  3491. this.playOrPause()
  3492. }else{//如果不是当前播放的,则播放该文件
  3493. this.videoUrl==item.filePath
  3494. this.doPlay(item,0,false,true)
  3495. }
  3496. },
  3497. onPlayPath:(path:string)=>{
  3498. this.videoUrl==path
  3499. const itemP = Utility.getItemByFilePath(this.videoLocalList,path)
  3500. if(itemP)
  3501. this.doPlay(itemP,0,false,true)
  3502. },
  3503. onSeeOutputPath:(outPutPath:string)=>{
  3504. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  3505. this.longItemFilePath = ''
  3506. this.modeType = 0
  3507. this.isShowFileName = true
  3508. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3509. },
  3510. onSliderChange:(value:number)=>{
  3511. if(this.videoUrl!=item.filePath){
  3512. this.videoUrl==item.filePath
  3513. return
  3514. }
  3515. this.isSeekTo = true;
  3516. this.mDestroyPage = false;
  3517. this.showLoadIng();
  3518. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3519. this.seekTo(seekValue + "");
  3520. this.isSeekTo = false;
  3521. },
  3522. onResult:(result: boolean,outPath:string)=>{
  3523. if(result){//如果成功,更新数据
  3524. this.doUpdateData()
  3525. }else{
  3526. ToastUtil.showToast('Ai人声分离失败')
  3527. }
  3528. }
  3529. }
  3530. )
  3531. }
  3532. }
  3533. .width('100%')
  3534. .height('100%')
  3535. }
  3536. //变速变调
  3537. @Builder
  3538. ChangeToneBuilder(item:VideoItem) {
  3539. Scroll() {
  3540. Column() {
  3541. ChangeTone(
  3542. {
  3543. mVideoItem:item,
  3544. currentPath:this.currentPath,
  3545. videoUrl:this.videoUrl,
  3546. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3547. currentTime:this.currentTime,
  3548. progressValue:this.progressValue,
  3549. onBack:()=>{
  3550. this.isChangeTone = !this.isChangeTone
  3551. this.longItemFilePath = ''
  3552. },
  3553. onPlayOrPause:()=>{
  3554. if(this.videoUrl==item.filePath){
  3555. this.playOrPause()
  3556. }else{//如果不是当前播放的,则播放该文件
  3557. this.videoUrl==item.filePath
  3558. this.doPlay(item,0,false,true)
  3559. }
  3560. },
  3561. onSeeOutputPath:(outPutPath:string)=>{
  3562. this.isChangeTone = !this.isChangeTone
  3563. this.longItemFilePath = ''
  3564. this.modeType = 0
  3565. this.isShowFileName = true
  3566. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3567. },
  3568. onSliderChange:(value:number)=>{
  3569. if(this.videoUrl!=item.filePath){
  3570. this.videoUrl==item.filePath
  3571. return
  3572. }
  3573. this.isSeekTo = true;
  3574. this.mDestroyPage = false;
  3575. this.showLoadIng();
  3576. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3577. this.seekTo(seekValue + "");
  3578. this.isSeekTo = false;
  3579. },
  3580. onResult:(result: boolean,outPath:string)=>{
  3581. if(result){//如果成功,更新数据
  3582. this.doUpdateData()
  3583. }else{
  3584. ToastUtil.showToast('变速变调失败')
  3585. }
  3586. }
  3587. }
  3588. )
  3589. }
  3590. }
  3591. .width('100%')
  3592. .height('100%')
  3593. }
  3594. //提取视频中的音频
  3595. @Builder
  3596. extractAudioFromVideoBuilder(item:VideoItem) {
  3597. Scroll() {
  3598. Column() {
  3599. ExtractAudioFromVideo(
  3600. {
  3601. mVideoItem:item,
  3602. currentPath:this.currentPath,
  3603. videoUrl:this.videoUrl,
  3604. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3605. currentTime:this.currentTime,
  3606. progressValue:this.progressValue,
  3607. onBack:()=>{
  3608. this.isExtractAudio = !this.isExtractAudio
  3609. this.longItemFilePath = ''
  3610. },
  3611. onPlayOrPause:()=>{
  3612. if(this.videoUrl==item.filePath){
  3613. this.playOrPause()
  3614. }else{//如果不是当前播放的,则播放该文件
  3615. this.videoUrl==item.filePath
  3616. this.doPlay(item,0,false,true)
  3617. }
  3618. },
  3619. onSeeOutputPath:(outPutPath:string)=>{
  3620. this.isExtractAudio = !this.isExtractAudio
  3621. this.longItemFilePath = ''
  3622. this.modeType = 0
  3623. this.isShowFileName = true
  3624. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3625. },
  3626. onSliderChange:(value:number)=>{
  3627. if(this.videoUrl!=item.filePath){
  3628. this.videoUrl==item.filePath
  3629. return
  3630. }
  3631. this.isSeekTo = true;
  3632. this.mDestroyPage = false;
  3633. this.showLoadIng();
  3634. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3635. this.seekTo(seekValue + "");
  3636. this.isSeekTo = false;
  3637. },
  3638. onResult:(result: boolean,outPath:string)=>{
  3639. if(result){//如果成功,更新数据
  3640. this.doUpdateData()
  3641. }else{
  3642. ToastUtil.showToast('提取音频失败')
  3643. }
  3644. }
  3645. }
  3646. )
  3647. }
  3648. }
  3649. .width('100%')
  3650. .height('100%')
  3651. }
  3652. //合并音频
  3653. @Builder
  3654. MergeAudioBuilder() {
  3655. Scroll() {
  3656. Column() {
  3657. MergeAudio(
  3658. {
  3659. videoUrl:this.videoUrl,
  3660. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3661. currentPath:this.currentPath,
  3662. selectedFiles:this.selectedFiles,
  3663. currentTime:this.currentTime,
  3664. progressValue:this.progressValue,
  3665. onBack:()=>{
  3666. this.isMergeAudio = !this.isMergeAudio
  3667. this.longItemFilePath = ''
  3668. },
  3669. // onPlayPath:(path:string)=>{
  3670. // if(this.videoUrl==item.filePath){
  3671. // this.playOrPause()
  3672. // }else{//如果不是当前播放的,则播放该文件
  3673. // this.videoUrl==item.filePath
  3674. // this.doPlay(item,0,false,true)
  3675. // }
  3676. //
  3677. // },
  3678. onSeeOutputPath:(outPutPath:string)=>{
  3679. this.isMergeAudio = !this.isMergeAudio
  3680. this.longItemFilePath = ''
  3681. this.modeType = 0
  3682. this.isShowFileName = true
  3683. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3684. },
  3685. onResult:(result: boolean,outPath:string)=>{
  3686. if(result){//如果成功,更新数据
  3687. this.doUpdateData()
  3688. }else{
  3689. if(this.selectedFiles.length>=3){
  3690. ToastUtil.showToast('合并数量太多导致失败')
  3691. }else{
  3692. ToastUtil.showToast('合并失败')
  3693. }
  3694. }
  3695. }
  3696. }
  3697. )
  3698. }
  3699. }
  3700. .width('100%')
  3701. .height('100%')
  3702. }
  3703. asyncCurrentPathData() {
  3704. if (this.modeType == 0) {
  3705. workerInstance.postMessage({
  3706. code: 1,
  3707. data1: this.context,
  3708. data2: this.currentPath,
  3709. data3: this.lockPath,
  3710. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  3711. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  3712. });
  3713. }
  3714. }
  3715. // 处理文件选择的函数
  3716. handleFileSelection(item: VideoItem, checked: boolean) {
  3717. if (checked) {
  3718. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  3719. this.selectedFiles.push(item);
  3720. }
  3721. } else {
  3722. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  3723. if (index > -1) {
  3724. this.selectedFiles.splice(index, 1);
  3725. }
  3726. }
  3727. }
  3728. private deleteComponentId: number = 0
  3729. //多选删除文件
  3730. showWarnIsDelete(){
  3731. this.getUIContext().getPromptAction().openCustomDialog({
  3732. builder: () => {
  3733. this.deleteComptentBuilder()
  3734. },
  3735. isModal:true,
  3736. showInSubWindow:false,
  3737. maskColor: Color.Transparent,
  3738. dialogTransition: // 设置弹窗内容显示的过渡效果
  3739. TransitionEffect.translate({ x: 0, y: 290, z: 0 })
  3740. .animation({ duration: 600, curve: Curve.Smooth }),
  3741. maskTransition: // 设置蒙层显示的过渡效果
  3742. TransitionEffect.opacity(0)
  3743. .animation({ duration: 600, curve: Curve.Smooth })
  3744. }).then((dialogId: number) => {
  3745. this.deleteComponentId = dialogId
  3746. })
  3747. .catch((error: BusinessError) => {
  3748. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  3749. })
  3750. }
  3751. @Builder
  3752. deleteComptentBuilder(){
  3753. DeleteComptent({
  3754. selectedFiles:this.selectedFiles,
  3755. onCancel:()=>{
  3756. this.isMultiSelect = false
  3757. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  3758. },
  3759. onDeleteResult:(result: boolean)=>{
  3760. this.isMultiSelect = false
  3761. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  3762. if(result){//如果删除成功,更新数据
  3763. this.selectedFiles = [];
  3764. this.isAllSelected = false
  3765. this.cache.delete(this.currentPath);
  3766. this.getSortedFiles(this.currentPath, true);
  3767. }
  3768. }
  3769. })
  3770. }
  3771. //多选移动文件
  3772. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  3773. Logger.info('onecold showCutDialogForMultipleFiles')
  3774. let mList: Array<string> = []
  3775. let rPath = this.rootPath
  3776. if (isCurrent) {
  3777. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  3778. rPath = this.currentPath
  3779. } else {
  3780. mList = Utility.getNameList(this.dirList);
  3781. rPath = this.rootPath
  3782. }
  3783. let dataBean = new BubbleBean();
  3784. dataBean.data = mList;
  3785. dataBean.color = this.themeColor
  3786. dataBean.onItemClick = (i) => {
  3787. const newDirPath = rPath + '/' + mList[i];
  3788. // Logger.info('newDirPath = ' + newDirPath)
  3789. this.selectedFiles.forEach((item) => {
  3790. const newPath = newDirPath + '/' + item.fileName;
  3791. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  3792. ToastUtil.showToast('移动成功');
  3793. this.table.deleteData(item, () => {
  3794. this.cache.delete(this.currentPath); // 删除原路径缓存
  3795. this.cache.delete(newDirPath); // 删除目标路径缓存
  3796. this.getSortedFiles(this.currentPath, true);
  3797. });
  3798. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  3799. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  3800. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  3801. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3802. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  3803. this.table.insert(newItem, (id: number) => {
  3804. //加入数据库
  3805. });
  3806. }
  3807. }).catch((error: Error) => {
  3808. console.error(error.message);
  3809. });
  3810. });
  3811. this.isMultiSelect = false
  3812. this.selectedFiles = [];
  3813. this.isAllSelected = false
  3814. XPopup.dismissTop();
  3815. };
  3816. let pup: XPopup
  3817. if (this.isDarkMode) {
  3818. pup = XPopup.Builder()
  3819. .setPopupPosition(PopupPosition.TOP)
  3820. .atView(viewId)
  3821. .setBackgroundColor(Color.Black)
  3822. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3823. .show();
  3824. } else {
  3825. pup = XPopup.Builder()
  3826. .setPopupPosition(PopupPosition.TOP)
  3827. .atView(viewId)
  3828. .setBackgroundColor(Color.White)
  3829. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3830. .show();
  3831. }
  3832. }
  3833. /**
  3834. * 加载所有歌单
  3835. */
  3836. async loadAllPlaylists() {
  3837. try {
  3838. this.allPlaylists = await this.playlistTable?.queryAllPlaylists()!
  3839. LogUtil.info('heanup Loaded playlists: ' + this.allPlaylists.length)
  3840. } catch (error) {
  3841. LogUtil.error('heaunp Failed to load playlists: ' + error.message)
  3842. }
  3843. }
  3844. /**
  3845. * 显示添加到歌单对话框
  3846. */
  3847. async openAddToPlaylistDialog(items: VideoItem | VideoItem[]) {
  3848. const songs = Array.isArray(items) ? items : [items]
  3849. const musicItems = songs.filter(song => song.type !== CommonConstants.TYPE_IS_DIR)
  3850. if (musicItems.length === 0) {
  3851. ToastUtil.showToast('请选择要添加的歌曲')
  3852. return
  3853. }
  3854. // 加载最新的歌单列表
  3855. await this.loadAllPlaylists()
  3856. showAddToPlaylistDialog(
  3857. musicItems,
  3858. this.allPlaylists,
  3859. async (playlistId: string) => {
  3860. // 添加歌曲到歌单
  3861. const success = await this.playlistTable?.addSongsToPlaylist(playlistId,
  3862. musicItems.map(song => song.filePath))
  3863. if (success) {
  3864. const count = musicItems.length
  3865. ToastUtil.showToast(count > 1 ? `已添加 ${count} 首歌曲` : '已添加到歌单')
  3866. // 重新加载歌单列表
  3867. await this.loadAllPlaylists()
  3868. } else {
  3869. ToastUtil.showToast(musicItems.length > 1 ? '选中的歌曲已在该歌单中' : '歌曲已在该歌单中')
  3870. }
  3871. this.longItemFilePath = ''
  3872. if (this.isMultiSelect) {
  3873. this.isMultiSelect = false
  3874. this.isAllSelected = false
  3875. this.selectedFiles = []
  3876. }
  3877. },
  3878. () => {
  3879. LogUtil.info('取消添加到歌单')
  3880. },
  3881. () => {
  3882. // 创建新歌单
  3883. showCreatePlaylistDialog(
  3884. async (name: string, description: string, coverPath?: string) => {
  3885. const success = await this.playlistTable?.createPlaylist(name, description, coverPath)
  3886. if (success) {
  3887. ToastUtil.showToast('歌单创建成功')
  3888. // 重新加载歌单列表并打开添加对话框
  3889. await this.loadAllPlaylists()
  3890. await this.openAddToPlaylistDialog(musicItems)
  3891. } else {
  3892. ToastUtil.showToast('歌单创建失败')
  3893. }
  3894. },
  3895. () => {
  3896. // 取消创建歌单
  3897. }
  3898. )
  3899. }
  3900. )
  3901. }
  3902. doFav(item: VideoItem) {
  3903. LogUtil.info('onecold doFav isFav=' + item.isFav)
  3904. let isFav = 0
  3905. if (Utility.getIsFav(this.favList, item)) {
  3906. isFav = 0
  3907. } else {
  3908. isFav = 1
  3909. }
  3910. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  3911. if (result) {
  3912. if (isFav === 1) {
  3913. ToastUtil.showToast('收藏成功');
  3914. } else {
  3915. ToastUtil.showToast('取消收藏成功');
  3916. }
  3917. this.deleteCache(this.currentPath)
  3918. this.getFavList(false)
  3919. if (this.modeType === 0 && !this.isFavMusic) {
  3920. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  3921. this.getSortedFiles(this.currentPath)
  3922. }
  3923. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  3924. workerInstance.postMessage({ code: 3, data: this.context });
  3925. workerInstance.postMessage({ code: 4, data: this.context });
  3926. }
  3927. })
  3928. }
  3929. //多选复制文件
  3930. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  3931. console.log('onecold showCopyDialogForMultipleFiles');
  3932. let mList: Array<string> = []
  3933. let rPath = this.rootPath
  3934. if (isCurrent) {
  3935. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  3936. rPath = this.currentPath
  3937. } else {
  3938. mList = Utility.getNameList(this.dirList);
  3939. rPath = this.rootPath
  3940. }
  3941. let dataBean = new BubbleBean();
  3942. dataBean.data = mList;
  3943. dataBean.isCopy = true
  3944. dataBean.color = this.themeColor
  3945. dataBean.onItemClick = (i) => {
  3946. const newDirPath = rPath + '/' + mList[i];
  3947. // Logger.info('newDirPath = ' + newDirPath)
  3948. this.selectedFiles.forEach((item) => {
  3949. const newPath = newDirPath + '/' + item.fileName;
  3950. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  3951. ToastUtil.showToast('复制成功');
  3952. this.cache.delete(newDirPath); // 删除目标路径缓存
  3953. this.getSortedFiles(this.currentPath);
  3954. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  3955. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  3956. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  3957. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  3958. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  3959. this.table.insert(newItem, (id: number) => {
  3960. //加入数据库
  3961. });
  3962. }
  3963. }).catch((error: Error) => {
  3964. console.error(error.message);
  3965. });
  3966. });
  3967. this.isMultiSelect = false
  3968. this.selectedFiles = [];
  3969. this.isAllSelected = false
  3970. XPopup.dismissTop();
  3971. };
  3972. let pup: XPopup
  3973. if (this.isDarkMode) {
  3974. pup = XPopup.Builder()
  3975. .setPopupPosition(PopupPosition.TOP)
  3976. .atView(viewId)
  3977. .setBackgroundColor(Color.Black)
  3978. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3979. .show();
  3980. } else {
  3981. pup = XPopup.Builder()
  3982. .setPopupPosition(PopupPosition.TOP)
  3983. .atView(viewId)
  3984. .setBackgroundColor(Color.White)
  3985. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  3986. .show();
  3987. }
  3988. }
  3989. @Builder
  3990. private DirItem(item: VideoItem, index?: number) {
  3991. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  3992. Row() {
  3993. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
  3994. $r('app.media.music_group'))
  3995. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  3996. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  3997. .fillColor(this.themeColor)// .fontSize(33)
  3998. .alt($r('app.media.music_group'))
  3999. .borderRadius(this.isCoverRectangle?9:'100%')
  4000. .clip(true)
  4001. .shadow({
  4002. radius: 2,
  4003. type: ShadowType.BLUR,
  4004. color: 'on_primary'
  4005. })
  4006. .sourceSize({width:38, height:38})
  4007. .margin({ left: 20, top: 8, bottom: 8 })
  4008. Column() {
  4009. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  4010. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4011. .maxLines(1)// .width('88%')
  4012. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4013. .animation({
  4014. duration: 555,
  4015. curve: 'ease-in-out',
  4016. })
  4017. .transition({
  4018. type: TransitionType.Insert,
  4019. opacity: 0,
  4020. translate: { x: 160 }
  4021. })
  4022. .margin({ left: 10, right: 20 })
  4023. .fontColor($r('app.color.text_color'))
  4024. Row() {
  4025. Text(`${this.getArtistSongCount(item.name)}首`)
  4026. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4027. .padding({ top: 8 })
  4028. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  4029. .fontColor($r('app.color.text_color'))
  4030. .margin({ left: 10 })
  4031. Text(`${this.getAlbumSongCount(item.name)}首`)
  4032. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4033. .padding({ top: 8 })
  4034. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  4035. .fontColor($r('app.color.text_color'))
  4036. .margin({ left: 10 })
  4037. Blank()
  4038. }
  4039. }
  4040. .height('100%')
  4041. .layoutWeight(1)
  4042. .justifyContent(FlexAlign.Center)
  4043. .alignItems(HorizontalAlign.Start)
  4044. Blank()
  4045. Image($r('app.media.arrow_right'))
  4046. .height(25)
  4047. .alignSelf(ItemAlign.Center)
  4048. .id(item.filePath)
  4049. .visibility(this.isShowAlphaBet?Visibility.None:Visibility.Visible)
  4050. .animation({ duration: 300, curve: Curve.Ease })
  4051. }
  4052. }
  4053. .backgroundColor(Color.Transparent)
  4054. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  4055. .width('98%')
  4056. .reuseId('dir_item')
  4057. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  4058. .opacity(this.opacityItem) // 绑定透明度
  4059. }
  4060. isShowDir(dirName: string) {
  4061. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  4062. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  4063. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  4064. if (dirName === undefined) {
  4065. return true
  4066. }
  4067. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  4068. return this.isShowSimi
  4069. }
  4070. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  4071. return this.isShowFAV
  4072. }
  4073. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  4074. return this.isShowHistory
  4075. }
  4076. return true
  4077. }
  4078. @State opacityItem: number = 1; // 控制透明度的状态变量
  4079. @Builder
  4080. private MusicItem(item: VideoItem, index?: number) {
  4081. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  4082. Row() {
  4083. Stack() {
  4084. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  4085. .fillColor(this.themeColor)
  4086. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4087. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4088. .alt($r('app.media.alt'))
  4089. .borderRadius(this.isCoverRectangle?9:'100%')
  4090. .clip(true)
  4091. .draggable(false)
  4092. .sourceSize({width:38, height:38})
  4093. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4094. // .autoResize(true) // 重采样,可减少内存占用
  4095. .opacity(this.opacityItem)// 绑定透明度
  4096. .margin({ left: 20 })
  4097. .shadow({
  4098. radius: StrUtil.isEmpty(item.pixelMapPath) ?6:14,
  4099. type: ShadowType.BLUR,
  4100. color: 'on_primary'
  4101. })
  4102. .gesture(LongPressGesture()
  4103. .onAction(async () => {
  4104. //如果是专辑和艺术家的首页,不能长按
  4105. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4106. return
  4107. //如果是我的收藏 最近播放等也不能长按
  4108. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4109. item.name === LocalMusic.STR_HISTORY_MUSIC
  4110. )
  4111. return
  4112. this.longItemFilePath = item.filePath
  4113. this.tempLyricContent = await this.getLyricContent(item)
  4114. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  4115. })
  4116. .onActionEnd((event: GestureEvent) => {
  4117. }))
  4118. .onClick(()=>{
  4119. if (this.isMultiSelect) {
  4120. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  4121. this.handleFileSelection(item, !isChecked);
  4122. } else {
  4123. this.doPlay(item,index)
  4124. this.setShowPlayTrue()
  4125. }
  4126. })
  4127. }
  4128. Column() {
  4129. Column() {
  4130. Text(this.isShowFileName?item.fileName :item.name)
  4131. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4132. .maxLines(1)
  4133. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4134. .animation({
  4135. duration: 555,
  4136. curve: 'Linear',
  4137. })
  4138. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4139. $r('app.color.text_color'))
  4140. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4141. .padding({right:25})
  4142. .bindPopup(this.longItemFilePath === item.filePath, {
  4143. builder: this.MenuBuilder(item,index,item.filePath),
  4144. placement: Placement.Top,
  4145. // autoCancel: true,
  4146. mask: {color:'#33000000'},
  4147. // popupColor: Color.Yellow,
  4148. enableArrow: false,//是否显示箭头
  4149. showInSubWindow: false,
  4150. onStateChange: (e) => {
  4151. if (!e.isVisible) {
  4152. this.longItemFilePath = ''
  4153. this.tempLyricContent = ''
  4154. }
  4155. }
  4156. })
  4157. .gesture(LongPressGesture()
  4158. .onAction(async () => {
  4159. //如果是专辑和艺术家的首页,不能长按
  4160. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4161. return
  4162. //如果是我的收藏 最近播放等也不能长按
  4163. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4164. item.name === LocalMusic.STR_HISTORY_MUSIC
  4165. )
  4166. return
  4167. this.longItemFilePath = item.filePath
  4168. this.tempLyricContent = await this.getLyricContent(item)
  4169. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  4170. })
  4171. .onActionEnd((event: GestureEvent) => {
  4172. })
  4173. )
  4174. Row() {
  4175. Column(){
  4176. Text(item.md5Str?.includes('Lossless')?
  4177. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  4178. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  4179. .padding({ top: 3,right:6,left:6,bottom:3 })
  4180. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4181. $r('app.color.text_color'))
  4182. .fontWeight(500)
  4183. .borderRadius(12)
  4184. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  4185. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4186. .backgroundColor('#FFC107')
  4187. }
  4188. .padding({ top: 8 })
  4189. Text(StrUtil.isEmpty(item.artist) ? item.duration
  4190. :this.twoFingerType==2? item.artist +' ' + item.duration
  4191. : item.artist + ' ' + item?.duration)
  4192. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4193. .padding({ top: 8 ,right:25})
  4194. .visibility(this.isShowFileName?Visibility.None:Visibility.Visible)
  4195. .maxLines(1)
  4196. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4197. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4198. Color.Gray)
  4199. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4200. Blank()
  4201. Text(this.isShowFileName?item.duration:item.size)
  4202. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4203. .padding({ top: 8 })
  4204. .maxLines(1)
  4205. .visibility(this.isShowFileName?Visibility.Visible:StrUtil.isEmpty(item.artist)
  4206. ? Visibility.Visible : Visibility.None)
  4207. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4208. Color.Gray)
  4209. .margin({ left: StrUtil.isEmpty(item.artist) ?0:10 })
  4210. }
  4211. .gesture(LongPressGesture()
  4212. .onAction(async () => {
  4213. //如果是专辑和艺术家的首页,不能长按
  4214. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4215. return
  4216. //如果是我的收藏 最近播放等也不能长按
  4217. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4218. item.name === LocalMusic.STR_HISTORY_MUSIC
  4219. )
  4220. return
  4221. this.longItemFilePath = item.filePath
  4222. this.tempLyricContent = await this.getLyricContent(item)
  4223. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  4224. })
  4225. .onActionEnd((event: GestureEvent) => {
  4226. })
  4227. )
  4228. }
  4229. .height('100%')
  4230. .width('100%')
  4231. .margin({ right: 10 })
  4232. .justifyContent(FlexAlign.Center)
  4233. .alignItems(HorizontalAlign.Start)
  4234. }
  4235. .height('100%')
  4236. .margin({ left: 5 })
  4237. .layoutWeight(1)
  4238. Column() {
  4239. Checkbox({ name: 'checkbox' + index })
  4240. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  4241. .selectedColor(this.themeColor)
  4242. .shape(CheckBoxShape.CIRCLE)
  4243. .opacity(this.isMultiSelect ? 1 : 0)
  4244. .animation({
  4245. duration: 666,
  4246. curve: 'Smooth' // 可选动画曲线
  4247. })
  4248. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  4249. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  4250. .margin({ left: 20, top: 8, bottom: 8,right:18 })
  4251. .width(22)
  4252. .height(22)
  4253. ImageAnimator()
  4254. .images(this.imagesF)// 动画数组
  4255. .duration(1000)// 持续
  4256. .state(this.animationState)// 动画状态
  4257. .fillMode(FillMode.Forwards)
  4258. .width(18)
  4259. .margin({ right: 20, top: 8, bottom: 8 })
  4260. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  4261. Visibility.None)
  4262. .height(18)
  4263. .iterations(-1) // 播放次数
  4264. }
  4265. }
  4266. }
  4267. .backgroundColor(Color.Transparent)
  4268. .width('100%')
  4269. .reuseId('file_item')
  4270. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  4271. }
  4272. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  4273. @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
  4274. buttons: [{ text: '文件夹' }, { text: '媒体库' },{ text: '艺术家' }, { text: '专辑' }],
  4275. direction: Direction.Ltr,
  4276. buttonPadding:{top:12,bottom:12},
  4277. backgroundColor: Color.Transparent,
  4278. fontSize:14,
  4279. selectedFontSize:15,
  4280. selectedFontColor:Color.White,
  4281. selectedBackgroundColor: this.themeColor,
  4282. localizedTextPadding: {
  4283. end: LengthMetrics.vp(20),
  4284. start: LengthMetrics.vp(20)
  4285. }
  4286. })
  4287. @State @Watch('capsuleSelectedIndexesChanged')tabSelectedIndexes: number[] = [0]
  4288. //当胶囊按钮的选择发生变化时调用此函数
  4289. capsuleSelectedIndexesChanged() {
  4290. this.modeType = this.tabSelectedIndexes[0]
  4291. }
  4292. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  4293. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  4294. isShowCoverHeader() {
  4295. if (!this.isShowHeader) {
  4296. return false
  4297. }
  4298. if (this.modeType == 0) {
  4299. if (this.isHistory || this.isFavMusic) {
  4300. return true
  4301. }
  4302. if (this.currentPath != this.rootPath) {
  4303. return true
  4304. }
  4305. }
  4306. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  4307. }
  4308. getCoverTitleBg(): ResourceStr | image.PixelMap {
  4309. if (this.isCustomizeBg) {
  4310. return ('rgba(255,255,255,0.2)')
  4311. }
  4312. if (this.isDarkMode) {
  4313. return $r('app.color.user_center_card_background')
  4314. }
  4315. return this.currentTitleCover
  4316. }
  4317. // 第二步:popup构造器定义弹框内容
  4318. @Builder popupBuilder() {
  4319. Column({ space: 2 }) {
  4320. Text('友情提示:双指缩放可以放大缩小列表')
  4321. .fontSize(12)
  4322. .fontWeight(FontWeight.Regular)
  4323. .fontColor($r('app.color.text_color'))
  4324. }
  4325. .justifyContent(FlexAlign.SpaceAround)
  4326. .width(220)
  4327. .height(55)
  4328. .padding(15)
  4329. }
  4330. //搜索功能的实现
  4331. @State searchText: string = ''; // 用户输入内容
  4332. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  4333. @State isSearchMode: boolean = false
  4334. // 实时搜索逻辑(带防抖)
  4335. private async onSearchInput(value: string): Promise<void> {
  4336. this.searchText = value.trim();
  4337. Logger.info('heanup LocalMusic', `onSearchInput: keyword="${this.searchText}", mode=${this.modeType}`);
  4338. // 新增条件判断:空输入时退出搜索模式
  4339. if (this.searchText === '') {
  4340. this.isSearchMode = false;
  4341. // 重新加载第一页(不带搜索条件)
  4342. await this.resetAndLoadFirstPage();
  4343. return;
  4344. }
  4345. // 进入搜索模式
  4346. if (!this.isSearchMode) {
  4347. this.isSearchMode = true;
  4348. }
  4349. // 使用数据库分页查询(带搜索条件)
  4350. await this.resetAndLoadFirstPage();
  4351. }
  4352. @State dragItem: number = -1
  4353. @State scaleItem: number = -1
  4354. @State neighborItem: number = -1
  4355. @State neighborScale: number = -1
  4356. @State offsetY: number = 0
  4357. private dragRefOffset: number = 0
  4358. private ITEM_INTV: number = 78
  4359. scaleSelect(item: number): number {
  4360. if (this.scaleItem === item) {
  4361. return 1.05
  4362. } else if (this.neighborItem === item) {
  4363. return this.neighborScale
  4364. } else {
  4365. return 1
  4366. }
  4367. }
  4368. itemMove(index: number, newIndex: number): void {
  4369. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  4370. return;
  4371. }
  4372. let tmp = this.videoLocalList.splice(index, 1);
  4373. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  4374. this.dataSource.pushArrayData(this.videoLocalList)
  4375. if(this.modeType==4&&this.playlistTable){
  4376. updateAllSongsSortOrder(this.playlistTable, this.videoLocalList,this.currentSongListID)
  4377. }
  4378. }
  4379. //瀑布流布局 支持双指缩放
  4380. @State columns: number = 2;
  4381. @State waterFlowScale: number = 1;
  4382. @State imageScale: number = 1;
  4383. @State waterFlowOpacity: number = 1;
  4384. @State waterFlowSnapshot: image.PixelMap | undefined = undefined;
  4385. private columnChanged: boolean = false;
  4386. private oldColumn: number = this.columns;
  4387. private pinchTime: number = 0;
  4388. // 根据缩放阈值改变列数,触发WaterFlow重新布局
  4389. changeColumns(scale: number): void {
  4390. if (scale > (this.columns / (this.columns - 0.5)) && this.columns > 1) {
  4391. this.columns--;
  4392. this.columnChanged = true;
  4393. } else if (scale < 1 && this.columns < 4) {
  4394. this.columns++;
  4395. this.columnChanged = true;
  4396. }
  4397. }
  4398. @Builder
  4399. getWaterView(){
  4400. Scroll(this.scroller) {
  4401. Column() {
  4402. Blank().height(this.topSafeHeight + 55)
  4403. WaterFlow({
  4404. scroller:this.waterScroller,
  4405. layoutMode: WaterFlowLayoutMode.SLIDING_WINDOW
  4406. }) {
  4407. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  4408. FlowItem() {
  4409. this.MusicWaterCardItem(item,index)
  4410. }
  4411. .width('100%')
  4412. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  4413. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  4414. {
  4415. preview: MenuPreviewMode.IMAGE,
  4416. previewAnimationOptions: { scale: [0.8, 1.0] },
  4417. })
  4418. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  4419. {
  4420. preview: MenuPreviewMode.IMAGE,
  4421. previewAnimationOptions: { scale: [0.8, 1.0] },
  4422. })
  4423. .transition(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }))
  4424. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  4425. TransitionEffect.scale({ x: 0, y: 0 })))
  4426. .gesture(
  4427. GestureGroup(GestureMode.Exclusive,
  4428. SwipeGesture({ direction: SwipeDirection.Horizontal })
  4429. .onAction((event: GestureEvent) => {
  4430. if (event) {
  4431. // this.sideBarController.openSideBar()
  4432. }
  4433. }),
  4434. TapGesture({ count: 1, fingers: 1 })
  4435. .onAction(async () => {
  4436. })
  4437. )
  4438. )
  4439. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  4440. }
  4441. // .columnsTemplate('repeat(auto-fit, 160)')
  4442. .id('waterflow') // 设置id用于截图
  4443. .columnsTemplate('1fr '.repeat(this.columns)) // 动态生成列模板,如:'1fr 1fr 1fr'表示3列等宽
  4444. .columnsGap(12) // 列间距
  4445. .rowsGap(16) // 行间距
  4446. .cachedCount(6)
  4447. .padding({bottom:this.bottomBarHeight+10})
  4448. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  4449. .animation({ duration: 500, curve: Curve.Ease }))
  4450. .scrollBar(BarState.Off)
  4451. // .fadingEdge(true, { fadingEdgeLength: LengthMetrics.vp(38) })
  4452. // 效果:只有向上或者向下滑动到顶部时才会有弹簧回弹效果
  4453. .edgeEffect(EdgeEffect.Spring, { alwaysEnabled: true })
  4454. .width('90%')
  4455. .height('100%')
  4456. .opacity(this.waterFlowOpacity)
  4457. .scale({
  4458. x: this.waterFlowScale,
  4459. y: this.waterFlowScale,
  4460. centerX: 0,
  4461. centerY: 0
  4462. })
  4463. .onAppear(() => {
  4464. this.scroller.scrollEdge(Edge.Top)
  4465. })
  4466. .nestedScroll({
  4467. scrollForward: NestedScrollMode.PARENT_FIRST,
  4468. scrollBackward: NestedScrollMode.SELF_FIRST
  4469. })
  4470. .priorityGesture(
  4471. PinchGesture()
  4472. .onActionStart((event: GestureEvent) => {
  4473. // 双指捏合手势识别成功时截图
  4474. this.pinchTime = event.timestamp;
  4475. this.columnChanged = false;
  4476. this.oldColumn = this.columns;
  4477. this.getUIContext().getComponentSnapshot().get('waterflow', (error: Error, pixmap: image.PixelMap) => {
  4478. if (error) {
  4479. console.info('error:' + JSON.stringify(error));
  4480. return;
  4481. }
  4482. this.waterFlowSnapshot = pixmap;
  4483. if ((this.oldColumn === 1 ) && event.scale > 1|| (this.oldColumn === 4 && event.scale < 1)) {
  4484. console.info("onecold onActionStart oldColumn:" + this.oldColumn)
  4485. if (this.oldColumn ===4) {
  4486. this.twoFingerType =3
  4487. this.isGridMusic = true
  4488. }else if (this.oldColumn ===1) {
  4489. this.twoFingerType =1
  4490. this.isGridMusic = false
  4491. }
  4492. return;
  4493. }
  4494. })
  4495. })
  4496. .onActionUpdate((event: GestureEvent) => {
  4497. // 手势更新:处理缩放逻辑和视觉效果
  4498. // 边界限制:防止超出列数范围时继续缩放
  4499. if ((this.oldColumn === 1 && event.scale > 1) || (this.oldColumn === 4 && event.scale < 1)) {
  4500. return;
  4501. }
  4502. // 节流处理:避免过于频繁的更新,提升性能
  4503. if (event.timestamp - this.pinchTime < 10000000) {
  4504. return;
  4505. }
  4506. this.pinchTime = event.timestamp;
  4507. this.waterFlowScale = event.scale;
  4508. this.imageScale = event.scale;
  4509. // 根据缩放比例设置WaterFlow透明度
  4510. this.waterFlowOpacity = (this.waterFlowScale > 1) ? (this.waterFlowScale - 1) : (1 - this.waterFlowScale);
  4511. this.waterFlowOpacity *= 3;
  4512. if (!this.columnChanged) {
  4513. this.changeColumns(event.scale);
  4514. }
  4515. // 列数改变后的缩放比例调整:避免出现空白区域
  4516. if (this.columnChanged) {
  4517. this.waterFlowScale = this.imageScale * this.columns / this.oldColumn;
  4518. // 限制缩放范围,确保视觉效果自然
  4519. if (event.scale < 1) {
  4520. this.waterFlowScale = this.waterFlowScale > 1 ? this.waterFlowScale : 1;
  4521. } else {
  4522. this.waterFlowScale = this.waterFlowScale < 1 ? this.waterFlowScale : 1;
  4523. }
  4524. }
  4525. })
  4526. .onActionEnd((event: GestureEvent) => {
  4527. // 手势结束:执行归位动画并保存状态
  4528. // 执行归位动画:平滑过渡到正常状态
  4529. this.getUIContext()?.animateTo({ duration: 300 }, () => {
  4530. this.waterFlowScale = 1;
  4531. this.waterFlowOpacity = 1;
  4532. })
  4533. // 持久化保存当前列数:下次启动时恢复
  4534. PreferencesUtil.putSync('lastColumns', this.columns);
  4535. })
  4536. )
  4537. .onScrollFrameBegin((offset: number) => {
  4538. // 获取当前滚动偏移量
  4539. if(this.autoHideTitle){
  4540. const currentOffsetY = this.waterScroller.currentOffset().yOffset;
  4541. // 判断滚动方向
  4542. if (currentOffsetY > this.prevOffsetY) {
  4543. // console.log("onecold 向上滚动");
  4544. this.isShowTitleBar = false
  4545. } else if (currentOffsetY < this.prevOffsetY) {
  4546. // console.log("onecold 向下滚动");
  4547. this.isShowTitleBar = true
  4548. }
  4549. // 更新前一次偏移量
  4550. this.prevOffsetY = currentOffsetY;
  4551. }
  4552. return { offsetRemain: offset };
  4553. })
  4554. }
  4555. }
  4556. .scrollBar(BarState.Off)
  4557. }
  4558. //瀑布流卡片布局
  4559. @Builder
  4560. private MusicWaterCardItem(item: VideoItem, index: number) {
  4561. Button({ type: ButtonType.Normal, stateEffect: false }) {
  4562. Stack() {
  4563. Column() {
  4564. Image(item.pixelMapPath)
  4565. .backgroundImageSize(ImageSize.Auto)
  4566. .borderRadius({
  4567. topLeft: 12,
  4568. topRight : 12,
  4569. bottomLeft: 0,
  4570. bottomRight: 0
  4571. })
  4572. .draggable(false)// 禁止长按手势拖动
  4573. .autoResize(true) // 重采样,可减少内存占用
  4574. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4575. .width('100%')
  4576. .height('auto')
  4577. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  4578. .objectFit(ImageFit.Auto)
  4579. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  4580. height: '99%' ,
  4581. dragBar: true,
  4582. onDisappear: () => {
  4583. this.longItemFilePath = '';
  4584. this.tempLyricContent = ''
  4585. },
  4586. showClose: true,
  4587. preferType: SheetType.CENTER ,
  4588. title: { title: '编辑标签' }
  4589. })
  4590. .draggable(false)
  4591. .opacity(this.opacityItem)// 绑定透明度
  4592. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  4593. // .animation({ duration: 500, curve: Curve.Ease }))
  4594. .animation({
  4595. duration: 666,
  4596. curve: 'ease-in-out' // 可选动画曲线
  4597. })
  4598. .margin({
  4599. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  4600. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  4601. })
  4602. Column() {
  4603. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  4604. .fontSize(this.columns == 4 ||this.columns==3? 12 : this.columns == 2 ? 15 : 18)
  4605. .maxLines(1)
  4606. .fontWeight(FontWeight.Bold)
  4607. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4608. .animation({
  4609. duration: 555,
  4610. curve: 'Linear',
  4611. })
  4612. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  4613. height: '95%',
  4614. dragBar: true,
  4615. showClose: true,
  4616. onDisappear: () => {
  4617. this.longItemFilePathDetail = '';
  4618. },
  4619. blurStyle:BlurStyle.Thin,
  4620. backgroundColor:Color.Transparent,
  4621. preferType: SheetType.CENTER ,
  4622. title: { title: '详情' }
  4623. })
  4624. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4625. $r('app.color.text_color'))
  4626. Column() {
  4627. Text(`${this.getArtistSongCount(item.name)}首`)
  4628. .fontSize(11)
  4629. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  4630. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4631. .fontColor($r('app.color.text_color'))
  4632. Text(`${this.getAlbumSongCount(item.name)}首`)
  4633. .fontSize(11)
  4634. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  4635. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4636. .fontColor($r('app.color.text_color'))
  4637. Row(){
  4638. Column(){
  4639. Text(item.md5Str?.includes('Lossless')?
  4640. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  4641. .fontSize(this.columns == 4 ||this.columns==3? 8 : this.columns == 2 ? 9 : 11)
  4642. .padding({ top: 3,right:6,left:6,bottom:3 })
  4643. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4644. $r('app.color.text_color'))
  4645. .fontWeight(500)
  4646. .borderRadius(12)
  4647. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4648. .backgroundColor('#FFC107')
  4649. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  4650. }
  4651. .margin({ top: 2 ,right:6})
  4652. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  4653. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  4654. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  4655. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 13)
  4656. .maxLines(1)
  4657. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4658. .margin({ top: 2})
  4659. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  4660. || item.type == CommonConstants.TYPE_IS_ALBUM
  4661. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  4662. .fontWeight(FontWeight.Medium)
  4663. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4664. $r('app.color.text_color'))
  4665. }
  4666. }
  4667. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  4668. }
  4669. .height(this.columns == 4 ||this.columns==3? item.type==CommonConstants.TYPE_IS_DIR?30:40
  4670. : this.columns == 2 ? (item.type==CommonConstants.TYPE_IS_DIR?38:48) :
  4671. (item.type==CommonConstants.TYPE_IS_DIR?48:58))
  4672. .width('100%')
  4673. .justifyContent(FlexAlign.Center)
  4674. .margin({
  4675. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  4676. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  4677. })
  4678. }
  4679. .width('100%')
  4680. .borderRadius(12)
  4681. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  4682. .backgroundImageSize({ height: '100%', width: '100%' })
  4683. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  4684. .animation({ curve: Curve.Sharp, duration: 300 })
  4685. Checkbox({ name: 'checkbox' + index })
  4686. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  4687. .selectedColor(this.themeColor)
  4688. .shape(CheckBoxShape.CIRCLE)
  4689. .opacity(this.isMultiSelect ? 1 : 0)
  4690. .animation({
  4691. duration: 666,
  4692. curve: 'Smooth' // 可选动画曲线
  4693. })
  4694. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  4695. Visibility.None)
  4696. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  4697. .margin({ left: 20, top: 8, bottom: 8 })
  4698. .width(38)
  4699. .height(38)
  4700. }
  4701. }
  4702. .backgroundColor(Color.Transparent)
  4703. .width('100%')
  4704. .height('auto')
  4705. .padding({top:2})
  4706. .shadow({
  4707. radius: 10,
  4708. type: ShadowType.BLUR,
  4709. color: 'on_primary'
  4710. })
  4711. .reuseId('card_item')
  4712. .onClick(() => {
  4713. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  4714. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  4715. this.handleFileSelection(item, !isChecked);
  4716. } else {
  4717. this.doPlay(item, index)
  4718. }
  4719. })
  4720. }
  4721. // Grid布局的开始
  4722. private dragRefOffSetX: number = 0;
  4723. private dragRefOffSetY: number = 0;
  4724. private FIX_VP_X: number = 180;
  4725. private FIX_VP_Y: number = 84;
  4726. isDraggable(index: number): boolean {
  4727. return index >= 0;
  4728. }
  4729. getRowEnd(item: number) {
  4730. if (item.toString() === '0') {
  4731. return 1;
  4732. } else {
  4733. return 0;
  4734. }
  4735. }
  4736. isInLeft(index: number) {
  4737. return index % 2 == 0;
  4738. }
  4739. down(index: number): void {
  4740. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  4741. return;
  4742. }
  4743. this.offsetY -= this.FIX_VP_Y;
  4744. this.dragRefOffSetY += this.FIX_VP_Y;
  4745. this.itemMove(index, index + 1);
  4746. }
  4747. up(index: number): void {
  4748. if (!this.isDraggable(index - 2)) {
  4749. return;
  4750. }
  4751. this.offsetY += this.FIX_VP_Y;
  4752. this.dragRefOffSetY -= this.FIX_VP_Y;
  4753. this.itemMove(index, index - 1);
  4754. }
  4755. left(index: number): void {
  4756. if (this.isInLeft(index)) {
  4757. return;
  4758. }
  4759. if (!this.isDraggable(index - 1)) {
  4760. return;
  4761. }
  4762. this.offsetX += this.FIX_VP_X;
  4763. this.dragRefOffSetX -= this.FIX_VP_X;
  4764. this.itemMove(index, index - 1)
  4765. }
  4766. right(index: number): void {
  4767. if (!this.isInLeft(index)) {
  4768. return;
  4769. }
  4770. if (!this.isDraggable(index + 1)) {
  4771. return;
  4772. }
  4773. this.offsetX -= this.FIX_VP_X;
  4774. this.dragRefOffSetX += this.FIX_VP_X;
  4775. this.itemMove(index, index + 1)
  4776. }
  4777. private scroller: Scroller = new Scroller();
  4778. private waterScroller: Scroller = new Scroller();
  4779. @State startIndex: number = 0
  4780. @State endIndex: number = 0
  4781. @State scaleValue: number = 1
  4782. @State pinchValue: number = 1
  4783. layoutOptionsForHeader: GridLayoutOptions = {
  4784. regularSize: [1, 1], // 只支持[1, 1]
  4785. irregularIndexes: [0], // 索引为0的GridItem占用一行
  4786. };
  4787. @Builder
  4788. getGridView() {
  4789. Grid(this.scroller, this.layoutOptionsForHeader) {
  4790. GridItem() {
  4791. Column(){
  4792. Blank().height(this.topSafeHeight + 45)
  4793. }
  4794. }
  4795. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  4796. GridItem() {
  4797. Stack({ alignContent: Alignment.Center }) {
  4798. this.MusicItemGrid(item, index)
  4799. }
  4800. }
  4801. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  4802. {
  4803. preview: MenuPreviewMode.IMAGE,
  4804. previewAnimationOptions: { scale: [0.8, 1.0] },
  4805. })
  4806. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  4807. {
  4808. preview: MenuPreviewMode.IMAGE,
  4809. previewAnimationOptions: { scale: [0.8, 1.0] },
  4810. })
  4811. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  4812. TransitionEffect.scale({ x: 0, y: 0 })))
  4813. .clickEffect({ level: ClickEffectLevel.LIGHT })
  4814. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  4815. .zIndex(this.dragItem === index ? 1 : 0)
  4816. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  4817. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  4818. }
  4819. .width('94%')
  4820. .height('100%')
  4821. .editMode(true)
  4822. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  4823. .animation({ duration: 500, curve: Curve.Ease }))
  4824. .padding({bottom:this.bottomBarHeight+this.bottomSafeHeight+10})
  4825. .reuseId('grid_item')
  4826. .layoutWeight(1)
  4827. .scrollBar(BarState.Off)
  4828. .supportAnimation(true)
  4829. .cachedCount(this.twoFingerType==1?5:this.twoFingerType==2?4:3)
  4830. .columnsTemplate(
  4831. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  4832. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  4833. )
  4834. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  4835. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  4836. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  4837. .gesture(PinchGesture({ fingers: 2 })
  4838. .onActionEnd((event: GestureEvent) => {
  4839. this.setGridTwoFingers()
  4840. })
  4841. .onActionUpdate(e => {
  4842. this.scaleValue = this.pinchValue * e.scale
  4843. })
  4844. .onActionStart(e => {
  4845. }))
  4846. .enableScrollInteraction(true)
  4847. .onScrollIndex((start: number, end: number) => {
  4848. this.startIndex = start
  4849. this.endIndex = end
  4850. })
  4851. .onScrollFrameBegin((offset: number) => {
  4852. if(this.autoHideTitle){
  4853. const currentOffsetY = this.scroller.currentOffset().yOffset;
  4854. // 判断滚动方向
  4855. if (currentOffsetY > this.prevOffsetY) {
  4856. // console.log("onecold 向上滚动");
  4857. this.isShowTitleBar = false
  4858. } else if (currentOffsetY < this.prevOffsetY) {
  4859. // console.log("onecold 向下滚动");
  4860. this.isShowTitleBar = true
  4861. }
  4862. // 更新前一次偏移量
  4863. this.prevOffsetY = currentOffsetY;
  4864. }
  4865. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  4866. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  4867. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  4868. if (this.isScrollHide) {
  4869. this.setBarHeightHide2(offset)
  4870. } else {
  4871. this.setBarHeightNormal()
  4872. }
  4873. } else {
  4874. this.setBarHeightHide(offset)
  4875. }
  4876. return { offsetRemain: offset };
  4877. })
  4878. }
  4879. @State targetFile: string = '';
  4880. setGridTwoFingers() {
  4881. this.pinchValue = this.scaleValue;
  4882. Logger.info('this.pinchValue = ' + this.pinchValue);
  4883. if (this.pinchValue >= 1) {
  4884. this.twoFingerType++
  4885. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  4886. if(this.twoFingerType >= 4){
  4887. this.twoFingerType = 4//切换成瀑布流
  4888. this.columns = 4
  4889. }
  4890. } else {
  4891. this.twoFingerType--
  4892. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  4893. if (this.twoFingerType < 1) {
  4894. this.twoFingerType = 3
  4895. this.isGridMusic = false
  4896. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4897. }
  4898. }
  4899. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  4900. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4901. this.pinchValue = 1;
  4902. this.scaleValue = 1;
  4903. }
  4904. @State longItemFilePath: string = ''
  4905. @State tempLyricContent: string = ''
  4906. @State editingItem: VideoItem | null = null
  4907. @Builder
  4908. private MusicItemGrid(item: VideoItem, index: number) {
  4909. Button({ type: ButtonType.Normal, stateEffect: false }) {
  4910. Stack() {
  4911. Column() {
  4912. Image(item.pixelMapPath)
  4913. .height(this.getGridHeight())
  4914. .width(this.getGridWight())
  4915. .draggable(false)
  4916. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4917. .autoResize(true) // 重采样,可减少内存占用
  4918. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  4919. .clip(true)
  4920. .borderRadius({
  4921. topLeft: 12,
  4922. topRight: 12,
  4923. bottomLeft: 0,
  4924. bottomRight: 0
  4925. })
  4926. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  4927. height: '99%' ,
  4928. dragBar: true,
  4929. onDisappear: () => {
  4930. this.longItemFilePath = '';
  4931. this.tempLyricContent = ''
  4932. },
  4933. showClose: true,
  4934. preferType: SheetType.CENTER ,
  4935. title: { title: '编辑标签' }
  4936. })
  4937. .draggable(false)
  4938. .opacity(this.opacityItem)// 绑定透明度
  4939. .animation({
  4940. duration: 666,
  4941. curve: 'ease-in-out' // 可选动画曲线
  4942. })
  4943. .margin({
  4944. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  4945. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  4946. })
  4947. Column() {
  4948. Text(this.isShowFileName&&item.type!=CommonConstants.TYPE_IS_DIR?item.fileName :item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  4949. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4950. .maxLines(1)
  4951. .fontWeight(FontWeight.Bold)
  4952. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4953. .animation({
  4954. duration: 555,
  4955. curve: 'Linear',
  4956. })
  4957. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  4958. height: '100%',
  4959. dragBar: true,
  4960. showClose: true,
  4961. onDisappear: () => {
  4962. this.longItemFilePathDetail = '';
  4963. },
  4964. blurStyle:BlurStyle.Thin,
  4965. backgroundColor:Color.Transparent,
  4966. preferType: SheetType.CENTER ,
  4967. title: { title: '详情' }
  4968. })
  4969. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4970. $r('app.color.text_color'))
  4971. Column() {
  4972. Text(`${this.getArtistSongCount(item.name)}首`)
  4973. .fontSize(11)
  4974. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  4975. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4976. .fontColor($r('app.color.text_color'))
  4977. Text(`${this.getAlbumSongCount(item.name)}首`)
  4978. .fontSize(11)
  4979. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  4980. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4981. .fontColor($r('app.color.text_color'))
  4982. Row(){
  4983. Column(){
  4984. Text(item.md5Str?.includes('Lossless')?
  4985. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  4986. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  4987. .padding({ top: 3,right:6,left:6,bottom:3 })
  4988. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4989. $r('app.color.text_color'))
  4990. .fontWeight(500)
  4991. .borderRadius(12)
  4992. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4993. .backgroundColor('#FFC107')
  4994. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  4995. }
  4996. .margin({ top: 2 ,right:6})
  4997. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  4998. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  4999. Text(this.isShowFileName?item.duration:StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  5000. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  5001. .maxLines(1)
  5002. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5003. .margin({ top: 2})
  5004. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  5005. || item.type == CommonConstants.TYPE_IS_ALBUM
  5006. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5007. .fontWeight(FontWeight.Medium)
  5008. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5009. $r('app.color.text_color'))
  5010. }
  5011. }
  5012. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  5013. }
  5014. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  5015. .width(this.getGridWight())
  5016. .justifyContent(FlexAlign.Center)
  5017. .margin({
  5018. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5019. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5020. })
  5021. }
  5022. .width(this.getGridWight())
  5023. .borderRadius(12)
  5024. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath)?$r('app.media.alt'):item.pixelMapPath)
  5025. .backgroundImageSize({ height: '100%', width: '100%' })
  5026. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  5027. .animation({ curve: Curve.Sharp, duration: 300 })
  5028. Checkbox({ name: 'checkbox' + index })
  5029. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  5030. .selectedColor(this.themeColor)
  5031. .shape(CheckBoxShape.CIRCLE)
  5032. .opacity(this.isMultiSelect ? 1 : 0)
  5033. .animation({
  5034. duration: 666,
  5035. curve: 'Smooth' // 可选动画曲线
  5036. })
  5037. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  5038. Visibility.None)
  5039. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5040. .margin({ left: 20, top: 8, bottom: 8 })
  5041. .width(38)
  5042. .height(38)
  5043. }
  5044. }
  5045. .backgroundColor(Color.Transparent)
  5046. .width('100%')
  5047. .padding({ top: 15 })
  5048. .height(this.getGridAllHeight())
  5049. .onClick(() => {
  5050. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5051. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5052. this.handleFileSelection(item, !isChecked);
  5053. } else {
  5054. this.doPlay(item, index)
  5055. }
  5056. })
  5057. }
  5058. getGridAllHeight() {
  5059. let heightG = 222
  5060. switch (this.twoFingerType) {
  5061. case 1:
  5062. heightG = 143
  5063. break;
  5064. case 2:
  5065. heightG = 178
  5066. break;
  5067. case 3:
  5068. heightG = 222
  5069. break;
  5070. }
  5071. return heightG
  5072. }
  5073. getGridHeight() {
  5074. let heightG = 150
  5075. switch (this.twoFingerType) {
  5076. case 1:
  5077. heightG = 80
  5078. break;
  5079. case 2:
  5080. heightG = 110
  5081. break;
  5082. case 3:
  5083. heightG = 150
  5084. break;
  5085. }
  5086. return heightG
  5087. }
  5088. getGridWight() {
  5089. let wightG = 158
  5090. switch (this.twoFingerType) {
  5091. case 1:
  5092. wightG = 80
  5093. break;
  5094. case 2:
  5095. wightG = 110
  5096. break;
  5097. case 3:
  5098. wightG = 158
  5099. break;
  5100. }
  5101. return wightG
  5102. }
  5103. @State isShowDetail:boolean = false
  5104. @State longItemFilePathDetail:string =''
  5105. @Builder
  5106. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  5107. if(
  5108. ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  5109. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5110. item.name === LocalMusic.STR_HISTORY_MUSIC)
  5111. ){
  5112. //如果是专辑和艺术家的首页,不能长按
  5113. //如果是我的收藏 最近播放等也不能长按
  5114. }else{
  5115. Scroll() {
  5116. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  5117. Menu() {
  5118. MenuItem({
  5119. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  5120. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  5121. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  5122. })
  5123. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5124. .onClick(() => {
  5125. if (item) {
  5126. this.doFav(item)
  5127. }
  5128. this.longItemFilePath = ''
  5129. })
  5130. MenuItem({
  5131. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  5132. content: '下一首播放'
  5133. })
  5134. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5135. .onClick(() => {
  5136. this.addToNextPlay(item);
  5137. this.longItemFilePath = ''
  5138. })
  5139. MenuItem({
  5140. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  5141. content: '添加到歌单'
  5142. })
  5143. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5144. .onClick(async () => {
  5145. this.longItemFilePath = ''
  5146. await this.openAddToPlaylistDialog(item)
  5147. })
  5148. MenuItem({
  5149. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  5150. content: '编辑标签'
  5151. })
  5152. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  5153. height: '99%',
  5154. dragBar: true,
  5155. showClose: true,
  5156. preferType: SheetType.CENTER ,
  5157. title: { title: '编辑标签' }
  5158. })
  5159. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5160. .onClick(async() => {
  5161. this.initEditFields(item)
  5162. this.tempLyricContent = await this.getLyricContent(item);
  5163. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  5164. this.lyricConStr = this.tempLyricContent
  5165. }
  5166. if(this.isGridMusic||this.twoFingerType==4){
  5167. this.longItemFilePath = item.filePath
  5168. }else{
  5169. this.isShowEdit = !this.isShowEdit;
  5170. }
  5171. })
  5172. MenuItem({
  5173. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  5174. content: $r('app.string.select_all')
  5175. })
  5176. .onClick(() => {
  5177. this.isMultiSelect = !this.isMultiSelect
  5178. this.longItemFilePath = ''
  5179. this.selectedFiles.push(item)
  5180. })
  5181. MenuItem({
  5182. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.cut')),
  5183. content: $r('app.string.edit_audio')
  5184. })
  5185. .bindContentCover($$this.isEditAudio, this.EditAudioBuilder(item), {
  5186. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5187. })
  5188. .onClick(() => {
  5189. this.isEditAudio = !this.isEditAudio
  5190. })
  5191. MenuItem({
  5192. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  5193. content: $r('app.string.extract_accompaniment')
  5194. })
  5195. .bindContentCover($$this.isExtractAcc, this.ExtractAccBuilder(item), {
  5196. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5197. })
  5198. .onClick(() => {
  5199. if (!Utility.isNoble()) {
  5200. this.showVipDialog()
  5201. return
  5202. }
  5203. this.isExtractAcc = !this.isExtractAcc
  5204. })
  5205. MenuItem({
  5206. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.repeat')),
  5207. content: $r('app.string.converter_audio')
  5208. })
  5209. .bindContentCover($$this.isConverter, this.ConverterBuilder(item), {
  5210. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5211. })
  5212. .onClick(() => {
  5213. if (!Utility.isNoble()) {
  5214. this.showVipDialog()
  5215. return
  5216. }
  5217. this.isConverter = !this.isConverter
  5218. })
  5219. MenuItem({
  5220. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.ai_edit')),
  5221. content: $r('app.string.vocal_separation')
  5222. })
  5223. .bindContentCover($$this.isAIVoiceSeparation, this.AiBuilder(item), {
  5224. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5225. })
  5226. .onClick(() => {
  5227. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  5228. })
  5229. MenuItem({
  5230. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_counterclockwise_clock')),
  5231. content: $r('app.string.change_tone')
  5232. })
  5233. .bindContentCover($$this.isChangeTone, this.ChangeToneBuilder(item), {
  5234. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5235. })
  5236. .onClick(() => {
  5237. this.isChangeTone = !this.isChangeTone
  5238. })
  5239. if(Utility.isVideoByExtension(item.filePath)){
  5240. MenuItem({
  5241. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.identify_song')),
  5242. content: $r('app.string.extract_audio')
  5243. })
  5244. .bindContentCover($$this.isExtractAudio, this.extractAudioFromVideoBuilder(item), {
  5245. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5246. })
  5247. .onClick(() => {
  5248. this.isExtractAudio = !this.isExtractAudio
  5249. })
  5250. }
  5251. MenuItem({
  5252. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.phone')),
  5253. content: $r('app.string.set_ring')
  5254. })
  5255. .onClick(async () => {
  5256. await PermissionUtil.activatePermission(item.filePath)
  5257. // if(item.filePath.includes(this.packName)){
  5258. setRingTone(this.context, item.filePath,item.name)
  5259. // }else{
  5260. // ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限设置铃声')
  5261. // }
  5262. this.longItemFilePath = ''
  5263. })
  5264. MenuItem({
  5265. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  5266. content: $r('app.string.rename')
  5267. })
  5268. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  5269. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5270. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  5271. .onClick(() => {
  5272. this.showReNameDialog(item, index + '', filePath)
  5273. this.longItemFilePath = ''
  5274. })
  5275. MenuItem({
  5276. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  5277. content: $r('app.string.delete')
  5278. })
  5279. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  5280. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5281. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  5282. .onClick(() => {
  5283. this.selectedFiles.push(item)
  5284. this.showWarnIsDelete()
  5285. this.longItemFilePath = ''
  5286. })
  5287. MenuItem({
  5288. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  5289. content: $r('app.string.detail')
  5290. })
  5291. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  5292. height:'100%',
  5293. dragBar: true,
  5294. showClose: true,
  5295. blurStyle:BlurStyle.Thin,
  5296. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  5297. backgroundColor:Color.Transparent,
  5298. title: { title: '详情信息' }
  5299. })
  5300. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5301. .onClick(() => {
  5302. if(this.isGridMusic||this.twoFingerType==4){
  5303. this.longItemFilePathDetail = item.filePath
  5304. }else{
  5305. this.isShowDetail = !this.isShowDetail
  5306. }
  5307. })
  5308. MenuItem({
  5309. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  5310. content: $r('app.string.share')
  5311. })
  5312. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5313. .onClick(() => {
  5314. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  5315. this.longItemFilePath = ''
  5316. })
  5317. }
  5318. .font({ size: 14, weight: FontWeight.Normal })
  5319. }
  5320. .width(180)
  5321. }
  5322. .height('auto')
  5323. .enableScrollInteraction(true)
  5324. .scrollBar(this.isGridMusic?BarState.On:BarState.Off)
  5325. }
  5326. }
  5327. private listMaxScrollOffsetY: number = 0
  5328. @State selectedIndex: number = -1
  5329. setlistTwoFingers() {
  5330. this.pinchValue = this.scaleValue;
  5331. Logger.info('this.pinchValue = ' + this.pinchValue);
  5332. if (this.pinchValue >= 1) {
  5333. this.twoFingerType++
  5334. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  5335. if (this.twoFingerType > 3) {
  5336. this.twoFingerType = 1
  5337. this.isGridMusic = true
  5338. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5339. }
  5340. } else {
  5341. this.twoFingerType--
  5342. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  5343. if (this.twoFingerType < 1) {
  5344. this.twoFingerType = 4
  5345. this.columns = 1
  5346. }
  5347. }
  5348. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  5349. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5350. this.pinchValue = 1;
  5351. this.scaleValue = 1;
  5352. }
  5353. @Builder
  5354. getList(){
  5355. Stack() {
  5356. Refresh({ refreshing: $$this.isRefreshing, refreshingContent: this.contentNode }) {
  5357. this.getListView()
  5358. }
  5359. .pullDownRatio(this.ratioL)
  5360. .pullToRefresh(true)
  5361. .refreshOffset(0)
  5362. .onOffsetChange((offset: number) => {
  5363. // 越接近最大距离,下拉跟手系数越小。
  5364. this.ratioL = 1 - Math.pow((offset / this.maxRefreshingHeight), 3);
  5365. })
  5366. .onStateChange((refreshStatus: RefreshStatus) => {
  5367. console.info('onecold Refresh onStatueChange state is ' + refreshStatus);
  5368. })
  5369. .onRefreshing(async () => {
  5370. if(this.modeType==0){
  5371. this.getHistoryList(false)
  5372. this.asyncCurrentPathOnlyFile()
  5373. }else if(this.modeType == 1){
  5374. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  5375. }else if(this.modeType == 2){
  5376. workerInstance.postMessage({ code: 3, data: this.context });
  5377. }else if(this.modeType == 3){
  5378. workerInstance.postMessage({ code: 4, data: this.context });
  5379. }else if(this.modeType == 4){
  5380. this.doSongListTask()
  5381. }
  5382. console.log('onRefreshing test');
  5383. })
  5384. }
  5385. }
  5386. // 扫描当前目录下的文件,不扫描子目录
  5387. asyncCurrentPathOnlyFile(){
  5388. if(this.modeType==0){
  5389. const task = new taskpool.Task(scanCurrentDirectoryTask, getContext(this), this.currentPath,
  5390. this.lockPath,PreferencesUtil.getStringSync('COVER_API',''));
  5391. taskpool.execute(task, taskpool.Priority.HIGH).then(()=>{
  5392. if(this.modeType==0){
  5393. setTimeout(()=>{
  5394. this.isRefreshing =false
  5395. this.deleteCache(this.currentPath)
  5396. this.getSortedFiles(this.currentPath)
  5397. },500)
  5398. }
  5399. }).catch((e:object)=>{
  5400. this.isRefreshing =false
  5401. console.info("onecold task1 catch e: " + e);
  5402. })
  5403. }
  5404. }
  5405. @Builder
  5406. getListView() {
  5407. List({ scroller: this.listScroller }) {
  5408. // ListItemGroup({ header: this.coverHeader() }) {
  5409. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5410. ListItem() {
  5411. Column() {
  5412. if (item.type === CommonConstants.TYPE_IS_DIR
  5413. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  5414. this.DirItem(item, index)
  5415. } else {
  5416. this.MusicItem(item, index)
  5417. }
  5418. }
  5419. .animation({ curve: Curve.Sharp, duration: 300 })
  5420. }
  5421. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.9, y: 0.9 })
  5422. .animation({ duration: 500 }),
  5423. TransitionEffect.scale({ x: 0, y: 0 })))
  5424. .clickEffect({ level: ClickEffectLevel.LIGHT })
  5425. .swipeAction((
  5426. (this.isSwipe&&this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack))
  5427. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  5428. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath),
  5429. start:null,edgeEffect: SwipeEdgeEffect.None } : {}) //左滑
  5430. .onClick(() => {
  5431. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5432. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5433. this.handleFileSelection(item, !isChecked);
  5434. } else {
  5435. this.doPlay(item, index)
  5436. }
  5437. })
  5438. //拖动List关键代码开始
  5439. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  5440. .zIndex(this.dragItem === index ? 1 : 0)
  5441. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  5442. .gesture(
  5443. GestureGroup(GestureMode.Sequence,
  5444. LongPressGesture({ repeat: true })
  5445. .onAction((event?: GestureEvent) => {
  5446. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5447. this.scaleItem = index
  5448. })
  5449. })
  5450. .onActionEnd(() => {
  5451. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5452. this.scaleItem = -1
  5453. })
  5454. }),
  5455. PanGesture({ fingers: 1, direction: null, distance: 0 })
  5456. .onActionStart(() => {
  5457. this.dragItem = index // 记录当前拖动项索引
  5458. this.dragRefOffset = 0 // 重置偏移基准
  5459. })
  5460. .onActionUpdate((event: GestureEvent) => {
  5461. this.offsetY = event.offsetY - this.dragRefOffset;
  5462. this.neighborItem = -1;
  5463. let indexA = this.videoLocalList.indexOf(item);
  5464. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  5465. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  5466. let value: number = 0;
  5467. if (this.offsetY < 0) {
  5468. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  5469. this.neighborItem = indexA - 1;
  5470. this.neighborScale = 1 - value / 20;
  5471. } else if (this.offsetY > 0) {
  5472. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  5473. this.neighborItem = indexA + 1;
  5474. this.neighborScale = 1 - value / 20;
  5475. }
  5476. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.videoLocalList.length) {
  5477. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5478. this.offsetY -= this.ITEM_INTV;
  5479. this.dragRefOffset += this.ITEM_INTV;
  5480. this.itemMove(indexA, indexA + 1);
  5481. });
  5482. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  5483. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5484. this.offsetY += this.ITEM_INTV;
  5485. this.dragRefOffset -= this.ITEM_INTV;
  5486. this.itemMove(indexA, indexA - 1);
  5487. });
  5488. }
  5489. })
  5490. .onActionEnd((event: GestureEvent) => {
  5491. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5492. this.dragItem = -1
  5493. this.neighborItem = -1
  5494. })
  5495. animateTo({
  5496. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  5497. }, () => {
  5498. this.scaleItem = -1
  5499. })
  5500. })
  5501. )
  5502. .onCancel(() => {
  5503. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5504. this.dragItem = -1
  5505. this.neighborItem = -1
  5506. })
  5507. animateTo({
  5508. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  5509. }, () => {
  5510. this.scaleItem = -1
  5511. })
  5512. })
  5513. ) //拖动List关键代码结束
  5514. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5515. // 加载中指示器
  5516. if (this.isLoadingPage) {
  5517. ListItem() {
  5518. Row() {
  5519. LoadingProgress()
  5520. .width(30)
  5521. .height(30)
  5522. .color(this.themeColor)
  5523. Text('加载中...')
  5524. .margin({ left: 10 })
  5525. .fontSize(14)
  5526. .fontColor($r('app.color.text_color'))
  5527. }
  5528. .width('100%')
  5529. .justifyContent(FlexAlign.Center)
  5530. .padding(20)
  5531. }
  5532. }
  5533. }
  5534. .onScrollStart(() => {
  5535. this.isScrolling = true
  5536. this.isShowAlphaBet = true
  5537. })
  5538. .onScrollIndex((start: number,center:number,end:number) => {
  5539. this.selectedIndex = start
  5540. if(start >= 0 && start < this.videoLocalList.length){
  5541. this.selectAlphaBetIndex = this.findAlphaBetIndex(this.videoLocalList[start])
  5542. }
  5543. })
  5544. .onScrollStop(() => {
  5545. if(this.isScrolling){
  5546. this.isScrolling = false
  5547. }
  5548. this.isShowAlphaBet = false
  5549. })
  5550. .onReachEnd(() => {
  5551. // 触底加载下一页
  5552. Logger.info('heanup LocalMusic', `onReachEnd: hasMore=${this.hasMoreData}, isLoading=${this.isLoadingPage}`);
  5553. if (this.isCanBack && (this.modeType === 2 || this.modeType === 3)) {
  5554. return;
  5555. }
  5556. if (this.hasMoreData && !this.isLoadingPage) {
  5557. this.loadNextPage();
  5558. }
  5559. })
  5560. .scrollBar(BarState.Off)
  5561. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  5562. .gesture(PinchGesture({ fingers: 2 })
  5563. .onActionEnd((event: GestureEvent) => {
  5564. this.setlistTwoFingers()
  5565. })
  5566. .onActionUpdate(e => {
  5567. this.scaleValue = this.pinchValue * e.scale
  5568. })
  5569. .onActionStart(e => {
  5570. }))
  5571. .contentStartOffset(this.topSafeHeight + 55)
  5572. .scrollBar(BarState.Off)
  5573. .contentEndOffset(this.bottomBarHeight+this.bottomSafeHeight)
  5574. .cachedCount(10)
  5575. // .reuseId('list_item')
  5576. .borderRadius(20)
  5577. .layoutWeight(1)
  5578. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  5579. .lanes(
  5580. new BreakpointType<number>({
  5581. sm: 1,
  5582. md: 2,
  5583. lg: 2,
  5584. xl: 3,
  5585. xxl: 4
  5586. }).getValue(this.currentBreakpoint),
  5587. new BreakpointType<number>({
  5588. sm: 0,
  5589. md: 12,
  5590. lg: 12,
  5591. xl: 16,
  5592. xxl: 20
  5593. }).getValue(this.currentBreakpoint)
  5594. )
  5595. .onAreaChange((oldValue: Area, newValue: Area) => {
  5596. this.listArea = newValue
  5597. if (this.twoFingerType == 3) {
  5598. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  5599. } else if (this.twoFingerType == 2) {
  5600. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  5601. } else if (this.twoFingerType == 1) {
  5602. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  5603. }
  5604. })
  5605. .onScrollFrameBegin((offset: number) => {
  5606. // 获取当前滚动偏移量
  5607. if(this.autoHideTitle){
  5608. const currentOffsetY = this.listScroller.currentOffset().yOffset;
  5609. // 判断滚动方向
  5610. if (currentOffsetY > this.prevOffsetY) {
  5611. // console.log("onecold 向上滚动");
  5612. this.isShowTitleBar = false
  5613. } else if (currentOffsetY < this.prevOffsetY) {
  5614. // console.log("onecold 向下滚动");
  5615. this.isShowTitleBar = true
  5616. }
  5617. // 更新前一次偏移量
  5618. this.prevOffsetY = currentOffsetY;
  5619. }
  5620. return { offsetRemain: offset };
  5621. })
  5622. }
  5623. setBarHeightNormal() {
  5624. this.hideDone = false;
  5625. this.getUIContext().animateTo({
  5626. duration: 300
  5627. }, () => {
  5628. this.bottomBarHeight = 68 + 0;
  5629. this.topBarHeight = 50 + 0;
  5630. this.barOpacity = 1;
  5631. this.barBottomOpacity = 1
  5632. this.currentYOffset = 0;
  5633. this.isHiding = false;
  5634. });
  5635. }
  5636. setBarHeightHide(offset: number) {
  5637. if (offset > 0 && !this.hideDone) {
  5638. this.currentYOffset += offset;
  5639. if (this.currentYOffset <= 100) {
  5640. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  5641. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  5642. this.barOpacity = 1 - this.currentYOffset / 100;
  5643. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  5644. } else {
  5645. this.topBarHeight = 0;
  5646. this.bottomBarHeight = 0;
  5647. this.barBottomOpacity = 0
  5648. this.barOpacity = 0;
  5649. this.hideDone = true;
  5650. }
  5651. this.isHiding = true;
  5652. }
  5653. if (offset < 0 && this.isHiding) {
  5654. this.hideDone = false;
  5655. this.getUIContext().animateTo({
  5656. duration: 300
  5657. }, () => {
  5658. this.bottomBarHeight = 68 + 0;
  5659. this.topBarHeight = 50 + 0;
  5660. this.barOpacity = 1;
  5661. this.barBottomOpacity = 1
  5662. this.currentYOffset = 0;
  5663. this.isHiding = false;
  5664. });
  5665. }
  5666. }
  5667. //这个方法没隐藏bottomBar,只隐藏topbar
  5668. setBarHeightHide2(offset: number) {
  5669. if (offset > 0 && !this.hideDone) {
  5670. this.currentYOffset += offset;
  5671. if (this.currentYOffset <= 100) {
  5672. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  5673. this.barOpacity = 1 - this.currentYOffset / 100;
  5674. } else {
  5675. this.topBarHeight = 0;
  5676. this.barOpacity = 0;
  5677. this.hideDone = true;
  5678. }
  5679. this.isHiding = true;
  5680. }
  5681. if (offset < 0 && this.isHiding) {
  5682. this.hideDone = false;
  5683. this.getUIContext().animateTo({
  5684. duration: 300
  5685. }, () => {
  5686. this.topBarHeight = 50 + 0;
  5687. this.barOpacity = 1;
  5688. this.currentYOffset = 0;
  5689. this.isHiding = false;
  5690. });
  5691. }
  5692. }
  5693. private async doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean,isOpen?:boolean) {
  5694. Logger.info(`heanup doPlay被调用 - 歌曲: ${item.name}, 文件路径: ${item.filePath}, 索引: ${index}, 类型: ${item.type}, isFromSonPlayList: ${isFromSonPlayList}`)
  5695. switch (item.type) {
  5696. case CommonConstants.TYPE_IS_DIR:
  5697. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  5698. let offsetB = 0
  5699. if(this.twoFingerType==4){
  5700. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  5701. let cur = this.waterScroller.currentOffset()
  5702. if (cur && typeof cur.yOffset === 'number') {
  5703. offsetB = cur.yOffset
  5704. }
  5705. }
  5706. this.mScrollMap.set('lastWaterDirScrollOffset', offsetB)
  5707. }else
  5708. if (this.isGridMusic) {
  5709. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  5710. let cur = this.scroller.currentOffset()
  5711. if (cur && typeof cur.yOffset === 'number') {
  5712. offsetB = cur.yOffset
  5713. }
  5714. }
  5715. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  5716. } else {
  5717. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  5718. let cur = this.listScroller.currentOffset()
  5719. if (cur && typeof cur.yOffset === 'number') {
  5720. offsetB = cur.yOffset
  5721. }
  5722. }
  5723. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  5724. }
  5725. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  5726. this.showVerifyDialog()
  5727. this.currentTitleName = '私密音频'
  5728. this.currentTitleCover = $r('app.media.alt')
  5729. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  5730. this.titleName = '最近播放'
  5731. this.currentTitleCover = $r('app.media.alt')
  5732. this.currentTitleName = '最近播放'
  5733. //加载动画效果
  5734. this.updateListData(this.historyList, true)
  5735. // this.videoLocalList = this.historyList
  5736. if (ArrayUtil.isEmpty(this.historyList)) {
  5737. ToastUtil.showToast('最近播放记录空空如也')
  5738. } else {
  5739. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  5740. }
  5741. this.isHistory = true
  5742. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  5743. this.titleName = '我的收藏'
  5744. this.currentTitleName = '我的收藏'
  5745. this.currentTitleCover = $r('app.media.alt')
  5746. //加载动画效果
  5747. this.updateListData(this.favList, true)
  5748. if (ArrayUtil.isEmpty(this.favList)) {
  5749. ToastUtil.showToast('无音乐收藏记录')
  5750. } else {
  5751. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  5752. }
  5753. this.isFavMusic = true
  5754. } else {
  5755. this.currentTitleName = item.name
  5756. this.currentPath = item.filePath
  5757. this.currentTitleCover = $r('app.media.alt')
  5758. this.getSortedFiles(this.currentPath)
  5759. }
  5760. //进入歌单的时候的滚动位置在顶部
  5761. if(this.twoFingerType==4){
  5762. setTimeout(() => {
  5763. this.waterScroller.scrollEdge(Edge.Top)
  5764. this.scroller.scrollEdge(Edge.Top)
  5765. }, 200)
  5766. }else{
  5767. if (this.isGridMusic) {
  5768. this.scroller.scrollToIndex(0,false)
  5769. }else{
  5770. this.listScroller.scrollToIndex(0,false)
  5771. }
  5772. }
  5773. this.rightTopImage = $r('sys.symbol.chevron_left')
  5774. break;
  5775. case CommonConstants.TYPE_IS_ARTIST:
  5776. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  5777. let offsetA = 0
  5778. if(this.twoFingerType==4){
  5779. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  5780. let cur = this.waterScroller.currentOffset()
  5781. if (cur && typeof cur.yOffset === 'number') {
  5782. offsetA = cur.yOffset
  5783. }
  5784. }
  5785. this.mScrollMap.set('lastWaterArtistScrollOffset', offsetA)
  5786. }else
  5787. if (this.isGridMusic) {
  5788. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  5789. let cur = this.scroller.currentOffset()
  5790. if (cur && typeof cur.yOffset === 'number') {
  5791. offsetA = cur.yOffset
  5792. }
  5793. }
  5794. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  5795. } else {
  5796. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  5797. let cur = this.listScroller.currentOffset()
  5798. if (cur && typeof cur.yOffset === 'number') {
  5799. offsetA = cur.yOffset
  5800. }
  5801. }
  5802. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  5803. }
  5804. let mList = this.artistMap.get(item.name)
  5805. if (mList === undefined || ArrayUtil.isEmpty(mList)) {
  5806. mList = await this.table.querySongsByArtist(item.name, this.sortType);
  5807. if (ArrayUtil.isNotEmpty(mList)) {
  5808. this.artistMap.set(item.name, mList);
  5809. }
  5810. }
  5811. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  5812. Utility.doSortListAscending(mList)
  5813. const nextArtistCountMap = new Map(this.artistSongCountMap);
  5814. nextArtistCountMap.set(item.name, mList.length);
  5815. this.artistSongCountMap = nextArtistCountMap;
  5816. this.isCanBack = true
  5817. this.hasMoreData = false
  5818. this.isLoadingPage = false
  5819. this.pageCache.clear()
  5820. this.totalCount = mList.length
  5821. this.titleName = item.name
  5822. this.currentTitleName = '艺术家:' + item.name
  5823. if (item.pixelMapPath) {
  5824. this.currentTitleCover = item.pixelMapPath
  5825. }
  5826. this.updateListData(mList)
  5827. } else {
  5828. ToastUtil.showToast('未找到该艺术家的歌曲');
  5829. return;
  5830. }
  5831. this.rightTopImage = $r('sys.symbol.chevron_left')
  5832. //进入歌单的时候的滚动位置在顶部
  5833. if(this.twoFingerType==4){
  5834. setTimeout(() => {
  5835. this.waterScroller.scrollEdge(Edge.Top)
  5836. this.scroller.scrollEdge(Edge.Top)
  5837. }, 380)
  5838. }else{
  5839. if (this.isGridMusic) {
  5840. this.scroller.scrollEdge(Edge.Top)
  5841. }else{
  5842. this.listScroller.scrollEdge(Edge.Top)
  5843. }
  5844. }
  5845. break;
  5846. case CommonConstants.TYPE_IS_ALBUM:
  5847. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  5848. let offset = 0
  5849. if(this.twoFingerType==4){
  5850. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  5851. let cur = this.waterScroller.currentOffset()
  5852. if (cur && typeof cur.yOffset === 'number') {
  5853. offset = cur.yOffset
  5854. }
  5855. }
  5856. this.mScrollMap.set('lastWaterAlBumScrollOffset', offset)
  5857. }else
  5858. if (this.isGridMusic) {
  5859. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  5860. let cur = this.scroller.currentOffset()
  5861. if (cur && typeof cur.yOffset === 'number') {
  5862. offset = cur.yOffset
  5863. }
  5864. }
  5865. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  5866. } else {
  5867. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  5868. let cur = this.listScroller.currentOffset()
  5869. if (cur && typeof cur.yOffset === 'number') {
  5870. offset = cur.yOffset
  5871. }
  5872. }
  5873. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  5874. }
  5875. let albumList = this.albumMap.get(item.name)
  5876. if (albumList === undefined || ArrayUtil.isEmpty(albumList)) {
  5877. albumList = await this.table.querySongsByAlbum(item.name, this.sortType);
  5878. if (ArrayUtil.isNotEmpty(albumList)) {
  5879. this.albumMap.set(item.name, albumList);
  5880. }
  5881. }
  5882. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  5883. Utility.doSortListAscending(albumList)
  5884. const nextAlbumCountMap = new Map(this.albumSongCountMap);
  5885. nextAlbumCountMap.set(item.name, albumList.length);
  5886. this.albumSongCountMap = nextAlbumCountMap;
  5887. this.isCanBack = true
  5888. this.hasMoreData = false
  5889. this.isLoadingPage = false
  5890. this.pageCache.clear()
  5891. this.totalCount = albumList.length
  5892. this.titleName = item.name
  5893. this.currentTitleName = '专辑:' + item.name
  5894. if (item.pixelMapPath) {
  5895. this.currentTitleCover = item.pixelMapPath
  5896. }
  5897. this.updateListData(albumList)
  5898. this.mScrollMap.set(item.name, this.selectedIndex)
  5899. this.rightTopImage = $r('sys.symbol.chevron_left')
  5900. } else {
  5901. ToastUtil.showToast('未找到该专辑的歌曲');
  5902. return;
  5903. }
  5904. //进入歌单的时候的滚动位置在顶部
  5905. if(this.twoFingerType==4){
  5906. setTimeout(() => {
  5907. this.waterScroller.scrollEdge(Edge.Top)
  5908. this.scroller.scrollEdge(Edge.Top)
  5909. }, 380)
  5910. }else{
  5911. if (this.isGridMusic) {
  5912. this.scroller.scrollEdge(Edge.Top)
  5913. }else{
  5914. this.listScroller.scrollEdge(Edge.Top)
  5915. }
  5916. }
  5917. break;
  5918. case CommonConstants.TYPE_IS_CSJAD:
  5919. return
  5920. break;
  5921. case CommonConstants.TYPE_LOCAL:
  5922. if(item&&item.filePath.toLowerCase().endsWith('.cue')){
  5923. const cueinfo:CueInfo = await parseCueFile(item.filePath)
  5924. const cueTracks:CueTrack[] = cueinfo.tracks
  5925. console.log('onecold cue cueTracks =', JSON.stringify(cueTracks));
  5926. if(ArrayUtil.isNotEmpty(cueTracks)){
  5927. this.showCueDialog(cueTracks,cueinfo)
  5928. }
  5929. // this.showCueSheet = !this.showCueSheet
  5930. return
  5931. }
  5932. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  5933. this.stop();
  5934. }
  5935. if (isOpen) {
  5936. this.currentSong = item
  5937. if (index !== undefined) {
  5938. this.curIndex = index
  5939. }
  5940. this.songList = []
  5941. this.songList.push(item)
  5942. this.sonDataSource.pushArrayData(this.songList)
  5943. this.playQueueScope = 'single'
  5944. }else if(isFromSonPlayList){ //点击来自右下角的播放列表
  5945. this.currentSong = item
  5946. if (index !== undefined) {
  5947. this.curIndex = index
  5948. }
  5949. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  5950. Logger.info(`heanup isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  5951. this.playQueueScope = 'playlist'
  5952. }else {
  5953. const globalVideoList = this.buildPlayQueueFromView();
  5954. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  5955. if (this.curIndex < 0) {
  5956. globalVideoList.push(item);
  5957. this.curIndex = globalVideoList.length - 1;
  5958. }
  5959. this.songList = globalVideoList
  5960. this.sonDataSource.pushArrayData(this.songList)
  5961. this.currentSong = this.songList[this.curIndex]
  5962. Logger.info(`heanup doPlay设置播放列表 - 总歌曲数: ${this.songList.length}, 当前索引: ${this.curIndex}, 当前歌曲: ${this.currentSong?.name}`)
  5963. }
  5964. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  5965. this.videoUrl = this.currentSong.filePath
  5966. this.name = this.currentSong.name
  5967. this.cover = this.currentSong.pixelMapPath
  5968. this.artist = this.currentSong.artist
  5969. LogUtil.info('onecold this.currentSong.cover =' + this.currentSong.pixelMapPath)
  5970. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  5971. this.startPlayOrResumePlay()
  5972. break;
  5973. case CommonConstants.TYPE_WEBDAV:
  5974. case CommonConstants.TYPE_SMB:
  5975. case CommonConstants.TYPE_NAVIDROME:
  5976. case CommonConstants.TYPE_FTP:
  5977. case CommonConstants.TYPE_BAIDU:
  5978. case CommonConstants.TYPE_JELLYFIN:
  5979. case CommonConstants.TYPE_EMBY:
  5980. // 处理网络音频播放(WebDAV/SMB)
  5981. Logger.info(`heanup 处理云端音频播放: ${item.name}, URL: ${item.filePath}`)
  5982. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  5983. this.stop();
  5984. }
  5985. if (isOpen) {
  5986. this.currentSong = item
  5987. if (index !== undefined) {
  5988. this.curIndex = index
  5989. }
  5990. this.songList = []
  5991. this.songList.push(item)
  5992. this.sonDataSource.pushArrayData(this.songList)
  5993. } else if (isFromSonPlayList) {
  5994. // 点击来自右下角的播放列表
  5995. this.currentSong = item
  5996. if (index !== undefined) {
  5997. this.curIndex = index
  5998. }
  5999. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  6000. Logger.info(`heanup 网络音频 isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  6001. } else {
  6002. // 从全局网络音频列表中查找
  6003. let globalVideoList = this.videoLocalList.filter(video => isRemoteCloudType(video.type)) as VideoItem[];
  6004. this.curIndex = globalVideoList.findIndex(video => video.filePath === item.filePath);
  6005. if (this.curIndex === -1 && index !== undefined) {
  6006. this.curIndex = index;
  6007. }
  6008. this.songList = globalVideoList.length > 0 ? globalVideoList : [item];
  6009. this.currentSong = this.songList[this.curIndex];
  6010. this.sonDataSource.pushArrayData(this.songList)
  6011. }
  6012. await this.hydrateRemoteSongFromDb(this.currentSong);
  6013. await this.hydrateRemoteSongFromDb(this.currentSong);
  6014. AppStorage.setOrCreate('currentSong', this.currentSong);
  6015. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  6016. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  6017. context: this.context,
  6018. autoParseMusicName: this.autoParseMusicName
  6019. });
  6020. Logger.info(TAG, `WebDAV URL同步构建完成(分支2): ${this.videoUrl}`);
  6021. this.name = this.currentSong.name
  6022. this.cover = this.currentSong.pixelMapPath
  6023. this.artist = this.currentSong.artist
  6024. Logger.info(`heanup 准备播放网络音频 - 歌名: ${this.name}, 艺术家: ${this.artist}, 完整URL: ${this.videoUrl}`)
  6025. this.startPlayOrResumePlay()
  6026. break;
  6027. }
  6028. }
  6029. private cueComponentId: number = 0
  6030. //显示cue分轨列表对话框
  6031. showCueDialog(cueTracks:CueTrack[],cueinfo:CueInfo){
  6032. this.getUIContext().getPromptAction().openCustomDialog({
  6033. builder: () => {
  6034. this.cueComptentBuilder(cueTracks,cueinfo)
  6035. },
  6036. isModal:true,
  6037. showInSubWindow:false,
  6038. maskColor: Color.Transparent,
  6039. dialogTransition: // 设置弹窗内容显示的过渡效果
  6040. TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  6041. .animation({ duration: 600, curve: Curve.Smooth }),
  6042. maskTransition: // 设置蒙层显示的过渡效果
  6043. TransitionEffect.opacity(0.5)
  6044. .animation({ duration: 600, curve: Curve.Smooth })
  6045. }).then((dialogId: number) => {
  6046. this.cueComponentId = dialogId
  6047. })
  6048. .catch((error: BusinessError) => {
  6049. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  6050. })
  6051. }
  6052. @Builder
  6053. cueComptentBuilder(cueTracks:CueTrack[]=[],cueinfo:CueInfo){
  6054. CueComptent({
  6055. title:cueinfo.title,
  6056. cueTracks:cueTracks,
  6057. isLongNameRoLL:this.isLongNameRoLL,
  6058. onCancel:()=>{
  6059. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId)
  6060. },
  6061. onDoItemClick: async (item: CueTrack, index: number)=>{
  6062. //获取cueinfo对应的filePath
  6063. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  6064. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, cueinfo.filePath)
  6065. this.currentSong = Utility.getItemByFilePath(globalVideoList, cueinfo.filePath)
  6066. console.info('onecold cueinfo.filePath=', cueinfo.filePath)
  6067. console.info('onecold this.currentSong =', JSON.stringify(this.currentSong))
  6068. if (this.currentSong){
  6069. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6070. this.stop();//播放之前先停止之前播放。
  6071. }
  6072. this.songList = globalVideoList
  6073. this.sonDataSource.pushArrayData(this.songList)
  6074. if (this.currentSong) {
  6075. try {
  6076. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  6077. context: this.context,
  6078. autoParseMusicName: this.autoParseMusicName
  6079. });
  6080. } catch (error) {
  6081. Logger.error(TAG, `CUE 点播构建播放地址失败: ${(error as Error).message}`);
  6082. this.videoUrl = this.currentSong.filePath;
  6083. }
  6084. }
  6085. this.name = item.title||this.currentSong.name
  6086. this.cover = this.currentSong.pixelMapPath
  6087. this.artist = item.performer||this.currentSong.artist
  6088. this.currentSong.name = this.name
  6089. this.currentSong.artist = this.artist
  6090. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  6091. this.startPlayOrResumePlay(item.startOffset)//从cue的某个位置开始播放
  6092. }
  6093. }
  6094. })
  6095. }
  6096. @State isFrontWhite: boolean = false
  6097. setShowPlayTrue(){
  6098. this.getUIContext()?.animateTo({
  6099. duration: 500,
  6100. curve: Curve.Friction
  6101. }, () => {
  6102. this.isShowPlay = true;
  6103. });
  6104. }
  6105. setShowPlayFalse(){
  6106. this.getUIContext()?.animateTo({
  6107. duration: 500,
  6108. curve: Curve.Friction
  6109. }, () => {
  6110. this.isShowPlay = false;
  6111. });
  6112. }
  6113. //打开播放页
  6114. showPlayerView() {
  6115. console.info('onecold showPlayerView this.songList'+ JSON.stringify(this.songList))
  6116. if (ArrayUtil.isNotEmpty(this.songList)) {
  6117. // this.setShowPlayTrue()
  6118. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
  6119. this.initLyric(lyricPath);
  6120. this.startAutoHide();
  6121. } else {
  6122. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  6123. }
  6124. }
  6125. //打开播放列表
  6126. openPlayList(){
  6127. if (ArrayUtil.isNotEmpty(this.songList)) {
  6128. this.isShowSheet = !this.isShowSheet;
  6129. this.isFrontWhite = false
  6130. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  6131. this.scrollIndex()
  6132. } else {
  6133. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  6134. }
  6135. }
  6136. scrollIndex(){
  6137. try {
  6138. setTimeout(() => {
  6139. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  6140. if(this.curIndex>60){
  6141. this.playListScroller.scrollToIndex(this.curIndex,false, ScrollAlign.CENTER)
  6142. }else{
  6143. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  6144. }
  6145. })
  6146. }, 123)
  6147. }catch (error) {
  6148. console.error(`onecold scrollIndex出错: ${error}`);
  6149. }
  6150. }
  6151. //播放列表布局
  6152. @Builder
  6153. PlayListSheet() {
  6154. Column() {
  6155. this.PlayList()
  6156. }
  6157. .width('100%')
  6158. .height('100%')
  6159. }
  6160. @State titleStr: string = ''
  6161. @State ablumStr: string = ''
  6162. @State artistStr: string = ''
  6163. @State lyricConStr: string = ''
  6164. @State currentEditItem: string = ''
  6165. @State yearStr: string = ''
  6166. @State trackStr: string = ''
  6167. @State genreStr: string = ''
  6168. @State imagePathStr: string = ''
  6169. @State albumArtistStr: string = ''
  6170. @State composerStr: string = ''
  6171. @State lyricistStr: string = ''
  6172. @State commentStr: string = ''
  6173. @State discStr: string = ''
  6174. doUpdateData() {
  6175. setTimeout(async () => {
  6176. if (this.modeType === 0) {
  6177. this.deleteCache(this.currentPath)
  6178. await this.resetAndLoadFirstPage();
  6179. }else if (this.modeType === 1){
  6180. await this.resetAndLoadFirstPage();
  6181. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6182. }
  6183. }, 500)
  6184. }
  6185. doAllUpdateData() {
  6186. setTimeout(async () => {
  6187. if (this.modeType === 0) {
  6188. this.deleteCache(this.currentPath)
  6189. await this.resetAndLoadFirstPage();
  6190. }else{
  6191. await this.resetAndLoadFirstPage();
  6192. }
  6193. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6194. workerInstance.postMessage({ code: 3, data: this.context });
  6195. workerInstance.postMessage({ code: 4, data: this.context });
  6196. }, 999)
  6197. }
  6198. /**
  6199. * 加载指定页的数据
  6200. */
  6201. private async loadPage(pageIndex: number, append: boolean = true): Promise<void> {
  6202. try {
  6203. // 1. 检查缓存
  6204. if (this.pageCache.has(pageIndex)) {
  6205. Logger.info('heanup LocalMusic', `loadPage: 从缓存加载 page=${pageIndex}`);
  6206. const cachedData = this.pageCache.get(pageIndex)!;
  6207. if (append) {
  6208. this.videoLocalList = [...this.videoLocalList, ...cachedData];
  6209. } else {
  6210. this.videoLocalList = cachedData;
  6211. }
  6212. this.dataSource.pushArrayData(this.videoLocalList);
  6213. return;
  6214. }
  6215. this.isLoadingPage = true;
  6216. Logger.info('heanup LocalMusic', `loadPage: 开始加载 page=${pageIndex}, size=${this.pageSize}, mode=${this.modeType}`);
  6217. // 2. 构造查询参数
  6218. const options: PageQueryOptions = {
  6219. pageIndex: pageIndex,
  6220. pageSize: this.pageSize,
  6221. sortType: this.sortType,
  6222. searchKeyword: this.isSearchMode ? this.searchText : undefined
  6223. };
  6224. // 根据 modeType 补充查询条件
  6225. if (this.modeType === 0) {
  6226. options.parentPath = this.currentPath;
  6227. }
  6228. // 3. 执行查询
  6229. let result: PageQueryResult = { items: [], totalCount: 0, hasMore: false };
  6230. switch (this.modeType) {
  6231. case 0:
  6232. result = await this.table.queryByParentPathPaged(options);
  6233. // modeType=0时,第一页需要添加文件夹列表
  6234. if (pageIndex === 0 && !this.isSearchMode) {
  6235. const directories: VideoItem[] = await this.loadDirectories(this.currentPath);
  6236. result.items = [...directories, ...result.items];
  6237. result.totalCount += directories.length;
  6238. }
  6239. break;
  6240. case 1:
  6241. result = await this.table.queryMediaLibraryPaged(options);
  6242. break;
  6243. case 2:
  6244. result = await this.table.queryArtistsPaged(options);
  6245. break;
  6246. case 3:
  6247. result = await this.table.queryAlbumsPaged(options);
  6248. break;
  6249. default:
  6250. result = await this.table.queryMediaLibraryPaged(options);
  6251. break;
  6252. }
  6253. if (!result || result.items.length === 0) {
  6254. Logger.info('heanup LocalMusic', 'loadPage: 查询结果为空');
  6255. this.isLoadingPage = false;
  6256. this.hasMoreData = false;
  6257. // 即使为空也要更新UI,显示空状态
  6258. this.totalCount = 0;
  6259. this.videoLocalList = [];
  6260. this.dataSource.pushArrayData(this.videoLocalList);
  6261. this.setButtonStatus();
  6262. return;
  6263. }
  6264. // 4. 更新状态和缓存
  6265. this.totalCount = result.totalCount;
  6266. this.hasMoreData = result.hasMore;
  6267. if (this.modeType === 1) {
  6268. this.mediaKuCount = result.totalCount;
  6269. }
  6270. if (this.modeType === 2 && result.countMap) {
  6271. this.mergeArtistCountMap(result.countMap);
  6272. } else if (this.modeType === 3 && result.countMap) {
  6273. this.mergeAlbumCountMap(result.countMap);
  6274. }
  6275. Logger.info('heanup LocalMusic', `loadPage: 查询完成 items=${result.items.length}, total=${result.totalCount}, hasMore=${result.hasMore}`);
  6276. // 缓存管理 - 只保留最近3页
  6277. this.pageCache.set(pageIndex, result.items);
  6278. this.cleanOldCache(pageIndex);
  6279. // 5. 更新显示列表
  6280. if (append) {
  6281. this.videoLocalList = [...this.videoLocalList, ...result.items];
  6282. } else {
  6283. this.videoLocalList = result.items;
  6284. }
  6285. this.dataSource.pushArrayData(this.videoLocalList);
  6286. this.setButtonStatus();
  6287. this.setAlphaBet();
  6288. void this.prefetchNextPage(pageIndex + 1);
  6289. this.isLoadingPage = false;
  6290. } catch (err) {
  6291. const error = err as Error;
  6292. Logger.error('heanup LocalMusic', `loadPage error: ${error.message}`);
  6293. ToastUtil.showToast('加载数据失败');
  6294. this.isLoadingPage = false;
  6295. this.hasMoreData = false;
  6296. }
  6297. }
  6298. /**
  6299. * 清理旧缓存 - 只保留当前页前后各1页
  6300. */
  6301. private cleanOldCache(currentPage: number): void {
  6302. const pagesToKeep = new Set([currentPage - 1, currentPage, currentPage + 1]);
  6303. const keysToDelete: number[] = [];
  6304. this.pageCache.forEach((_, page) => {
  6305. if (!pagesToKeep.has(page)) {
  6306. keysToDelete.push(page);
  6307. }
  6308. });
  6309. keysToDelete.forEach(page => this.pageCache.delete(page));
  6310. if (keysToDelete.length > 0) {
  6311. Logger.info('heanup LocalMusic', `cleanOldCache: 清理了 ${keysToDelete.length} 页缓存`);
  6312. }
  6313. }
  6314. private async prefetchNextPage(nextPage: number): Promise<void> {
  6315. if (this.modeType !== 2 && this.modeType !== 3) {
  6316. return;
  6317. }
  6318. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  6319. return;
  6320. }
  6321. if (!this.hasMoreData || this.pageCache.has(nextPage) || this.prefetchingPages.has(nextPage)) {
  6322. return;
  6323. }
  6324. this.prefetchingPages.add(nextPage);
  6325. try {
  6326. const options: PageQueryOptions = {
  6327. pageIndex: nextPage,
  6328. pageSize: this.pageSize,
  6329. sortType: this.sortType,
  6330. searchKeyword: this.isSearchMode ? this.searchText : undefined
  6331. };
  6332. let result: PageQueryResult = { items: [], totalCount: 0, hasMore: false };
  6333. if (this.modeType === 2) {
  6334. result = await this.table.queryArtistsPaged(options);
  6335. if (result.countMap) {
  6336. this.mergeArtistCountMap(result.countMap);
  6337. }
  6338. } else if (this.modeType === 3) {
  6339. result = await this.table.queryAlbumsPaged(options);
  6340. if (result.countMap) {
  6341. this.mergeAlbumCountMap(result.countMap);
  6342. }
  6343. }
  6344. if (result.items.length > 0) {
  6345. this.pageCache.set(nextPage, result.items);
  6346. this.cleanOldCache(nextPage);
  6347. }
  6348. } catch (err) {
  6349. const error = err as Error;
  6350. Logger.warn('heanup LocalMusic', `prefetchNextPage error: ${error.message}`);
  6351. } finally {
  6352. this.prefetchingPages.delete(nextPage);
  6353. }
  6354. }
  6355. private mergeArtistCountMap(countMap: Map<string, number>): void {
  6356. const nextMap = new Map(this.artistSongCountMap);
  6357. countMap.forEach((count, artist) => {
  6358. nextMap.set(artist, count);
  6359. });
  6360. this.artistSongCountMap = nextMap;
  6361. }
  6362. private mergeAlbumCountMap(countMap: Map<string, number>): void {
  6363. const nextMap = new Map(this.albumSongCountMap);
  6364. countMap.forEach((count, album) => {
  6365. nextMap.set(album, count);
  6366. });
  6367. this.albumSongCountMap = nextMap;
  6368. }
  6369. private getArtistSongCount(artist: string): number {
  6370. return this.artistSongCountMap.get(artist) ?? this.artistMap.get(artist)?.length ?? 0;
  6371. }
  6372. private getAlbumSongCount(album: string): number {
  6373. return this.albumSongCountMap.get(album) ?? this.albumMap.get(album)?.length ?? 0;
  6374. }
  6375. /**
  6376. * 加载文件夹列表(仅用于modeType=0的首页模式)
  6377. */
  6378. private async loadDirectories(curPath: string): Promise<VideoItem[]> {
  6379. try {
  6380. Logger.info('heanup LocalMusic', `loadDirectories: 开始加载文件夹 path=${curPath}`);
  6381. // 检查缓存
  6382. const cacheKey = curPath + "_dirList";
  6383. const cachedDirList = this.findCache(cacheKey);
  6384. if (cachedDirList !== undefined && Array.isArray(cachedDirList)) {
  6385. Logger.info('heanup LocalMusic', `loadDirectories: 从缓存加载 count=${cachedDirList.length}`);
  6386. return cachedDirList as VideoItem[];
  6387. }
  6388. // 从文件系统读取
  6389. const fileList = FileUtil.listFileSync(curPath);
  6390. const directories: VideoItem[] = [];
  6391. for (let i = 0; i < fileList.length; i++) {
  6392. const path = curPath + '/' + fileList[i];
  6393. if (FileUtil.isDirectory(path)) {
  6394. const item: VideoItem = new VideoItem(
  6395. fileList[i].toString(),
  6396. fileList[i].toString(),
  6397. path,
  6398. CommonConstants.TYPE_IS_DIR,
  6399. 0,
  6400. ''
  6401. );
  6402. if (this.isShowDir(item.name)) {
  6403. directories.push(item);
  6404. }
  6405. }
  6406. }
  6407. // 排序
  6408. Utility.doSortListAscending(directories);
  6409. // 缓存文件夹列表
  6410. if (curPath === this.rootPath) {
  6411. this.dirList = directories;
  6412. this.addCache(cacheKey, directories);
  6413. }
  6414. Logger.info('heanup LocalMusic', `loadDirectories: 加载完成 count=${directories.length}`);
  6415. return directories;
  6416. } catch (err) {
  6417. const error = err as Error;
  6418. Logger.error('heanup LocalMusic', `loadDirectories error: ${error.message}`);
  6419. return [];
  6420. }
  6421. }
  6422. /**
  6423. * 构建播放队列(避免一次性加载全量)
  6424. */
  6425. private buildPlayQueueFromView(): Array<VideoItem> {
  6426. if (this.modeType === 4) {
  6427. this.playQueueScope = 'playlist';
  6428. return this.currentSongList;
  6429. }
  6430. if (this.isHistory) {
  6431. this.playQueueScope = 'history';
  6432. return this.historyList;
  6433. }
  6434. if (this.isFavMusic) {
  6435. this.playQueueScope = 'fav';
  6436. return this.favList;
  6437. }
  6438. this.playQueueScope = 'view';
  6439. return this.videoLocalList.filter((item: VideoItem) => item.type === CommonConstants.TYPE_LOCAL);
  6440. }
  6441. private async tryLoadNextPageForPlayback(): Promise<void> {
  6442. if (this.playQueueScope !== 'view') {
  6443. return;
  6444. }
  6445. if (this.isCanBack || this.isHistory || this.isFavMusic) {
  6446. return;
  6447. }
  6448. if (!this.hasMoreData || this.isLoadingPage) {
  6449. return;
  6450. }
  6451. await this.loadNextPage();
  6452. const nextList = this.videoLocalList.filter((item: VideoItem) => item.type === CommonConstants.TYPE_LOCAL);
  6453. if (nextList.length > this.songList.length) {
  6454. this.songList = nextList;
  6455. this.sonDataSource.pushArrayData(this.songList);
  6456. }
  6457. }
  6458. /**
  6459. * 重置分页状态并加载首页
  6460. */
  6461. private async resetAndLoadFirstPage(): Promise<void> {
  6462. Logger.info('heanup LocalMusic', 'resetAndLoadFirstPage: 重置分页状态');
  6463. this.currentPage = 0;
  6464. this.videoLocalList = [];
  6465. this.pageCache.clear();
  6466. this.hasMoreData = true;
  6467. this.totalCount = 0;
  6468. if (this.modeType === 2) {
  6469. this.artistSongCountMap = new Map();
  6470. } else if (this.modeType === 3) {
  6471. this.albumSongCountMap = new Map();
  6472. }
  6473. await this.loadPage(0, false);
  6474. }
  6475. /**
  6476. * 加载下一页
  6477. */
  6478. private async loadNextPage(): Promise<void> {
  6479. if (this.hasMoreData && !this.isLoadingPage) {
  6480. this.currentPage++;
  6481. Logger.info('heanup LocalMusic', `loadNextPage: 加载第 ${this.currentPage} 页`);
  6482. await this.loadPage(this.currentPage, true);
  6483. }
  6484. }
  6485. //编辑信息
  6486. async doEdit(item: VideoItem) {
  6487. if (!item) {
  6488. return
  6489. }
  6490. if (StrUtil.isEmpty(this.titleStr)) {
  6491. ToastUtil.showToast('标题不能为空')
  6492. return
  6493. }
  6494. //内嵌音乐标签不能开启监听
  6495. // this.deletionWatcher?.stop();
  6496. this.loadingDialogId = DialogHelper.showLoadingDialog()
  6497. await PermissionUtil.activatePermission(item.filePath)
  6498. let tempOutPath = ''
  6499. // 如果不是 packName 包下的文件,则直接路径用this.currentPath
  6500. if(!item.filePath.toLowerCase().includes(this.packName)){
  6501. tempOutPath = this.currentPath + '/' + item.fileName
  6502. }
  6503. console.info('onecold tempOutPath ='+tempOutPath)
  6504. //用户更改了封面,那就内嵌下封面
  6505. if(StrUtil.isNotEmpty(this.imagePathStr)){
  6506. const resultCover:boolean = await changeMusicCover(this.context,
  6507. item.filePath,this.imagePathStr,true,tempOutPath);
  6508. this.imagePathStr = ''
  6509. if(resultCover){
  6510. ToastUtil.showToast('内嵌封面成功')
  6511. }
  6512. }
  6513. const metadata:FFMpegTags = {
  6514. title: this.titleStr,
  6515. artist: this.artistStr,
  6516. album: this.ablumStr,
  6517. TYER:this.yearStr,
  6518. genre:this.genreStr,
  6519. track:this.trackStr,
  6520. album_artist:this.albumArtistStr,
  6521. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  6522. COMPOSER:this.composerStr,
  6523. lyricist:this.lyricistStr,
  6524. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  6525. comment:this.commentStr,
  6526. disc:this.discStr,
  6527. };
  6528. let newInput = item.filePath
  6529. //内嵌标签歌路径如果不是包含包名,输入newInput要赋值tempOutPath,然后tempOutPath为空
  6530. if(!item.filePath.toLowerCase().includes(this.packName)&&FileUtil.accessSync(tempOutPath)){
  6531. newInput = tempOutPath
  6532. tempOutPath = ''
  6533. }
  6534. const isWav:boolean = newInput.toLowerCase().endsWith('.wav');
  6535. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  6536. const result:boolean = await repairAudioMetadata(
  6537. newInput,
  6538. this.lyricConStr,
  6539. metadata,
  6540. true,
  6541. tempOutPath
  6542. );
  6543. if (result||isWav) {
  6544. if(!item.filePath.includes(this.packName)){
  6545. //内嵌成功的歌路径如果不是包含包名,则要入库
  6546. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newInput,
  6547. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  6548. this.table.insert(newItem, (id: number) => {
  6549. //加入数据库
  6550. if(this.modeType==0){
  6551. this.deleteCache(this.currentPath)
  6552. this.getSortedFiles(this.currentPath)
  6553. }
  6554. });
  6555. }
  6556. const task = new taskpool.Task(
  6557. updateInfoDb,
  6558. this.context,
  6559. item.filePath,
  6560. this.titleStr,
  6561. this.artistStr,
  6562. this.ablumStr,
  6563. this.lyricConStr,
  6564. this.yearStr,this.genreStr,
  6565. this.trackStr,this.albumArtistStr,
  6566. this.composerStr, this.lyricistStr,
  6567. this.commentStr,this.discStr
  6568. );
  6569. taskpool.execute(task, taskpool.Priority.HIGH).then((result) => {
  6570. if (result) {
  6571. console.log(" onecold 编辑信息成功,数据库已同步");
  6572. if(isWav){
  6573. ToastUtil.showToast('wav格式有可能内嵌失败,但是编辑信息成功')
  6574. }else{
  6575. ToastUtil.showToast('内嵌音乐标签成功')
  6576. }
  6577. this.isShowMoreView = false
  6578. this.name = this.titleStr
  6579. this.syncEditedFields(item)
  6580. if (item.filePath == this.currentSong?.filePath) {
  6581. this.currentSong.name = this.titleStr
  6582. this.artist = this.artistStr
  6583. this.currentSong.artist = this.artistStr
  6584. this.currentSong.album = this.ablumStr
  6585. this.currentSong.year = this.yearStr
  6586. this.currentSong.genre = this.genreStr
  6587. this.currentSong.track = this.trackStr
  6588. this.currentSong.lyricContent = this.lyricConStr
  6589. this.currentSong.ALBUMARTIST = this.albumArtistStr
  6590. this.currentSong.COMPOSER = this.composerStr
  6591. this.currentSong.LYRICIST = this.lyricistStr
  6592. this.currentSong.COMMENT = this.commentStr
  6593. }
  6594. this.syncListsAfterEdit(item.filePath)
  6595. this.doUpateEditedFields(item)
  6596. //this.doUpdateData()
  6597. } else {
  6598. // ToastUtil.showToast('保存失败' + error?.toString())
  6599. console.error(" onecold 编辑信息数据库失败 ");
  6600. }
  6601. // 关闭进度条
  6602. DialogHelper.closeDialog(this.loadingDialogId)
  6603. }).catch((error: Error) => {
  6604. // 关闭进度条
  6605. DialogHelper.closeDialog(this.loadingDialogId)
  6606. console.error('onecold Subtitle sync failed:', error);
  6607. });
  6608. console.log(' onecold 元数据标签更新成功,');
  6609. } else {
  6610. // 关闭进度条
  6611. DialogHelper.closeDialog(this.loadingDialogId)
  6612. ToastUtil.showToast('内嵌音乐标签失败')
  6613. console.log('onecold 内嵌音乐标签失败');
  6614. }
  6615. this.longItemFilePath = ''
  6616. this.tempLyricContent = ''
  6617. this.isShowEdit = false
  6618. }
  6619. // 内嵌标签更新当前内嵌的Item
  6620. async doUpateEditedFields(item: VideoItem) {
  6621. // 找到当前项在 videoLocalList 中的索引
  6622. const index = this.videoLocalList.findIndex(video => video.filePath === item.filePath);
  6623. if (index !== -1) {
  6624. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  6625. const updatedItem = await this.table.queryVideoByFilePath(item.filePath)
  6626. // 只有当查询结果不为 null 时才更新列表
  6627. if (updatedItem !== null) {
  6628. // 更新 videoLocalList 中的项(通过创建新数组触发响应式更新)
  6629. this.videoLocalList = [
  6630. ...this.videoLocalList.slice(0, index),
  6631. updatedItem,
  6632. ...this.videoLocalList.slice(index + 1)
  6633. ];
  6634. // 同步更新 LazyDataSource
  6635. this.dataSource.pushArrayData(this.videoLocalList)
  6636. } else {
  6637. ToastUtil.showToast('未找到更新的数据');
  6638. }
  6639. }
  6640. DialogHelper.closeDialog(this.loadingDialogId)
  6641. }
  6642. @Builder
  6643. editSheet(item: VideoItem) {
  6644. Scroll() {
  6645. Column() {
  6646. this.editDetail(item)
  6647. }
  6648. }
  6649. .width('100%')
  6650. .height('100%')
  6651. }
  6652. @Builder
  6653. editDetail(item: VideoItem) {
  6654. Column() {
  6655. if (item) {
  6656. Row() {
  6657. Stack() {
  6658. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  6659. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  6660. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
  6661. item.pixelMapPath)
  6662. .fillColor(this.themeColor)
  6663. .height(88)
  6664. .width(88)
  6665. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  6666. .borderRadius(12)
  6667. .clip(true)
  6668. .opacity(this.opacityItem)// 绑定透明度
  6669. .margin({ left: 25 })
  6670. }
  6671. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  6672. .onClick(async () => {
  6673. const imagePath:string | undefined = await this.goSelectImage(item);
  6674. if (imagePath) {
  6675. //用户更改过图片
  6676. this.imagePathStr = imagePath
  6677. }
  6678. })
  6679. .width('28%')
  6680. Row() {
  6681. Column() {
  6682. Text(item.name)
  6683. .fontSize(17)
  6684. .maxLines(1)
  6685. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6686. .animation({
  6687. duration: 555,
  6688. curve: 'Linear',
  6689. })
  6690. .fontColor(this.themeColor)
  6691. .margin({ left: 8 })
  6692. Row() {
  6693. Text(item.artist)
  6694. .fontSize(14)
  6695. .maxLines(1)
  6696. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6697. .padding({ top: 8 })
  6698. .fontColor(this.themeColor)
  6699. .margin({ left: 8 })
  6700. }
  6701. }
  6702. .height('100%')
  6703. .width(100)
  6704. .layoutWeight(1)
  6705. .justifyContent(FlexAlign.Center)
  6706. .alignItems(HorizontalAlign.Start)
  6707. Column() {
  6708. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6709. Row(){
  6710. SymbolGlyph($r('sys.symbol.picture'))
  6711. .fontSize(18)
  6712. .fontColor([Color.White])
  6713. Text('获取封面')
  6714. .margin({ left: 4 })
  6715. .fontSize(11)
  6716. .fontColor(Color.White)
  6717. .fontWeight(480)
  6718. .textAlign(TextAlign.Center)
  6719. }
  6720. .justifyContent(FlexAlign.Center)
  6721. }
  6722. .height(38)
  6723. .width(100)
  6724. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6725. .backgroundColor(this.themeColor)
  6726. .stateEffect(true)
  6727. .margin({ right: 35 })
  6728. .onClick(async () => {
  6729. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  6730. this.showTipsDialog();
  6731. return; // Return empty string when no API is configured
  6732. }
  6733. const imagePath:string | undefined = await this.doSearchCover(item,
  6734. this.titleStr,this.artistStr);
  6735. console.info('onecold imagePath = '+imagePath)
  6736. if (StrUtil.isNotEmpty(imagePath)) {
  6737. //用户更改过图片
  6738. this.imagePathStr = imagePath
  6739. ToastUtil.showToast('获取封面成功')
  6740. }else{
  6741. ToastUtil.showToast('获取封面失败,请重试')
  6742. }
  6743. })
  6744. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6745. Row(){
  6746. SymbolGlyph($r('sys.symbol.input_mode'))
  6747. .fontSize(18)
  6748. .fontColor([Color.White])
  6749. Text('获取歌词')
  6750. .margin({ left: 4 })
  6751. .fontSize(11)
  6752. .fontColor(Color.White)
  6753. .fontWeight(480)
  6754. .textAlign(TextAlign.Center)
  6755. }
  6756. .justifyContent(FlexAlign.Center)
  6757. }
  6758. .height(38)
  6759. .width(100)
  6760. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6761. .backgroundColor(this.themeColor)
  6762. .stateEffect(true)
  6763. .margin({ top: 9, right: 35 })
  6764. .onClick(async () => {
  6765. //判断有没有设置api
  6766. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  6767. if (StrUtil.isEmpty(apiUrl)) {
  6768. this.isLyricSetting = false
  6769. this.showTipsDialog()
  6770. return
  6771. }
  6772. let res: string | undefined = await getApiLyric(apiUrl,
  6773. this.titleStr, this.artistStr, false);
  6774. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  6775. this.lyricConStr = res;
  6776. ToastUtil.showToast('获取歌词成功')
  6777. }else{
  6778. ToastUtil.showToast('获取歌词失败,请重试')
  6779. }
  6780. })
  6781. }
  6782. .justifyContent(FlexAlign.Start)
  6783. }
  6784. .height('100%')
  6785. .justifyContent(FlexAlign.Start)
  6786. .layoutWeight(1)
  6787. }
  6788. .width('100%')
  6789. .height(98)
  6790. Row() {
  6791. Text('标题:')
  6792. .fontSize(14)
  6793. .fontColor($r('app.color.text_color'))
  6794. .margin({ left: 22 })
  6795. TextInput({ text: this.titleStr||item.name })
  6796. .height(40)
  6797. .maxLines(1)
  6798. .fontSize(14)
  6799. .layoutWeight(1)
  6800. .fontColor($r('app.color.text_color'))
  6801. .margin({ right: 15, left: 10 })
  6802. .onChange((val: string) => {
  6803. this.titleStr = val
  6804. })
  6805. Button('修复乱码',{ type: ButtonType.Capsule, stateEffect: true})
  6806. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6807. .backgroundColor(this.themeColor)
  6808. .fontSize(10)
  6809. .margin({ right: 20})
  6810. .onClick(async () => {
  6811. let hwTags = await extractHwMediaMetadata(item.filePath)
  6812. let artist = hwTags?.artist|| '';
  6813. let title = hwTags?.title|| '';
  6814. let album = hwTags?.album|| '';
  6815. console.info('onecold 乱码修正 artist='+artist);
  6816. console.info('onecold 乱码修正 title='+title);
  6817. console.info('onecold 乱码修正 album='+album);
  6818. this.titleStr = title;
  6819. this.artistStr = artist;
  6820. this.ablumStr = album;
  6821. })
  6822. }
  6823. .width('100%')
  6824. .margin({ top: 10, bottom: 10 })
  6825. .justifyContent(FlexAlign.Start)
  6826. Row() {
  6827. Text('艺术家:')
  6828. .fontSize(14)
  6829. .fontColor($r('app.color.text_color'))
  6830. .margin({ left: 22 })
  6831. TextInput({ text: this.artistStr||item.artist })
  6832. .height(40)
  6833. .maxLines(1)
  6834. .fontSize(14)
  6835. .layoutWeight(1)
  6836. .fontColor($r('app.color.text_color'))
  6837. .margin({ right: 20, left: 10 })
  6838. .onChange((val: string) => {
  6839. this.artistStr = val
  6840. })
  6841. }
  6842. .width('100%')
  6843. .margin({ top: 10, bottom: 10 })
  6844. .justifyContent(FlexAlign.Start)
  6845. Row() {
  6846. Text('专辑名:')
  6847. .fontSize(14)
  6848. .fontColor($r('app.color.text_color'))
  6849. .margin({ left: 22 })
  6850. TextInput({ text: this.ablumStr||item.album })
  6851. .height(40)
  6852. .maxLines(1)
  6853. .fontSize(14)
  6854. .layoutWeight(1)
  6855. .fontColor($r('app.color.text_color'))
  6856. .margin({ right: 20, left: 10 })
  6857. .onChange((val: string) => {
  6858. this.ablumStr = val
  6859. })
  6860. }
  6861. .width('100%')
  6862. .margin({ top: 10, bottom: 10 })
  6863. .justifyContent(FlexAlign.Start)
  6864. Row() {
  6865. Column(){
  6866. Column(){
  6867. Text('歌词:')
  6868. .fontSize(14)
  6869. .fontColor($r('app.color.text_color'))
  6870. .margin({ top:9,left: 22 })
  6871. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6872. SymbolGlyph($r('sys.symbol.trash_fill'))
  6873. .fontSize(25)
  6874. .alignSelf(ItemAlign.Center)
  6875. .margin({ left: 22,top:25})
  6876. }
  6877. .backgroundColor(Color.Transparent)
  6878. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  6879. Visibility.None:Visibility.Visible)
  6880. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6881. .onClick(()=>{
  6882. this.lyricConStr = ''
  6883. this.lyricContent = ''
  6884. this.tempLyricContent = ''
  6885. })
  6886. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6887. SymbolGlyph($r('sys.symbol.plus'))
  6888. .fontSize(25)
  6889. .alignSelf(ItemAlign.Center)
  6890. .margin({ left: 22,top:25})
  6891. }
  6892. .backgroundColor(Color.Transparent)
  6893. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6894. .onClick( ()=>{
  6895. this.callFilePickerSelectFileForLyric()
  6896. })
  6897. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6898. SymbolGlyph($r('sys.symbol.traditional_square'))
  6899. .fontSize(25)
  6900. .alignSelf(ItemAlign.Center)
  6901. .margin({ left: 22,top:25})
  6902. }
  6903. .backgroundColor(Color.Transparent)
  6904. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  6905. Visibility.None:Visibility.Visible)
  6906. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6907. .onClick( ()=>{
  6908. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  6909. this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
  6910. })
  6911. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6912. Image($r('app.media.jianti'))
  6913. .height(25)
  6914. .fillColor($r('app.color.text_color'))
  6915. .alignSelf(ItemAlign.Center)
  6916. .margin({ left: 22,top:25})
  6917. }
  6918. .backgroundColor(Color.Transparent)
  6919. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  6920. Visibility.None:Visibility.Visible)
  6921. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6922. .onClick( ()=>{
  6923. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  6924. this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
  6925. })
  6926. }
  6927. .layoutWeight(1)
  6928. }
  6929. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  6930. this.tempLyricContent })
  6931. .type(TextAreaType.NORMAL)
  6932. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
  6933. .fontSize(14)
  6934. .layoutWeight(1)
  6935. .fontColor($r('app.color.text_color'))
  6936. .margin({ right: 20, left: 10 })
  6937. .onChange((val: string) => {
  6938. this.lyricConStr = val
  6939. })
  6940. }
  6941. .width('100%')
  6942. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
  6943. .margin({ top: 10, bottom: 10 })
  6944. .justifyContent(FlexAlign.Start)
  6945. Row() {
  6946. Text('年份:')
  6947. .fontSize(14)
  6948. .fontColor($r('app.color.text_color'))
  6949. .margin({ left: 22 })
  6950. TextInput({ text: item.year })
  6951. .height(40)
  6952. .maxLines(1)
  6953. .fontSize(14)
  6954. .type(InputType.Number)
  6955. .layoutWeight(1)
  6956. .fontColor($r('app.color.text_color'))
  6957. .margin({ right: 20, left: 10 })
  6958. .onChange((val: string) => {
  6959. this.yearStr = val
  6960. })
  6961. }
  6962. .width('100%')
  6963. .margin({ top: 10, bottom: 10 })
  6964. .justifyContent(FlexAlign.Start)
  6965. Row() {
  6966. Text('音轨号:')
  6967. .fontSize(14)
  6968. .fontColor($r('app.color.text_color'))
  6969. .margin({ left: 22 })
  6970. TextInput({ text:item.track=='未知'?'': item.track })
  6971. .height(40)
  6972. .maxLines(1)
  6973. .fontSize(14)
  6974. .type(InputType.Number)
  6975. .layoutWeight(1)
  6976. .fontColor($r('app.color.text_color'))
  6977. .margin({ right: 20, left: 10 })
  6978. .onChange((val: string) => {
  6979. this.trackStr = val
  6980. })
  6981. }
  6982. .width('100%')
  6983. .margin({ top: 10, bottom: 10 })
  6984. .justifyContent(FlexAlign.Start)
  6985. Row() {
  6986. Text('碟号:')
  6987. .fontSize(14)
  6988. .fontColor($r('app.color.text_color'))
  6989. .margin({ left: 22 })
  6990. TextInput({ text:item.disc })
  6991. .height(40)
  6992. .maxLines(1)
  6993. .fontSize(14)
  6994. .type(InputType.Number)
  6995. .layoutWeight(1)
  6996. .fontColor($r('app.color.text_color'))
  6997. .margin({ right: 20, left: 10 })
  6998. .onChange((val: string) => {
  6999. this.discStr = val
  7000. })
  7001. }
  7002. .width('100%')
  7003. .margin({ top: 10, bottom: 10 })
  7004. .justifyContent(FlexAlign.Start)
  7005. Row() {
  7006. Text('风格:')
  7007. .fontSize(14)
  7008. .fontColor($r('app.color.text_color'))
  7009. .margin({ left: 22 })
  7010. TextInput({ text: item.genre })
  7011. .height(40)
  7012. .maxLines(1)
  7013. .fontSize(14)
  7014. .layoutWeight(1)
  7015. .fontColor($r('app.color.text_color'))
  7016. .margin({ right: 20, left: 10 })
  7017. .onChange((val: string) => {
  7018. this.genreStr = val
  7019. })
  7020. }
  7021. .width('100%')
  7022. .margin({ top: 10, bottom: 10 })
  7023. .justifyContent(FlexAlign.Start)
  7024. Row() {
  7025. Text('专辑艺术家:')
  7026. .fontSize(14)
  7027. .fontColor($r('app.color.text_color'))
  7028. .margin({ left: 22 })
  7029. TextInput({ text: item.ALBUMARTIST })
  7030. .height(40)
  7031. .maxLines(1)
  7032. .fontSize(14)
  7033. .layoutWeight(1)
  7034. .fontColor($r('app.color.text_color'))
  7035. .margin({ right: 20, left: 10 })
  7036. .onChange((val: string) => {
  7037. this.albumArtistStr = val
  7038. })
  7039. }
  7040. .width('100%')
  7041. .margin({ top: 10, bottom: 10 })
  7042. .justifyContent(FlexAlign.Start)
  7043. Row() {
  7044. Text('作曲:')
  7045. .fontSize(14)
  7046. .fontColor($r('app.color.text_color'))
  7047. .margin({ left: 22 })
  7048. TextInput({ text: item.COMPOSER })
  7049. .height(40)
  7050. .maxLines(1)
  7051. .fontSize(14)
  7052. .layoutWeight(1)
  7053. .fontColor($r('app.color.text_color'))
  7054. .margin({ right: 20, left: 10 })
  7055. .onChange((val: string) => {
  7056. this.composerStr = val
  7057. })
  7058. }
  7059. .width('100%')
  7060. .margin({ top: 10, bottom: 10 })
  7061. .justifyContent(FlexAlign.Start)
  7062. Row() {
  7063. Text('作词:')
  7064. .fontSize(14)
  7065. .fontColor($r('app.color.text_color'))
  7066. .margin({ left: 22 })
  7067. TextInput({ text: item.LYRICIST })
  7068. .height(40)
  7069. .maxLines(1)
  7070. .fontSize(14)
  7071. .layoutWeight(1)
  7072. .fontColor($r('app.color.text_color'))
  7073. .margin({ right: 20, left: 10 })
  7074. .onChange((val: string) => {
  7075. this.lyricistStr = val
  7076. })
  7077. }
  7078. .width('100%')
  7079. .margin({ top: 10, bottom: 10 })
  7080. .justifyContent(FlexAlign.Start)
  7081. Row() {
  7082. Text('注释:')
  7083. .fontSize(14)
  7084. .fontColor($r('app.color.text_color'))
  7085. .margin({ left: 22 })
  7086. TextInput({ text: item.COMMENT })
  7087. .height(40)
  7088. .maxLines(1)
  7089. .fontSize(14)
  7090. .layoutWeight(1)
  7091. .fontColor($r('app.color.text_color'))
  7092. .margin({ right: 20, left: 10 })
  7093. .onChange((val: string) => {
  7094. this.commentStr = val
  7095. })
  7096. }
  7097. .width('100%')
  7098. .margin({ top: 10, bottom: 10 })
  7099. .justifyContent(FlexAlign.Start)
  7100. Row() {
  7101. Button('保存')
  7102. .fontColor(Color.White)
  7103. .layoutWeight(1)
  7104. .height(50)
  7105. .width(100)
  7106. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7107. .backgroundColor(this.themeColor)
  7108. .stateEffect(true)
  7109. .margin({ right: 20, bottom: 20 })
  7110. .onClick(async () => {
  7111. this.doEdit(item)
  7112. })
  7113. Button('取消')
  7114. .fontColor(Color.White)
  7115. .layoutWeight(1)
  7116. .height(50)
  7117. .width(100)
  7118. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7119. .backgroundColor(this.themeColor)
  7120. .stateEffect(true)
  7121. .margin({ left: 20, bottom: 20 })
  7122. .onClick(async () => {
  7123. if(this.isGridMusic){
  7124. this.longItemFilePath =''
  7125. }else{
  7126. this.isShowEdit = false
  7127. }
  7128. this.setEditStrEmpty()
  7129. if(this.isShowPlay){
  7130. this.isShowEdit = false
  7131. }
  7132. })
  7133. }
  7134. .margin({
  7135. left: 38,
  7136. right: 38,
  7137. top: 10,
  7138. bottom: 10
  7139. })
  7140. .width(250)
  7141. .height(60)
  7142. }
  7143. }
  7144. .margin({ bottom: 20 })
  7145. }
  7146. setEditStrEmpty(){
  7147. this.imagePathStr = ''
  7148. this.lyricConStr = ''
  7149. this.artistStr = ''
  7150. this.titleStr = ''
  7151. this.ablumStr = ''
  7152. this.genreStr = ''
  7153. this.yearStr = ''
  7154. this.trackStr = ''
  7155. this.albumArtistStr = ''
  7156. this.composerStr = ''
  7157. this.lyricistStr = ''
  7158. this.commentStr = ''
  7159. this.discStr = ''
  7160. }
  7161. initEditFields(item?: VideoItem) {
  7162. if (!item) {
  7163. this.setEditStrEmpty()
  7164. return
  7165. }
  7166. this.imagePathStr = ''
  7167. this.titleStr = item.name ?? ''
  7168. this.artistStr = item.artist ?? ''
  7169. this.ablumStr = item.album ?? ''
  7170. this.genreStr = item.genre ?? ''
  7171. this.yearStr = item.year ?? ''
  7172. this.trackStr = item.track ?? ''
  7173. this.albumArtistStr = item.ALBUMARTIST ?? ''
  7174. this.composerStr = item.COMPOSER ?? ''
  7175. this.lyricistStr = item.LYRICIST ?? ''
  7176. this.commentStr = item.COMMENT ?? ''
  7177. this.discStr = item.disc ?? ''
  7178. this.lyricConStr = item.lyricContent ?? ''
  7179. }
  7180. private syncEditedFields(target?: VideoItem) {
  7181. if (!target) {
  7182. return
  7183. }
  7184. target.name = this.titleStr
  7185. target.artist = this.artistStr
  7186. target.album = this.ablumStr
  7187. target.lyricContent = this.lyricConStr
  7188. target.year = this.yearStr
  7189. target.genre = this.genreStr
  7190. target.track = this.trackStr
  7191. target.ALBUMARTIST = this.albumArtistStr
  7192. target.COMPOSER = this.composerStr
  7193. target.LYRICIST = this.lyricistStr
  7194. target.COMMENT = this.commentStr
  7195. target.disc = this.discStr
  7196. }
  7197. private replaceItemInList(list: Array<VideoItem> | undefined, filePath: string,
  7198. apply?: (next: Array<VideoItem>) => void) {
  7199. if (!list || ArrayUtil.isEmpty(list)) {
  7200. return
  7201. }
  7202. const index = list.findIndex((video: VideoItem) => video.filePath === filePath)
  7203. if (index < 0) {
  7204. return
  7205. }
  7206. const nextList = [...list]
  7207. this.syncEditedFields(nextList[index])
  7208. apply?.(nextList)
  7209. }
  7210. private syncListsAfterEdit(filePath: string) {
  7211. this.replaceItemInList(this.videoLocalList, filePath, (next: Array<VideoItem>) => {
  7212. this.videoLocalList = next
  7213. this.dataSource.pushArrayData(next)
  7214. })
  7215. this.replaceItemInList(this.songList, filePath, (next: Array<VideoItem>) => {
  7216. this.songList = next
  7217. this.sonDataSource.pushArrayData(next)
  7218. })
  7219. this.replaceItemInList(this.favList, filePath, (next: Array<VideoItem>) => {
  7220. this.favList = next
  7221. })
  7222. this.replaceItemInList(this.historyList, filePath, (next: Array<VideoItem>) => {
  7223. this.historyList = next
  7224. })
  7225. this.replaceItemInList(this.currentSongList, filePath, (next: Array<VideoItem>) => {
  7226. this.currentSongList = next
  7227. })
  7228. this.replaceItemInList(this.mediaKuList, filePath, (next: Array<VideoItem>) => {
  7229. this.mediaKuList = next
  7230. })
  7231. this.replaceItemInList(this.filteredList, filePath, (next: Array<VideoItem>) => {
  7232. this.filteredList = next
  7233. })
  7234. this.replaceItemInList(this.artistList, filePath, (next: Array<VideoItem>) => {
  7235. this.artistList = next
  7236. })
  7237. this.replaceItemInList(this.albumList, filePath, (next: Array<VideoItem>) => {
  7238. this.albumList = next
  7239. })
  7240. this.listRefreshKey++
  7241. }
  7242. private refreshLazyListViews(mainListUpdated: boolean, playlistUpdated: boolean): void {
  7243. if (!mainListUpdated && !playlistUpdated) {
  7244. return;
  7245. }
  7246. this.listRefreshKey++;
  7247. if (mainListUpdated) {
  7248. this.dataSource.notifyDataReload();
  7249. }
  7250. if (playlistUpdated) {
  7251. this.sonDataSource.notifyDataReload();
  7252. }
  7253. }
  7254. @Builder
  7255. detailSheet(item:VideoItem) {
  7256. Scroll() {
  7257. Column() {
  7258. this.songDetail(item)
  7259. }
  7260. }
  7261. .width('100%')
  7262. .height('100%')
  7263. }
  7264. @Builder
  7265. songDetail(currentItem:VideoItem) {
  7266. Column() {
  7267. if (currentItem) {
  7268. Row() {
  7269. Stack() {
  7270. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.alt') :
  7271. currentItem.pixelMapPath)
  7272. .fillColor(this.themeColor)
  7273. .height(80)
  7274. .width(80)
  7275. .borderRadius(10)
  7276. .opacity(this.opacityItem)// 绑定透明度
  7277. .margin({ left: 22 })
  7278. }
  7279. Column() {
  7280. Column() {
  7281. Text(currentItem.name)
  7282. .fontSize(16)
  7283. .maxLines(1)
  7284. .animation({
  7285. duration: 555,
  7286. curve: 'Linear',
  7287. })
  7288. .fontColor($r('app.color.text_color'))
  7289. .margin({ left: 15 })
  7290. }
  7291. .height('100%')
  7292. .width('100%')
  7293. .justifyContent(FlexAlign.Center)
  7294. .alignItems(HorizontalAlign.Start)
  7295. }
  7296. .height('100%')
  7297. }
  7298. .width('100%')
  7299. .height(90)
  7300. .justifyContent(FlexAlign.SpaceBetween)
  7301. Row() {
  7302. Text('艺术家:')
  7303. .fontSize(14)
  7304. .fontColor($r('app.color.text_color'))
  7305. .margin({ left: 22 })
  7306. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  7307. .fontSize(14)
  7308. .fontColor($r('app.color.text_color'))
  7309. .margin({ left: 10 })
  7310. .layoutWeight(1)
  7311. }
  7312. .width('100%')
  7313. .margin({ top: 10, bottom: 10 })
  7314. .justifyContent(FlexAlign.Start)
  7315. Row() {
  7316. Text('专辑名:')
  7317. .fontSize(14)
  7318. .fontColor($r('app.color.text_color'))
  7319. .margin({ left: 22 })
  7320. Text(currentItem?.album ?currentItem.album : '未知专辑')
  7321. .fontSize(14)
  7322. .margin({ left: 10 })
  7323. .fontColor($r('app.color.text_color'))
  7324. .layoutWeight(1)
  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. Text(StrUtil.isEmpty(currentItem.duration)?
  7335. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  7336. .fontSize(14)
  7337. .margin({ left: 10 })
  7338. .fontColor($r('app.color.text_color'))
  7339. .layoutWeight(1)
  7340. }
  7341. .width('100%')
  7342. .margin({ top: 10, bottom: 10 })
  7343. .justifyContent(FlexAlign.Start)
  7344. Row() {
  7345. Text('采样率:')
  7346. .fontSize(14)
  7347. .fontColor($r('app.color.text_color'))
  7348. .margin({ left: 22 })
  7349. Text(Utility.convertToKHz(currentItem.sampleRate))
  7350. .fontSize(14)
  7351. .margin({ left: 10 })
  7352. .fontColor($r('app.color.text_color'))
  7353. .layoutWeight(1)
  7354. }
  7355. .width('100%')
  7356. .margin({ top: 10, bottom: 10 })
  7357. .justifyContent(FlexAlign.Start)
  7358. Row() {
  7359. Text('比特率:')
  7360. .fontSize(14)
  7361. .fontColor($r('app.color.text_color'))
  7362. .margin({ left: 22 })
  7363. Text(currentItem.bit_rate)
  7364. .fontSize(14)
  7365. .margin({ left: 10 })
  7366. .fontColor($r('app.color.text_color'))
  7367. .layoutWeight(1)
  7368. }
  7369. .width('100%')
  7370. .margin({ top: 10, bottom: 10 })
  7371. .justifyContent(FlexAlign.Start)
  7372. Row() {
  7373. Text('位深:')
  7374. .fontSize(14)
  7375. .fontColor($r('app.color.text_color'))
  7376. .margin({ left: 22 })
  7377. Text(`${currentItem.bits_per_raw_sample} bits`)
  7378. .fontSize(14)
  7379. .margin({ left: 10 })
  7380. .fontColor($r('app.color.text_color'))
  7381. .layoutWeight(1)
  7382. }
  7383. .width('100%')
  7384. .margin({ top: 10, bottom: 10 })
  7385. .justifyContent(FlexAlign.Start)
  7386. Row() {
  7387. Text('声道:')
  7388. .fontSize(14)
  7389. .fontColor($r('app.color.text_color'))
  7390. .margin({ left: 22 })
  7391. Text(`${currentItem.channels}`)
  7392. .fontSize(14)
  7393. .margin({ left: 10 })
  7394. .fontColor($r('app.color.text_color'))
  7395. .layoutWeight(1)
  7396. }
  7397. .width('100%')
  7398. .margin({ top: 10, bottom: 10 })
  7399. .justifyContent(FlexAlign.Start)
  7400. Row() {
  7401. Text('声道布局:')
  7402. .fontSize(14)
  7403. .fontColor($r('app.color.text_color'))
  7404. .margin({ left: 22 })
  7405. Text(`${currentItem.channel_layout}`)
  7406. .fontSize(14)
  7407. .margin({ left: 10 })
  7408. .fontColor($r('app.color.text_color'))
  7409. .layoutWeight(1)
  7410. }
  7411. .width('100%')
  7412. .margin({ top: 10, bottom: 10 })
  7413. .justifyContent(FlexAlign.Start)
  7414. Row() {
  7415. Text('起始播放点:')
  7416. .fontSize(14)
  7417. .fontColor($r('app.color.text_color'))
  7418. .margin({ left: 22 })
  7419. Text(`${currentItem.start_time}`)
  7420. .fontSize(14)
  7421. .margin({ left: 10 })
  7422. .fontColor($r('app.color.text_color'))
  7423. .layoutWeight(1)
  7424. }
  7425. .width('100%')
  7426. .margin({ top: 10, bottom: 10 })
  7427. .justifyContent(FlexAlign.Start)
  7428. Row() {
  7429. Text('风格:')
  7430. .fontSize(14)
  7431. .fontColor($r('app.color.text_color'))
  7432. .margin({ left: 22 })
  7433. Text(currentItem.genre)
  7434. .fontSize(14)
  7435. .margin({ left: 10 })
  7436. .fontColor($r('app.color.text_color'))
  7437. .layoutWeight(1)
  7438. }
  7439. .width('100%')
  7440. .margin({ top: 10, bottom: 10 })
  7441. .justifyContent(FlexAlign.Start)
  7442. Row() {
  7443. Text('发行时间:')
  7444. .fontSize(14)
  7445. .fontColor($r('app.color.text_color'))
  7446. .margin({ left: 22 })
  7447. Text(currentItem.year)
  7448. .fontSize(14)
  7449. .margin({ left: 10 })
  7450. .fontColor($r('app.color.text_color'))
  7451. .layoutWeight(1)
  7452. }
  7453. .width('100%')
  7454. .margin({ top: 10, bottom: 10 })
  7455. .justifyContent(FlexAlign.Start)
  7456. Row() {
  7457. Text('质量评分:')
  7458. .fontSize(14)
  7459. .fontColor($r('app.color.text_color'))
  7460. .margin({ left: 22 })
  7461. Text(currentItem.probe_score+"")
  7462. .fontSize(14)
  7463. .margin({ left: 10 })
  7464. .fontColor($r('app.color.text_color'))
  7465. .layoutWeight(1)
  7466. }
  7467. .width('100%')
  7468. .margin({ top: 10, bottom: 10 })
  7469. .justifyContent(FlexAlign.Start)
  7470. Row() {
  7471. Text('音轨号:')
  7472. .fontSize(14)
  7473. .fontColor($r('app.color.text_color'))
  7474. .margin({ left: 22 })
  7475. Text(currentItem.track)
  7476. .fontSize(14)
  7477. .margin({ left: 10 })
  7478. .fontColor($r('app.color.text_color'))
  7479. .layoutWeight(1)
  7480. }
  7481. .width('100%')
  7482. .margin({ top: 10, bottom: 10 })
  7483. .justifyContent(FlexAlign.Start)
  7484. Row() {
  7485. Text('碟号:')
  7486. .fontSize(14)
  7487. .fontColor($r('app.color.text_color'))
  7488. .margin({ left: 22 })
  7489. Text(currentItem.disc)
  7490. .fontSize(14)
  7491. .margin({ left: 10 })
  7492. .fontColor($r('app.color.text_color'))
  7493. .layoutWeight(1)
  7494. }
  7495. .width('100%')
  7496. .margin({ top: 10, bottom: 10 })
  7497. .justifyContent(FlexAlign.Start)
  7498. Row() {
  7499. Text('专辑艺术家:')
  7500. .fontSize(14)
  7501. .fontColor($r('app.color.text_color'))
  7502. .margin({ left: 22 })
  7503. Text(currentItem.ALBUMARTIST)
  7504. .fontSize(14)
  7505. .margin({ left: 10 })
  7506. .fontColor($r('app.color.text_color'))
  7507. .layoutWeight(1)
  7508. }
  7509. .width('100%')
  7510. .margin({ top: 10, bottom: 10 })
  7511. .justifyContent(FlexAlign.Start)
  7512. Row() {
  7513. Text('作曲家:')
  7514. .fontSize(14)
  7515. .fontColor($r('app.color.text_color'))
  7516. .margin({ left: 22 })
  7517. Text(currentItem.COMPOSER)
  7518. .fontSize(14)
  7519. .margin({ left: 10 })
  7520. .fontColor($r('app.color.text_color'))
  7521. .layoutWeight(1)
  7522. }
  7523. .width('100%')
  7524. .margin({ top: 10, bottom: 10 })
  7525. .justifyContent(FlexAlign.Start)
  7526. Row() {
  7527. Text('作词家:')
  7528. .fontSize(14)
  7529. .fontColor($r('app.color.text_color'))
  7530. .margin({ left: 22 })
  7531. Text(currentItem.LYRICIST)
  7532. .fontSize(14)
  7533. .margin({ left: 10 })
  7534. .fontColor($r('app.color.text_color'))
  7535. .layoutWeight(1)
  7536. }
  7537. .width('100%')
  7538. .margin({ top: 10, bottom: 10 })
  7539. .justifyContent(FlexAlign.Start)
  7540. Row() {
  7541. Text('注释:')
  7542. .fontSize(14)
  7543. .fontColor($r('app.color.text_color'))
  7544. .margin({ left: 22 })
  7545. Text(currentItem.COMMENT)
  7546. .fontSize(14)
  7547. .margin({ left: 10 })
  7548. .fontColor($r('app.color.text_color'))
  7549. .layoutWeight(1)
  7550. }
  7551. .width('100%')
  7552. .margin({ top: 10, bottom: 10 })
  7553. .justifyContent(FlexAlign.Start)
  7554. Row() {
  7555. Text('格式:')
  7556. .fontSize(14)
  7557. .fontColor($r('app.color.text_color'))
  7558. .margin({ left: 22 })
  7559. Text(Utility.formatMimeType(currentItem.mimeType))
  7560. .fontSize(14)
  7561. .margin({ left: 10 })
  7562. .fontColor($r('app.color.text_color'))
  7563. .layoutWeight(1)
  7564. }
  7565. .width('100%')
  7566. .margin({ top: 10, bottom: 10 })
  7567. .justifyContent(FlexAlign.Start)
  7568. Row() {
  7569. Text('播放次数:')
  7570. .fontSize(14)
  7571. .fontColor($r('app.color.text_color'))
  7572. .margin({ left: 22 })
  7573. Text(currentItem.playCount?.toString())
  7574. .fontSize(14)
  7575. .margin({ left: 10 })
  7576. .fontColor($r('app.color.text_color'))
  7577. .layoutWeight(1)
  7578. }
  7579. .width('100%')
  7580. .margin({ top: 10, bottom: 10 })
  7581. .justifyContent(FlexAlign.Start)
  7582. Row() {
  7583. Text('流数量:')
  7584. .fontSize(14)
  7585. .fontColor($r('app.color.text_color'))
  7586. .margin({ left: 22 })
  7587. Text(currentItem.nb_streams?.toString())
  7588. .fontSize(14)
  7589. .margin({ left: 10 })
  7590. .fontColor($r('app.color.text_color'))
  7591. .layoutWeight(1)
  7592. }
  7593. .width('100%')
  7594. .margin({ top: 10, bottom: 10 })
  7595. .justifyContent(FlexAlign.Start)
  7596. Row() {
  7597. Text('文件大小:')
  7598. .fontSize(14)
  7599. .fontColor($r('app.color.text_color'))
  7600. .margin({ left: 22 })
  7601. Text(currentItem.size)
  7602. .fontSize(14)
  7603. .margin({ left: 10 })
  7604. .fontColor($r('app.color.text_color'))
  7605. .layoutWeight(1)
  7606. }
  7607. .width('100%')
  7608. .margin({ top: 10, bottom: 10 })
  7609. .justifyContent(FlexAlign.Start)
  7610. Row() {
  7611. Text('文件名:')
  7612. .fontSize(14)
  7613. .fontColor($r('app.color.text_color'))
  7614. .margin({ left: 22 })
  7615. Text(currentItem.fileName)
  7616. .fontSize(14)
  7617. .margin({ left: 10 })
  7618. .fontColor($r('app.color.text_color'))
  7619. .layoutWeight(1)
  7620. }
  7621. .width('100%')
  7622. .margin({ top: 10, bottom: 10 })
  7623. .justifyContent(FlexAlign.Start)
  7624. Row() {
  7625. Text('修改时间:')
  7626. .fontSize(14)
  7627. .fontColor($r('app.color.text_color'))
  7628. .margin({ left: 22 })
  7629. Text(currentItem.cTime)
  7630. .fontSize(14)
  7631. .margin({ left: 10 })
  7632. .fontColor($r('app.color.text_color'))
  7633. .layoutWeight(1)
  7634. }
  7635. .width('100%')
  7636. .margin({ top: 10, bottom: 10 })
  7637. .justifyContent(FlexAlign.Start)
  7638. Row() {
  7639. Text('存放目录:')
  7640. .fontSize(14)
  7641. .fontColor($r('app.color.text_color'))
  7642. .margin({ left: 22 })
  7643. Text(currentItem.filePath)
  7644. .fontSize(12)
  7645. .margin({ left: 10 })
  7646. .fontColor($r('app.color.text_color'))
  7647. .layoutWeight(1)
  7648. }
  7649. .margin({ top: 10, bottom: 10 })
  7650. .width('100%')
  7651. .justifyContent(FlexAlign.Start)
  7652. Row() {
  7653. Text('内嵌歌词:')
  7654. .fontSize(14)
  7655. .fontColor($r('app.color.text_color'))
  7656. .margin({ left: 22 })
  7657. Text(currentItem.lyricContent)
  7658. .fontSize(12)
  7659. .copyOption(CopyOptions.InApp)
  7660. .margin({ left: 10 })
  7661. .fontColor($r('app.color.text_color'))
  7662. .layoutWeight(1)
  7663. }
  7664. .margin({ top: 10, bottom: 10 })
  7665. .width('100%')
  7666. .justifyContent(FlexAlign.Start)
  7667. }
  7668. }
  7669. .margin({ bottom: 20 })
  7670. }
  7671. //定时关闭布局
  7672. @Builder
  7673. TimeCloseSheet() {
  7674. Scroll() {
  7675. Column() {
  7676. this.TimeClose()
  7677. }
  7678. }
  7679. .width('100%')
  7680. .height('100%')
  7681. }
  7682. //倒计时关闭音乐,退出App功能实现。
  7683. @State selectedMinutes: number = 0 // 0表示未开启
  7684. @State remainingSeconds: number = 0
  7685. // 预设时间选项
  7686. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  7687. private formatTime(seconds: number): string {
  7688. const mins = Math.floor(seconds / 60)
  7689. const secs = seconds % 60
  7690. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  7691. }
  7692. // 开始倒计时
  7693. private handleTimeSelect(minutes: number) {
  7694. if (minutes === this.selectedMinutes) {
  7695. this.stopCountdown();
  7696. this.selectedMinutes = 0;
  7697. return;
  7698. }
  7699. this.selectedMinutes = minutes;
  7700. this.remainingSeconds = minutes * 60;
  7701. this.startCountdown(); // 新增调用
  7702. }
  7703. @Builder
  7704. TimeClose() {
  7705. Column() {
  7706. // 倒计时显示区域
  7707. Text(this.selectedMinutes > 0 ?
  7708. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  7709. "定时关闭未开启")
  7710. .fontSize(17)
  7711. .fontColor($r('app.color.text_color'))
  7712. .margin({ top: 2, bottom: 8 });
  7713. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  7714. ForEach(this.presetTimes, (minutes: number, index: number) => {
  7715. // 单行时间选项容器
  7716. Row() {
  7717. // 文字描述区域
  7718. Text(this.getDisplayText(minutes))
  7719. .fontSize(15)
  7720. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  7721. $r('app.color.text_color'))// 选中态颜色变化
  7722. .textAlign(TextAlign.Start)
  7723. .layoutWeight(1); // 占据剩余空间
  7724. // 复选框样式的选择器
  7725. Row() {
  7726. if (minutes === this.selectedMinutes) {
  7727. // 选中状态 - 带勾号的圆形复选框
  7728. Row() {
  7729. // 使用系统内置的勾号图标
  7730. Image($r('sys.media.ohos_ic_public_ok'))
  7731. .width(14)
  7732. .height(14)
  7733. .fillColor(Color.White)
  7734. }
  7735. .width(24)
  7736. .height(24)
  7737. .borderRadius(12)
  7738. .backgroundColor(this.themeColor)
  7739. .justifyContent(FlexAlign.Center)
  7740. .alignItems(VerticalAlign.Center)
  7741. } else {
  7742. // 未选中状态的圆形边框
  7743. Row()
  7744. .width(24)
  7745. .height(24)
  7746. .borderRadius(12)
  7747. .border({
  7748. width: 2,
  7749. color: $r('app.color.text_color'),
  7750. style: BorderStyle.Solid
  7751. })
  7752. .backgroundColor(Color.Transparent)
  7753. }
  7754. }
  7755. .width(24)
  7756. .height(24)
  7757. .margin({ left: 20 })
  7758. .justifyContent(FlexAlign.Center)
  7759. .alignItems(VerticalAlign.Center)
  7760. }
  7761. .width('100%')
  7762. .padding({
  7763. top: 18,
  7764. bottom: 18,
  7765. left: 18,
  7766. right: 18
  7767. })
  7768. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  7769. $r('app.color.bottom_control_background')) // 选中背景高亮
  7770. .borderRadius(12)
  7771. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  7772. .margin({ bottom: 18 })
  7773. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  7774. });
  7775. }
  7776. .width('100%')
  7777. .padding(16)
  7778. }
  7779. }
  7780. // 获取显示文本
  7781. private getDisplayText(minutes: number): string {
  7782. if (minutes === -1) {
  7783. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  7784. }
  7785. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  7786. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  7787. }
  7788. // 处理选择事件
  7789. private handleSelect(minutes: number): void {
  7790. if (minutes === -1) { // 自定义
  7791. // 弹出自定义时间对话框
  7792. DialogHelper.showTextInputDialog({
  7793. title: '自定义时间',
  7794. maskColor: Color.Transparent,
  7795. inputType: InputType.Number,
  7796. text: '',
  7797. onChange: (text) => {
  7798. console.error("onChange: " + text);
  7799. },
  7800. onAction: (action, dialogId, content) => {
  7801. if (action == DialogAction.TWO) {
  7802. const customMinutes = Number(content);
  7803. if (customMinutes > 0) {
  7804. this.handleTimeSelect(customMinutes); // 设置自定义时间
  7805. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  7806. }
  7807. }
  7808. }
  7809. });
  7810. } else {
  7811. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  7812. }
  7813. }
  7814. // 添加定时器引用
  7815. private timerId: number = -1;
  7816. // 启动/重置倒计时
  7817. private startCountdown() {
  7818. // 清除旧定时器
  7819. if (this.timerId !== -1) {
  7820. clearInterval(this.timerId);
  7821. }
  7822. // 创建新定时器
  7823. if (this.selectedMinutes > 0) {
  7824. this.timerId = setInterval(() => {
  7825. if (this.remainingSeconds === 15) {
  7826. this.showConfirmationDialog();
  7827. }
  7828. if (this.remainingSeconds > 0) {
  7829. this.remainingSeconds -= 1;
  7830. } else {
  7831. this.stopCountdown();
  7832. this.handleTimeout();
  7833. }
  7834. }, 1000);
  7835. }
  7836. }
  7837. // 15倒计时后再次提示显示确认是否关闭App对话框
  7838. private showConfirmationDialog() {
  7839. DialogHelper.showAlertDialog({
  7840. backgroundColor: $r('app.color.btn_green'),
  7841. title: '确认关闭',
  7842. maskColor: Color.Transparent,
  7843. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  7844. borderStyle: BorderStyle.Dashed,
  7845. primaryButton: '暂不关闭',
  7846. secondaryButton: '确定',
  7847. onAction: (action) => {
  7848. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  7849. this.stopCountdown();
  7850. this.selectedMinutes = 0
  7851. } else if (action == DialogAction.TWO) {
  7852. }
  7853. }
  7854. })
  7855. }
  7856. // 停止倒计时
  7857. private stopCountdown() {
  7858. if (this.timerId !== -1) {
  7859. clearInterval(this.timerId);
  7860. this.timerId = -1;
  7861. }
  7862. }
  7863. // 超时处理
  7864. private handleTimeout() {
  7865. // 执行播放器关闭逻辑
  7866. this.selectedMinutes = 0;
  7867. ToastUtil.showToast(" 定时关闭已完成");
  7868. this.stop(); // 假设存在的播放器实例
  7869. //退出APP
  7870. const mContext = getContext(this) as common.UIAbilityContext
  7871. mContext.terminateSelf();
  7872. AvSessionController.getInstance(true).unregisterSessionListener()
  7873. }
  7874. //倒计时关闭音乐,退出App功能实现结束。
  7875. //播放列表的拖动List 重新排序
  7876. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  7877. //左滑操作 移动文件 重命名 删除等操作
  7878. @Builder
  7879. sonButton(item: VideoItem, index: number, filePath: string) {
  7880. Row() {
  7881. //加入下一首播放
  7882. Button() {
  7883. Image($r('app.media.next_to_play'))
  7884. .fillColor(Color.White)
  7885. .width(20)
  7886. }
  7887. .width(40)
  7888. .height(40)
  7889. .type(ButtonType.Circle)
  7890. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  7891. .backgroundColor(this.themeColor)
  7892. .margin(5)
  7893. .onClick(() => {
  7894. this.addToNextPlay(item);
  7895. })
  7896. Button() {
  7897. Image($r('app.media.close'))
  7898. .fillColor(Color.White)
  7899. .width(20)
  7900. }
  7901. .width(40)
  7902. .height(40)
  7903. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  7904. .type(ButtonType.Circle)
  7905. .backgroundColor(this.themeColor)
  7906. .margin(5)
  7907. .onClick(() => {
  7908. this.songList.splice(Number(index), 1)
  7909. this.sonDataSource.pushArrayData(this.songList)
  7910. })
  7911. Button() {
  7912. Image($r('app.media.share2'))
  7913. .fillColor(Color.White)
  7914. .width(20)
  7915. }
  7916. .width(40)
  7917. .height(40)
  7918. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  7919. .type(ButtonType.Circle)
  7920. .backgroundColor(this.themeColor)
  7921. .margin(5)
  7922. .onClick(() => {
  7923. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  7924. })
  7925. }
  7926. }
  7927. itemMoveSon(index: number, newIndex: number): void {
  7928. if (newIndex < 0 || newIndex >= this.songList.length) {
  7929. return;
  7930. }
  7931. let tmp = this.songList.splice(index, 1);
  7932. this.songList.splice(newIndex, 0, tmp[0]);
  7933. this.sonDataSource.pushArrayData(this.songList)
  7934. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  7935. if(this.modeType==4&&this.playlistTable){
  7936. updateAllSongsSortOrder(this.playlistTable, this.songList,this.currentSongListID)
  7937. }
  7938. }
  7939. @Builder
  7940. PlayList() {
  7941. List({ scroller: this.playListScroller }) {
  7942. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  7943. ListItem() {
  7944. this.MusicItemSon(item, index)
  7945. }
  7946. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  7947. .animation({
  7948. duration: 666,
  7949. curve: 'ease-in-out' // 可选动画曲线
  7950. })
  7951. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 600 }),
  7952. TransitionEffect.scale({ x: 0, y: 0 })))
  7953. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  7954. //拖动List关键代码开始
  7955. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  7956. .zIndex(this.dragItem === index ? 1 : 0)
  7957. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  7958. .gesture(
  7959. GestureGroup(GestureMode.Sequence,
  7960. LongPressGesture({ repeat: true })
  7961. .onAction((event?: GestureEvent) => {
  7962. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  7963. this.scaleItem = index
  7964. })
  7965. })
  7966. .onActionEnd(() => {
  7967. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  7968. this.scaleItem = -1
  7969. })
  7970. }),
  7971. PanGesture({ fingers: 1, direction: null, distance: 0 })
  7972. .onActionStart(() => {
  7973. this.dragItem = index // 记录当前拖动项索引
  7974. this.dragRefOffset = 0 // 重置偏移基准
  7975. })
  7976. .onActionUpdate((event: GestureEvent) => {
  7977. this.offsetY = event.offsetY - this.dragRefOffset;
  7978. this.neighborItem = -1;
  7979. let indexA = this.songList.indexOf(item);
  7980. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  7981. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  7982. let value: number = 0;
  7983. if (this.offsetY < 0) {
  7984. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  7985. this.neighborItem = indexA - 1;
  7986. this.neighborScale = 1 - value / 20;
  7987. } else if (this.offsetY > 0) {
  7988. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  7989. this.neighborItem = indexA + 1;
  7990. this.neighborScale = 1 - value / 20;
  7991. }
  7992. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  7993. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  7994. this.offsetY -= this.ITEM_INTV;
  7995. this.dragRefOffset += this.ITEM_INTV;
  7996. this.itemMoveSon(indexA, indexA + 1);
  7997. });
  7998. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  7999. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8000. this.offsetY += this.ITEM_INTV;
  8001. this.dragRefOffset -= this.ITEM_INTV;
  8002. this.itemMoveSon(indexA, indexA - 1);
  8003. });
  8004. }
  8005. })
  8006. .onActionEnd((event: GestureEvent) => {
  8007. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8008. this.dragItem = -1
  8009. this.neighborItem = -1
  8010. })
  8011. animateTo({
  8012. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  8013. }, () => {
  8014. this.scaleItem = -1
  8015. })
  8016. })
  8017. )
  8018. .onCancel(() => {
  8019. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8020. this.dragItem = -1
  8021. this.neighborItem = -1
  8022. })
  8023. animateTo({
  8024. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  8025. }, () => {
  8026. this.scaleItem = -1
  8027. })
  8028. })
  8029. ) //拖动List关键代码结束
  8030. .onClick(() => {
  8031. this.doPlay(item, index, true)
  8032. })
  8033. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  8034. }
  8035. .width('100%')
  8036. .height('100%')
  8037. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  8038. // .animation({ duration: 500, curve: Curve.Ease }))
  8039. .cachedCount(10)
  8040. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  8041. .gesture(PinchGesture({ fingers: 2 })
  8042. .onActionEnd((event: GestureEvent) => {
  8043. this.setSonListTwoFingers()
  8044. })
  8045. .onActionUpdate(e => {
  8046. this.scaleValue = this.pinchValue * e.scale
  8047. })
  8048. .onActionStart(e => {
  8049. }))
  8050. .padding({
  8051. bottom: 0
  8052. })
  8053. }
  8054. setSonListTwoFingers() {
  8055. this.pinchValue = this.scaleValue;
  8056. Logger.info('this.pinchValue = ' + this.pinchValue);
  8057. if (this.pinchValue >= 1) {
  8058. this.sonTwoFingerType++
  8059. Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
  8060. if (this.sonTwoFingerType > 3) {
  8061. this.sonTwoFingerType = 1
  8062. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  8063. }
  8064. } else {
  8065. this.sonTwoFingerType--
  8066. Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
  8067. if (this.sonTwoFingerType < 1) {
  8068. this.sonTwoFingerType = 1
  8069. }
  8070. }
  8071. PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
  8072. this.pinchValue = 1;
  8073. this.scaleValue = 1;
  8074. }
  8075. @State sonTwoFingerType:number = 3
  8076. @Builder
  8077. private MusicItemSon(item: VideoItem, index?: number) {
  8078. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  8079. Row() {
  8080. Stack() {
  8081. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  8082. .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  8083. .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  8084. .alt($r('app.media.alt'))
  8085. .fillColor(this.themeColor)
  8086. .borderRadius(this.isCoverRectangle?11:'100%')
  8087. .clip(true)
  8088. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  8089. .draggable(false)// 禁止长按手势拖动
  8090. .autoResize(true) // 重采样,可减少内存占用
  8091. .margin({ left: 20 })
  8092. }
  8093. .width('15%')
  8094. Column() {
  8095. Column() {
  8096. Text(this.isShowFileName?item.fileName :item.name)
  8097. .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
  8098. .fontColor(this.curIndex === index ? this.themeColor :
  8099. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  8100. .maxLines(1)
  8101. .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
  8102. Row() {
  8103. Column(){
  8104. Text(item.md5Str?.includes('Lossless')?
  8105. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  8106. .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
  8107. .padding({ top: 3,right:6,left:6,bottom:3 })
  8108. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  8109. $r('app.color.text_color'))
  8110. .fontWeight(500)
  8111. .borderRadius(12)
  8112. .visibility(StrUtil.isEmpty(item.md5Str) ? Visibility.None : Visibility.Visible)
  8113. .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
  8114. .backgroundColor('#FFC107')
  8115. }
  8116. .padding({ top: 8 })
  8117. Text(StrUtil.isEmpty(item.artist) ? item.duration :
  8118. item.artist + ' ' + item?.duration)
  8119. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  8120. .padding({ top: 8 })
  8121. .maxLines(1)
  8122. .fontColor(this.curIndex === index ? this.themeColor :
  8123. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  8124. .margin({ left: StrUtil.isEmpty(item.md5Str)? 12 :this.sonTwoFingerType == 3 ? 5 : 3 })
  8125. Blank()
  8126. Text(item.size)
  8127. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  8128. .padding({ top: 8 })
  8129. .maxLines(1)
  8130. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  8131. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  8132. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  8133. .margin({ left: 10 })
  8134. }
  8135. }
  8136. .height('100%')
  8137. .width('100%')
  8138. .justifyContent(FlexAlign.Center)
  8139. .alignItems(HorizontalAlign.Start)
  8140. }
  8141. .height('100%')
  8142. .width('65%')
  8143. Column() {
  8144. ImageAnimator()
  8145. .images(this.imagesF)// 动画数组
  8146. .duration(1000)// 持续
  8147. .state(this.animationState)// 动画状态
  8148. .fillMode(FillMode.Forwards)
  8149. .width(18)
  8150. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  8151. Visibility.None)
  8152. .height(18)
  8153. .iterations(-1) // 播放次数
  8154. }
  8155. .width('20%')
  8156. }
  8157. }
  8158. .backgroundColor(Color.Transparent)
  8159. .width('100%')
  8160. .reuseId('son_item')
  8161. .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
  8162. .shadow(this.scaleItem === index ? {
  8163. radius: 70,
  8164. color: '#15000000',
  8165. offsetX: 0,
  8166. offsetY: 0
  8167. } :
  8168. {
  8169. radius: 0,
  8170. color: '#15000000',
  8171. offsetX: 0,
  8172. offsetY: 0
  8173. })
  8174. .animation({ curve: Curve.Sharp, duration: 300 })
  8175. }
  8176. @Builder
  8177. MusicPlayBuilder() {
  8178. Column() {
  8179. this.IjkMusicPlayerView()
  8180. }
  8181. .transition(TransitionEffect.asymmetric(
  8182. TransitionEffect.opacity(1),
  8183. TransitionEffect.OPACITY
  8184. ))
  8185. .visualEffect(deviceInfo.sdkApiVersion>=20&&this.bgController?
  8186. new hdsEffect.HdsEffectBuilder()
  8187. .shaderEffect({
  8188. effectType: hdsEffect.EffectType.UV_BACKGROUND_FLOW_LIGHT,
  8189. animation: {
  8190. duration: 10000,
  8191. iterations: -1,
  8192. autoPlay: true,
  8193. onFinish: ()=> {
  8194. console.info('Succeeded in finishing');
  8195. }
  8196. },
  8197. controller: this.bgController,
  8198. })
  8199. .buildEffect():null)
  8200. .height('100%')
  8201. .width('100%')
  8202. .onDisAppear(() => {
  8203. this.translateY = 0;
  8204. })
  8205. .translate({ y: this.translateY })
  8206. .gesture(
  8207. PanGesture(this.panOption)
  8208. .onActionUpdate((event?: GestureEvent) => {
  8209. if (event) {
  8210. // 只允许向下滑动,向上滑动时限制为0
  8211. this.translateY = Math.max(0, event.offsetY);
  8212. this.getUIContext().animateTo({
  8213. duration: 500,
  8214. curve: Curve.Sharp
  8215. }, () => {
  8216. this.scaleValueImage = Math.min(1, Math.max(0.38, 1 - event.offsetY / 500));
  8217. console.info('onecold scaleValueImage:', this.scaleValueImage)
  8218. this.scaleValueText =Math.min(1, Math.max(0.6, 1 - event.offsetY / 700));
  8219. })
  8220. }
  8221. })
  8222. .onActionEnd((event?: GestureEvent) => {
  8223. // 使用更低的阈值和滑动速度判断
  8224. const minDistance = 300; // 最小滑动距离 100vp
  8225. const minVelocity = 500; // 最小滑动速度
  8226. // 获取滑动速度(如果可用)
  8227. const velocity = event?.velocityY || 0;
  8228. // 判断是否应该关闭:距离足够 或者 速度足够快
  8229. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  8230. if (shouldClose) {
  8231. // 添加关闭动画
  8232. this.getUIContext().animateTo({
  8233. duration: 600,
  8234. curve: Curve.Friction
  8235. }, () => {
  8236. this.isShowPlay = false;
  8237. this.scaleValueImage = 1
  8238. this.scaleValueText = 1
  8239. this.translateY = 0;
  8240. })
  8241. } else {
  8242. // 回弹动画
  8243. this.getUIContext().animateTo({
  8244. duration: 600,
  8245. curve: Curve.Friction
  8246. }, () => {
  8247. this.scaleValueImage = 1
  8248. this.scaleValueText = 1
  8249. this.translateY = 0;
  8250. })
  8251. }
  8252. })
  8253. )
  8254. }
  8255. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  8256. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  8257. HeightBreakpoint.HEIGHT_LG;
  8258. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  8259. @State topBarHeight: number = 50
  8260. @State barOpacity: number = 1
  8261. @State barBottomOpacity: number = 1
  8262. private hideDone: boolean = false;
  8263. @State currentYOffset: number = 0;
  8264. @State bottomBarHeight: number = 68;
  8265. private isHiding: boolean = false;
  8266. //是否是Pura X外屏,或者小屏幕
  8267. isPuraWP() {
  8268. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  8269. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  8270. }
  8271. //是否是Pura X外屏,或者小屏幕,手机横屏
  8272. /**
  8273. * 是否是Pura X外屏,或者小屏幕,手机横屏
  8274. * @returns
  8275. */
  8276. isCoverOpacity() {
  8277. if (this.isPuraWP()) {
  8278. return true
  8279. }
  8280. if (this.isPhoneLan()) {
  8281. return true
  8282. }
  8283. if (deviceInfo.marketName.includes('Pura X')
  8284. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  8285. return true
  8286. }
  8287. return false
  8288. }
  8289. //是不是手机横屏
  8290. isPhoneLan() {
  8291. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  8292. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  8293. logHiCarWindow(`isPhoneLan width=${this.windowWidth}`);
  8294. logHiCarWindow(`isPhoneLan height=${this.windowHeight}`);
  8295. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarStatus=${this.isHiCarStatus}`);
  8296. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, curDisplayIsHiCar=${this.curDisplayIsHiCar}`);
  8297. logHiCarWindow(`window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall=${this.isHiCarSmall()}`);
  8298. if (this.isHiCarKuanBianPing()) {
  8299. return true
  8300. }
  8301. if (this.isHiCar()) {
  8302. return false
  8303. }
  8304. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8305. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  8306. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  8307. return true
  8308. }
  8309. return false
  8310. }
  8311. //是不是1920x720的hicar的屏幕分辨率
  8312. isHiCarKuanBianPing(){
  8313. // if(!this.isHiCar()){
  8314. // return false
  8315. // }
  8316. const hiCarAspectRatios: HiCarAspectRatio[] = [
  8317. { ratio: 1920 / 720, name: "1920x720" },
  8318. ];
  8319. const currentRatio: number = this.windowWidth / this.windowHeight;
  8320. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  8321. logHiCarWindow(`HiCarKuanBianPing currentRatio=${currentRatio}`)
  8322. for (const hiCarRatio of hiCarAspectRatios) {
  8323. logHiCarWindow(`HiCarKuanBianPing hiCarRatio=${hiCarRatio.ratio}`)
  8324. logHiCarWindow(`HiCarKuanBianPing diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  8325. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  8326. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  8327. //宽扁平的尺寸设置列表展示
  8328. this.twoFingerType ==3
  8329. this.isGridMusic = false
  8330. return true;
  8331. }
  8332. }
  8333. return false;
  8334. }
  8335. //是不是hicar的屏幕分辨率
  8336. isHiCarSmall() {
  8337. if(!this.isHiCar()){
  8338. return false
  8339. }
  8340. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  8341. {
  8342. this.columns = 6
  8343. return false
  8344. }
  8345. const hiCarAspectRatios: HiCarAspectRatio[] = [
  8346. { ratio: 800 / 480, name: "800x480" },
  8347. { ratio: 1280 / 720, name: "1280x720" },
  8348. { ratio: 1920 / 1080, name: "1920x1080" },
  8349. ];
  8350. const currentRatio: number = this.windowWidth / this.windowHeight;
  8351. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  8352. logHiCarWindow(`HiCarSmall currentRatio=${currentRatio}`)
  8353. for (const hiCarRatio of hiCarAspectRatios) {
  8354. logHiCarWindow(`HiCarSmall hiCarRatio=${hiCarRatio.ratio}`)
  8355. logHiCarWindow(`HiCarSmall diff=${Math.abs(currentRatio - hiCarRatio.ratio)}`)
  8356. logHiCarWindow(`HiCarSmall isHiCarStatus=${this.isHiCarStatus}`);
  8357. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  8358. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  8359. //宽扁平的尺寸设置列表展示
  8360. return true;
  8361. }
  8362. }
  8363. return false;
  8364. }
  8365. isHiCar() {
  8366. return this.curDisplayIsHiCar;
  8367. }
  8368. //是不是正常的手机竖屏
  8369. isPhonePortrait() {
  8370. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  8371. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  8372. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  8373. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8374. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  8375. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  8376. return true
  8377. }
  8378. return false
  8379. }
  8380. @State showSpeedDialog: boolean = false
  8381. @State longPressSpeed: number = 3 //长按默认倍数
  8382. @Builder
  8383. SpeedDialog() {
  8384. Stack() {
  8385. Column() {
  8386. Text('已切换至' + this.longPressSpeed + '倍速播放')
  8387. .fontColor(Color.White)
  8388. .visibility(Visibility.Hidden)
  8389. }
  8390. .backgroundColor(Color.Black)
  8391. .borderRadius(20)
  8392. .padding({
  8393. top: 10,
  8394. right: 20,
  8395. left: 15,
  8396. bottom: 20
  8397. })
  8398. .opacity(0.6)
  8399. Text('已切换至' + this.longPressSpeed + '倍速播放')
  8400. .fontColor(Color.White)
  8401. }
  8402. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  8403. .zIndex(5)
  8404. .margin({ top: 80 })
  8405. }
  8406. @Builder
  8407. IjkMusicPlayerView() {
  8408. Stack() {
  8409. if(canIUse("SystemCapability.UIDesign.HDSComponent.Core")
  8410. &&deviceInfo.sdkApiVersion>=20&&this.sceneBgController){
  8411. HdsVisualComponent()
  8412. .scene(HdsSceneType.DUAL_EDGE_FLOW_LIGHT_WITH_BACKGROUND_MASK, this.sceneBgController, () => {
  8413. console.info('Succeeded in finishing');
  8414. })
  8415. .width('100%')
  8416. .height('100%')
  8417. .visibility(this.isShowBgLiuGUANG?Visibility.Visible:Visibility.None)
  8418. }
  8419. Column() {
  8420. Column() {
  8421. //播放标题
  8422. Column() {
  8423. this.PlayTitle()
  8424. }
  8425. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  8426. .width('100%')
  8427. .margin({ top: 0 })
  8428. .height(PlayConstants.HEIGHT)
  8429. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  8430. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  8431. if (this.showSpeedDialog) {
  8432. this.SpeedDialog()
  8433. }
  8434. Stack() {
  8435. //手势拖动快进
  8436. Column()
  8437. .width(CommonConstants.FULL_PERCENT)
  8438. .height('100%')
  8439. .gesture(
  8440. GestureGroup(GestureMode.Parallel,
  8441. // 长按屏幕倍数播放
  8442. LongPressGesture({ repeat: true })
  8443. .onAction(() => {
  8444. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8445. this.showSpeedDialog = true;
  8446. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  8447. }
  8448. })
  8449. .onActionEnd(() => {
  8450. this.showSpeedDialog = false;
  8451. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  8452. }),
  8453. //双击屏幕暂停或者播放
  8454. TapGesture({ count: 2 })
  8455. .onAction((event: GestureEvent) => {
  8456. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8457. ToastUtil.showToast('已暂停')
  8458. }
  8459. console.info('onecold playOrPause 6693')
  8460. this.playOrPause()
  8461. })
  8462. )
  8463. )
  8464. }
  8465. .height('65%')
  8466. Swiper() {
  8467. this.CoverInfo()
  8468. this.PlayerLyrics()
  8469. }
  8470. .onChange((index: number) => {
  8471. this.currentSwiperIndex = index
  8472. })
  8473. .indicator(false)
  8474. .displayCount(new BreakpointType({
  8475. sm: 1,
  8476. md: 2,
  8477. lg: 2,
  8478. xl: 2,
  8479. xxl: 2
  8480. }).getValue(this.currentBreakpoint))
  8481. .clip(false)
  8482. .loop(false)
  8483. .autoPlay(false)
  8484. // .interval(8000)
  8485. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  8486. .height('100%')
  8487. .hitTestBehavior(HitTestMode.Transparent)
  8488. Image($r('app.media.icon_replay'))
  8489. .objectFit(ImageFit.Auto)
  8490. .width('120px')
  8491. .height('120px')
  8492. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  8493. .border({ width: 0 })
  8494. .visibility(Visibility.None)
  8495. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  8496. .onClick(() => {
  8497. console.info('onecold startPlayOrResumePlay 6744')
  8498. this.startPlayOrResumePlay();
  8499. })
  8500. }
  8501. .width(CommonConstants.FULL_PERCENT)
  8502. .height(CommonConstants.FULL_PERCENT)
  8503. .justifyContent(FlexAlign.End)
  8504. }
  8505. .justifyContent(FlexAlign.End)
  8506. .margin({ bottom: 8 })
  8507. }
  8508. .backgroundImage(!this.isMusicBGCover||StrUtil.isEmpty(this.cover)?null: this.cover)
  8509. .backgroundImageSize(this.isPuraWP()||!this.isMusicBGCover ? { width: '100%' } : { height: '150%', width: '100%' })
  8510. .animation({
  8511. duration: 666,
  8512. curve: 'ease-in-out' // 可选动画曲线
  8513. })
  8514. .backgroundBlurStyle((this.isPuraWP() && this.currentSwiperIndex === 0) ||!this.isMusicBGCover
  8515. ? BlurStyle.NONE :
  8516. BlurStyle.BACKGROUND_ULTRA_THICK)
  8517. .hitTestBehavior(HitTestMode.Transparent)
  8518. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  8519. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  8520. .onClick(() => {
  8521. if(this.isHiCar())
  8522. return
  8523. if(this.is_auto_hide_progress){
  8524. this.is_auto_hide_progress = false
  8525. }
  8526. this.startAutoHide()
  8527. })
  8528. }
  8529. @Consume progressValue: number ;
  8530. @State currentTime: string = "00:00";
  8531. @State totalTime: string = "00:00";
  8532. @State loadingVisible: Visibility = Visibility.None;
  8533. @State replayVisible: Visibility = Visibility.None;
  8534. @State slideEnable: boolean = false;
  8535. @State aspRatio: number = 0.5;
  8536. @State mContext: object | undefined = undefined;
  8537. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  8538. @State mFirst: boolean = true;
  8539. @State mDestroyPage: boolean = false;
  8540. @State playSpeed: number = 1;
  8541. @State oldSeconds: number = 0;
  8542. @State isSeekTo: boolean = false;
  8543. @State isCurrentTime: boolean = false;
  8544. @State videoWidth: string = '100%';
  8545. @State videoHeight: string = '100%';
  8546. @State initAspectRatio: number = 1;
  8547. @State videoAspectRatio: number = this.initAspectRatio;
  8548. @State videoUrl: string = '';
  8549. private last: number = 0;
  8550. @State videoParentAspectRatio: number = this.initAspectRatio;
  8551. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  8552. @Consume CONTROL_PlayStatus: number ;
  8553. @State PROGRESS_MAX_VALUE: number = 100;
  8554. @State updateProgressTimer: number = 0;
  8555. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  8556. @State name: string = '';
  8557. // @State loop: boolean = false;
  8558. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  8559. @State multiple: string = '1.0X';
  8560. xcomponentController: XComponentController = new XComponentController()
  8561. private panOptionBright: PanGestureOptions =
  8562. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  8563. private panOptionVolume: PanGestureOptions =
  8564. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  8565. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  8566. //手势的音量控制和亮度控制
  8567. private positionX: number = PlayConstants.POSITION_X;
  8568. private positionY: number = PlayConstants.POSITION_Y;
  8569. private windowClass: window.Window = globalThis.windowClass
  8570. @State volume: number = 0.5;
  8571. @State volumeSmall: boolean = false
  8572. @State autoParseMusicName: boolean = true
  8573. @State isShowFileName: boolean = false
  8574. @State isLongNameRoLL: boolean = true//长歌名滚动
  8575. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  8576. @State bright: number = PlayConstants.BRIGHT;
  8577. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  8578. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  8579. @State screenWidth: number = 0
  8580. @State screenHeight: number = 0
  8581. @State statusBarHeight: number = 0
  8582. @State isYesFull: boolean = false
  8583. private seekValue: number = 0
  8584. @State isVideoLock: boolean = false; // Whether the video playback is locked
  8585. eventHub = getContext().eventHub;
  8586. //投播组件
  8587. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  8588. private castController: avSession.AVCastController | undefined = undefined;
  8589. @State isCastPlaying: boolean = false;
  8590. @State currentTime2: number = 0;
  8591. @State currentStringTime: string = '00:00';
  8592. @State duration: number = 0;
  8593. @State isReady: boolean = false;
  8594. @State durationTime: number = 0;
  8595. @State durationStringTime: string = '00:00';
  8596. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  8597. // @State isPlaying: boolean = false;
  8598. private castSeek: boolean = false;
  8599. private castItem: avSession.AVQueueItem | undefined = undefined;
  8600. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  8601. @State rotateAngle2: number = -9
  8602. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  8603. @Consume cover: string | undefined ;
  8604. @State artist: string | undefined = ''
  8605. // 1.初始化controller
  8606. private lyricController: LyricController = new LyricController()
  8607. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  8608. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  8609. private parser = new LyricParser()
  8610. @State randomColor: string = 'rgb(0,0,0)'
  8611. @State randomShakenX: number = 0
  8612. @State randomShakenY: number = 0
  8613. @State lyricTextSize: number = 24
  8614. @State lyricContent: string = ''
  8615. @State isDebug: boolean = false
  8616. @State isHightLightCenter: boolean = true
  8617. /**
  8618. * 初始化歌词加载与展示逻辑
  8619. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  8620. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  8621. * @param isApi2 是否使用API2获取歌词(可选)
  8622. *
  8623. * 主要流程:
  8624. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  8625. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  8626. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  8627. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  8628. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  8629. * 6. 解析失败或读取失败时,清空歌词显示。
  8630. *
  8631. * 注意事项:
  8632. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  8633. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  8634. * - 歌词内容解析后通过lyricController驱动UI渲染。
  8635. */
  8636. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
  8637. if (StrUtil.isEmpty(lyricPath)) {
  8638. return
  8639. }
  8640. this.initPipLyricSetting()
  8641. this.lyricControllerSingle
  8642. .setTextSize(15)
  8643. .setCacheSize(4)
  8644. .setTextColor("#FFFFFF")
  8645. .setHighlightColor(this.currentHighLightLyricColor)
  8646. .setHighlightScale(1.2)
  8647. .setEmptyHint("")
  8648. .setAlignMode('center')
  8649. .setAnimationDuration(500)
  8650. .setSingleLine(true)
  8651. this.lyricContent = ''
  8652. this.lyricController
  8653. .setTextSize(this.currentLyricSize)
  8654. .setCacheSize(4)
  8655. .setTextColor("#DDDDDD")
  8656. .setHighlightColor("#FFFFFF")
  8657. .setEmptyHint("")
  8658. .setAnimationDuration(1000)
  8659. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  8660. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  8661. this.setBlurDegree(this.blurDegree, false)
  8662. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  8663. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  8664. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  8665. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  8666. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  8667. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  8668. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  8669. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  8670. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  8671. this.lyricController.setTextWeight(this.lyricTextWeight)
  8672. this.showSingleLyric = false
  8673. this.timeOffset = 0
  8674. this.lyricController.setLyric(null)
  8675. this.lyricControllerSingle.setLyric(null)
  8676. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  8677. console.log("onecold lyricPath =" + lyricPath)
  8678. // 1. 检查内嵌歌词
  8679. let neiqianLrc = ''
  8680. let lyContent = this.currentSong?.lyricContent
  8681. if(lyContent && StrUtil.isNotEmpty(lyContent)){
  8682. neiqianLrc = lyContent
  8683. }
  8684. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast && !isLocal) {
  8685. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  8686. // Navidrome JSON歌词转换
  8687. if (this.currentSong && isNavidromeType(this.currentSong.type)) {
  8688. const convertedLyric: string | undefined = LyricUtil.convertNavidromeJsonLyricToLrc(neiqianLrc);
  8689. if (convertedLyric) {
  8690. neiqianLrc = convertedLyric;
  8691. console.log("onecold Navidrome歌词转换成功");
  8692. }
  8693. }
  8694. this.setLyricToControllers(neiqianLrc);
  8695. return
  8696. }
  8697. // 2. 尝试从服务器获取歌词 (Navidrome/Jellyfin/Emby)
  8698. if (this.currentSong && (isJellyfinType(this.currentSong.type)|| isEmbyType(this.currentSong.type))) {
  8699. const manager = RemoteDriveManager.getInstance();
  8700. const getAccount = (accountId: string) => manager.getWebDavAccountById(accountId);
  8701. // 将currentSong转换为SongData接口
  8702. const songData: SongData = {
  8703. webdav_account_id: this.currentSong.webdav_account_id,
  8704. artist: this.currentSong.artist,
  8705. name: this.currentSong.name,
  8706. webdav_id: this.currentSong.webdav_id,
  8707. lyricIndex: this.currentSong.lyricIndex,
  8708. type: this.currentSong.type
  8709. };
  8710. let serverLyric = '';
  8711. if (!serverLyric && isJellyfinType(songData.type)) {
  8712. serverLyric = await lyricService.fetchJellyfinLyric(songData, getAccount);
  8713. }
  8714. if (!serverLyric && isEmbyType(songData.type)) {
  8715. serverLyric = await lyricService.fetchEmbyLyric(songData, getAccount);
  8716. }
  8717. if (serverLyric) {
  8718. this.setLyricToControllers(serverLyric, lyricPath);
  8719. return;
  8720. }
  8721. }
  8722. // 3. 尝试在线歌词API
  8723. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  8724. && !Utility.isVideoByExtension(this.videoUrl))) {
  8725. this.fetchOnlineLyric(lyricPath, isOnLineAndToast || false, isApi2);
  8726. return;
  8727. }
  8728. // 4. 从本地文件读取歌词
  8729. await this.loadLyricFromFile(lyricPath, jiaMilyricPath, isLocal || false);
  8730. }
  8731. /**
  8732. * 从本地文件加载歌词
  8733. */
  8734. private async loadLyricFromFile(lyricPath: string, jiaMilyricPath: string, isLocal: boolean): Promise<void> {
  8735. try {
  8736. let isJiaMi = false;
  8737. let realLyricPath = lyricPath;
  8738. if (FileUtil.accessSync(jiaMilyricPath)) {
  8739. isJiaMi = true;
  8740. realLyricPath = jiaMilyricPath;
  8741. console.info("onecold 找到加密本地歌词 ");
  8742. } else {
  8743. isJiaMi = false;
  8744. realLyricPath = lyricPath;
  8745. console.info("onecold 找到本地歌词 ");
  8746. }
  8747. // 读取文件内容
  8748. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  8749. const stat = await fileIo.stat(file.fd);
  8750. const arrayBuffer = new ArrayBuffer(stat.size);
  8751. fs.read(file.fd, arrayBuffer)
  8752. .then((readLen: number) => {
  8753. console.info("read file data succeed");
  8754. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  8755. if (buf.length === 0) {
  8756. throw new Error("Buffer is empty after reading the file");
  8757. }
  8758. try {
  8759. // 检测文件编码
  8760. let detectedEncoding = this.detect(arrayBuffer);
  8761. console.info("onecoldT Detected encoding: " + detectedEncoding);
  8762. // 使用检测到的编码解码,解决中文乱码问题
  8763. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  8764. console.info("onecoldT Detected textDecoder: " + textDecoder);
  8765. let fileContent = textDecoder.decode(buf);
  8766. console.info(`onecoldT The content of file1: ${fileContent}`);
  8767. // 解密
  8768. if (isJiaMi) {
  8769. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  8770. }
  8771. console.info(`onecold The content of file2: ${fileContent}`);
  8772. this.lyricContent = fileContent;
  8773. if(isLocal){
  8774. // 编辑标签选择本地歌词需要赋值给this.lyricConStr
  8775. this.lyricConStr = fileContent;
  8776. }
  8777. this.setLyricToControllers(fileContent);
  8778. console.info(`The content of file: ${fileContent}`);
  8779. } catch (chardetError) {
  8780. console.error("chardet.detect failed with error: " + chardetError.message);
  8781. this.clearLyricControllers();
  8782. }
  8783. })
  8784. .catch((err: BusinessError) => {
  8785. this.clearLyricControllers();
  8786. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  8787. })
  8788. .catch((err: Error) => {
  8789. this.clearLyricControllers();
  8790. console.error("read file 2 data failed with error message: " + err.message);
  8791. })
  8792. .finally(() => {
  8793. fs.closeSync(file);
  8794. });
  8795. } catch (error) {
  8796. this.clearLyricControllers();
  8797. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  8798. }
  8799. }
  8800. detect(data: ArrayBuffer): string {
  8801. //创建检测对象
  8802. let detector: UniversalDetector = new UniversalDetector();
  8803. // 传入检测数据并实时判断编码格式
  8804. detector.handleData(data, 0, data.byteLength);
  8805. // 标记检测数据 读取结束
  8806. detector.dataEnd();
  8807. // 获取检测结果
  8808. let detected: string = detector.getDetectedCharset();
  8809. // 释放资源
  8810. detector.reset();
  8811. return detected;
  8812. }
  8813. /**
  8814. * 设置歌词到所有控制器
  8815. * @param lyricText 歌词文本
  8816. * @param savePath 可选,如果提供则保存到本地文件
  8817. */
  8818. private setLyricToControllers(lyricText: string, savePath?: string): void {
  8819. if (StrUtil.isEmpty(lyricText)) {
  8820. this.clearLyricControllers();
  8821. return;
  8822. }
  8823. this.lyricContent = lyricText;
  8824. const lines: string[] = lyricText.split('\n').map((line: string) => line.trim());
  8825. const lyric: Lyric = this.parser.parse(lines);
  8826. this.lyricController.setLyric(lyric);
  8827. this.lyricControllerXF.setLyric(lyric);
  8828. this.lyricControllerSingle.setLyric(lyric);
  8829. this.showSingleLyric = true;
  8830. // 如果提供了保存路径,保存歌词到本地
  8831. if (savePath) {
  8832. this.saveDataToFile(lyricText, savePath, false);
  8833. }
  8834. }
  8835. /**
  8836. * 清空所有歌词控制器
  8837. */
  8838. private clearLyricControllers(): void {
  8839. this.lyricController.setLyric(null);
  8840. this.lyricControllerXF.setLyric(null);
  8841. this.lyricControllerSingle.setLyric(null);
  8842. }
  8843. /**
  8844. * 从在线API获取歌词
  8845. */
  8846. private fetchOnlineLyric(lyricPath: string, isOnLineAndToast: boolean, isApi2?: boolean): void {
  8847. if (!this.currentSong) {
  8848. this.clearLyricControllers();
  8849. if (isOnLineAndToast) {
  8850. ToastUtil.showShort('未获取到歌词!');
  8851. }
  8852. return;
  8853. }
  8854. let artist = this.currentSong.artist || '';
  8855. if (isApi2 === undefined) {
  8856. isApi2 = false;
  8857. }
  8858. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  8859. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  8860. this.setLyricToControllers(res, lyricPath);
  8861. } else {
  8862. this.clearLyricControllers();
  8863. if (isOnLineAndToast) {
  8864. ToastUtil.showShort('未获取到歌词!');
  8865. }
  8866. }
  8867. });
  8868. }
  8869. //初始化悬浮歌词的自定义设置
  8870. initPipLyricSetting() {
  8871. this.lyricControllerXF
  8872. .setTextSize(this.currentLyricSize)
  8873. .setCacheSize(4)
  8874. .setTextColor("#DDDDDD")
  8875. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  8876. .setEmptyHint("")
  8877. .setAnimationDuration(1000)
  8878. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  8879. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  8880. this.setBlurDegree(this.blurDegreePip, true)
  8881. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  8882. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  8883. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  8884. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  8885. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  8886. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  8887. this.lyricControllerXF.setHightLightCenter(true)
  8888. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  8889. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  8890. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  8891. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  8892. if (this.pipBgIndex === 0) {
  8893. if (this.cover) {
  8894. this.pipBg = this.cover
  8895. } else {
  8896. this.pipBg = this.imageColor
  8897. }
  8898. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  8899. }
  8900. }
  8901. //根据item返回歌词内容
  8902. async getLyricContent(item: VideoItem): Promise<string> {
  8903. let neiqianLrc = ''
  8904. let lyContent = item?.lyricContent
  8905. if(lyContent&&StrUtil.isNotEmpty(lyContent)){
  8906. neiqianLrc = lyContent
  8907. return neiqianLrc
  8908. }
  8909. try {
  8910. //取数据库里面的歌词lyContent
  8911. const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
  8912. if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
  8913. console.log("onecold Lyrics:", lyricContent);
  8914. neiqianLrc = lyricContent
  8915. return neiqianLrc
  8916. }
  8917. } catch (error) {
  8918. console.error("Error fetching lyrics:", error);
  8919. }
  8920. try {
  8921. let filePath = item.filePath;
  8922. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  8923. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  8924. let isJiaMi = false;
  8925. let realLyricPath = lyricPath;
  8926. if (FileUtil.accessSync(jiaMilyricPath)) {
  8927. isJiaMi = true;
  8928. realLyricPath = jiaMilyricPath;
  8929. console.info("onecold 找到加密本地歌词");
  8930. } else {
  8931. console.info("onecold 找到本地歌词");
  8932. }
  8933. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  8934. const stat = await fileIo.stat(file.fd);
  8935. const arrayBuffer = new ArrayBuffer(stat.size);
  8936. const readLen = await fs.read(file.fd, arrayBuffer);
  8937. console.info("read file data succeed");
  8938. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  8939. if (buf.length === 0) {
  8940. throw new Error("Buffer is empty after reading the file");
  8941. }
  8942. // let detectedEncoding = chardet.detect(buf);
  8943. let detectedEncoding = this.detect(arrayBuffer)
  8944. console.info("Detected encoding: " + detectedEncoding);
  8945. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  8946. let fileContent = textDecoder.decode(buf);
  8947. console.info(`onecold The content of file1: ${fileContent}`);
  8948. if (isJiaMi) {
  8949. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  8950. }
  8951. console.info(`onecold The content of file2: ${fileContent}`);
  8952. fs.closeSync(file);
  8953. return fileContent;
  8954. } catch (error) {
  8955. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  8956. return '';
  8957. }
  8958. }
  8959. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  8960. if (StrUtil.isEmpty(filePath)) {
  8961. return
  8962. }
  8963. try {
  8964. //将content进行加密
  8965. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  8966. let lyricContent = ''
  8967. if (isJiaMi) {
  8968. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  8969. } else {
  8970. lyricContent = content
  8971. }
  8972. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  8973. // 清空文件内容
  8974. await fileIo.truncate(file.fd, 0);
  8975. await fileIo.write(file.fd, lyricContent);
  8976. await fileIo.close(file);
  8977. console.log('onecold lyric file Data saved successfully.');
  8978. } catch (error) {
  8979. console.error('onecold lyric file Failed to save data:', error);
  8980. }
  8981. }
  8982. // 定义开始旋转的方法
  8983. // 使用动画系统优化旋转性能,避免 setInterval 频繁更新导致卡顿
  8984. @State timer: number = 0
  8985. @State rotateAngle: number = 0
  8986. @State isRotationRunning: boolean = false // 旋转动画是否正在运行
  8987. //封面旋转动画
  8988. animationRoFun() {
  8989. if (this.isPlaying && !this.isCoverRectangle) {
  8990. // 启动旋转动画
  8991. if (!this.isRotationRunning) {
  8992. this.isRotationRunning = true
  8993. this.startContinuousRotation()
  8994. }
  8995. this.startRotation()
  8996. } else {
  8997. // 停止旋转动画
  8998. this.isRotationRunning = false
  8999. clearInterval(this.timer)
  9000. this.stopRotation()
  9001. }
  9002. }
  9003. // 使用持续的动画进行旋转,避免频繁状态更新
  9004. private startContinuousRotation() {
  9005. clearInterval(this.timer)
  9006. // 改为每 1000ms 更新 36 度(10秒一圈),减少更新频率
  9007. // 不使用 % 360 取模,让角度持续累加,避免反转
  9008. this.timer = setInterval(() => {
  9009. if (this.isRotationRunning) {
  9010. this.rotateAngle = this.rotateAngle + 36
  9011. }
  9012. }, 1000)
  9013. }
  9014. // 定义开始旋转的方法
  9015. startRotation() {
  9016. if (this.isPlaying) {
  9017. animateTo({
  9018. duration: 777,
  9019. iterations: 1,
  9020. curve: Curve.Linear
  9021. }, () => {
  9022. this.rotateAngle2 = -9
  9023. })
  9024. }
  9025. }
  9026. // 回调,暂停和播放按钮回调,下一首和上一首
  9027. playChange() {
  9028. // if(this.isCoverRectangle){
  9029. // return
  9030. // }
  9031. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  9032. this.setIsPlaying(true)
  9033. this.animationState = AnimationStatus.Running
  9034. } else {
  9035. this.setIsPlaying(false)
  9036. this.animationState = AnimationStatus.Paused
  9037. }
  9038. AppStorage.setOrCreate('animationState', this.animationState);
  9039. }
  9040. // 定义停止旋转的方法
  9041. stopRotation() {
  9042. if (this.isCoverRectangle) {
  9043. this.rotateAngle = 0
  9044. } else {
  9045. //唱针以左上角为点选择逆时针40度
  9046. animateTo({
  9047. duration: 1000,
  9048. curve: Curve.Linear,
  9049. iterations: 1,
  9050. }, () => {
  9051. this.rotateAngle2 = -45;
  9052. });
  9053. }
  9054. }
  9055. @Builder
  9056. private LyricsTopItem() {
  9057. Row() {
  9058. Stack() {
  9059. Image(this.cover)
  9060. .height(58)
  9061. .width(58)
  9062. .clip(true)
  9063. .sourceSize({width:38, height:38})
  9064. .alt($r('app.media.alt'))
  9065. .borderRadius(8)
  9066. .clickEffect({ level: ClickEffectLevel.HEAVY })
  9067. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  9068. .shadow({
  9069. radius: 22,
  9070. type: ShadowType.BLUR,
  9071. color: 'on_primary'
  9072. })
  9073. }
  9074. .width('18%')
  9075. Column() {
  9076. Column() {
  9077. Text(this.name)
  9078. .fontSize(16)
  9079. .maxLines(1)
  9080. .fontWeight(FontWeight.Bolder)
  9081. .fontColor(Color.White)
  9082. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  9083. Row() {
  9084. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  9085. .fontSize(13)
  9086. .fontWeight(FontWeight.Bolder)
  9087. .padding({ top: 8 })
  9088. .fontColor(Color.White)
  9089. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  9090. Blank()
  9091. }
  9092. }
  9093. .height('100%')
  9094. .width('100%')
  9095. .justifyContent(FlexAlign.Center)
  9096. .alignItems(HorizontalAlign.Start)
  9097. }
  9098. .height('100%')
  9099. .width('65%')
  9100. Column() {
  9101. Image($r('app.media.lyric'))
  9102. .width(28)
  9103. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9104. .margin({ right: 30 })
  9105. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9106. .onClick(() => {
  9107. this.isLyricSetting = !this.isLyricSetting;
  9108. })
  9109. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  9110. height: '99%',
  9111. dragBar: true,
  9112. preferType: SheetType.CENTER,
  9113. showClose: true,
  9114. blurStyle: BlurStyle.Thin,
  9115. backgroundColor: Color.Transparent,
  9116. title: { title: $r('app.string.lyric_setting') }
  9117. })
  9118. }
  9119. .width('18%')
  9120. }
  9121. .width('82%')
  9122. .height(58)
  9123. .justifyContent(FlexAlign.SpaceBetween)
  9124. }
  9125. //歌词显示
  9126. @Builder
  9127. PlayerLyrics() {
  9128. Column() {
  9129. Column() {
  9130. this.LyricsTopItem()
  9131. }
  9132. .height(this.isPuraWP() ? 15 : 58)
  9133. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  9134. Visibility.None : Visibility.Visible)
  9135. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  9136. .width("100%")
  9137. Column() {
  9138. LyricView2({
  9139. controller: this.lyricController,
  9140. enableSeek: true,
  9141. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  9142. seekLineColor: "#80ffffff", // 滑动定位线颜色
  9143. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  9144. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  9145. if (!this.isPlaying) {
  9146. console.info('onecold startPlayOrResumePlay 7527')
  9147. this.startPlayOrResumePlay()
  9148. }
  9149. else {
  9150. this.isSeekTo = true;
  9151. this.mDestroyPage = false;
  9152. this.showLoadIng();
  9153. this.seekTo(position + "");
  9154. this.isSeekTo = false;
  9155. }
  9156. return true
  9157. }
  9158. })
  9159. .width("100%")
  9160. .layoutWeight(1)
  9161. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  9162. if (this.isPhoneLan()) {
  9163. Column() {
  9164. this.playProgressView()
  9165. // this.playCenterView()
  9166. }
  9167. .margin({ bottom: 30, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  9168. }
  9169. }
  9170. .position({
  9171. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  9172. (this.isPuraWP() ? 58 : 99)
  9173. })
  9174. .justifyContent(FlexAlign.Center)
  9175. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  9176. }
  9177. }
  9178. @Builder
  9179. SingleLyricView() {
  9180. Column() {
  9181. Column() {
  9182. LyricView2({
  9183. controller: this.lyricControllerSingle,
  9184. enableSeek: false,
  9185. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  9186. seekLineColor: "#80ffffff", // 滑动定位线颜色
  9187. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  9188. })
  9189. }
  9190. .height(66)
  9191. .margin({ bottom: 20 })
  9192. }
  9193. }
  9194. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  9195. @Builder
  9196. BottomControl() {
  9197. Column() {
  9198. this.TopPlayProgressView()
  9199. //播放 暂停,下一首,上一首
  9200. this.playCenterView()
  9201. if(!this.curDisplayIsHiCar){
  9202. //播放进度条
  9203. this.BottomView()
  9204. }
  9205. }
  9206. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  9207. }
  9208. //播放控制上一首 下一首 暂停和播放
  9209. @Builder
  9210. playCenterView(){
  9211. Row() {
  9212. Button({type:ButtonType.Circle,stateEffect:true}){
  9213. //更多功能
  9214. Image($r('app.media.menu'))
  9215. .width(24)
  9216. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9217. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  9218. height: '99%',
  9219. preferType:SheetType.CENTER,
  9220. dragBar: true,
  9221. showClose: true,
  9222. blurStyle: BlurStyle.Thin,
  9223. title: { title: $r('app.string.more') },
  9224. backgroundColor: Color.Transparent,
  9225. })
  9226. }
  9227. .height(45)
  9228. .width(45)
  9229. .margin({ left: 5 })
  9230. .backgroundColor(Color.Transparent)
  9231. .onClick(() => {
  9232. this.isShowMoreView = !this.isShowMoreView;
  9233. })
  9234. Button({type:ButtonType.Circle,stateEffect:true}){
  9235. Image($r('app.media.ic_previous'))
  9236. .width(33)
  9237. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9238. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9239. }
  9240. .height(45)
  9241. .width(45)
  9242. .onClick(async () => {
  9243. await this.playPrevious()
  9244. })
  9245. .backgroundColor(Color.Transparent)
  9246. Button({type:ButtonType.Circle,stateEffect:true}){
  9247. Stack() {
  9248. Column() {
  9249. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  9250. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  9251. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  9252. .width(this.isPhoneLan()?45:55)
  9253. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9254. .fillColor(Color.White)
  9255. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9256. }
  9257. // 加载进度圈
  9258. if (this.isPlayerLoading) {
  9259. Progress({value:0,total:100,type:ProgressType.Ring })
  9260. .width(this.isPhoneLan()?48:57)
  9261. .height(this.isPhoneLan()?48:57)
  9262. .color(Color.White)
  9263. .style({ strokeWidth: 5, status: ProgressStatus.LOADING })
  9264. }
  9265. }
  9266. .width(this.isPhoneLan()?45:55)
  9267. .height(this.isPhoneLan()?45:55)
  9268. }
  9269. .onClick(async () => {
  9270. this.playOrPause()
  9271. })
  9272. .backgroundColor(Color.Transparent)
  9273. .layoutWeight(1)
  9274. // PointLightButton({
  9275. // builder: () => {
  9276. // this.PlayOrPauseButton()
  9277. // },
  9278. // isPx: true,
  9279. // builderHeight: 60,
  9280. // builderWidth: 60,
  9281. // })
  9282. // .layoutWeight(1)
  9283. // .onClick(() =>{
  9284. // this.playOrPause()
  9285. // })
  9286. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9287. Image($r('app.media.ic_next'))
  9288. .width(33)
  9289. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9290. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9291. }
  9292. .height(45)
  9293. .width(45)
  9294. .backgroundColor(Color.Transparent)
  9295. .onClick(async () => {
  9296. await this.playNext();
  9297. })
  9298. if(this.curDisplayIsHiCar){
  9299. this.playModeButton()
  9300. }else{
  9301. this.fullButton()
  9302. }
  9303. }
  9304. .width('95%')
  9305. .margin({ bottom:this.isCoverOpacity()?0:15 })
  9306. .justifyContent(FlexAlign.SpaceEvenly)
  9307. }
  9308. @Builder
  9309. PlayOrPauseButton(){
  9310. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  9311. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  9312. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  9313. .width(this.isPhoneLan()?45:55)
  9314. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9315. .fillColor(Color.White)
  9316. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9317. }
  9318. @Builder
  9319. TopPlayProgressView(){
  9320. Column() {
  9321. Row(){
  9322. Stack(){
  9323. SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
  9324. .fontColor([Color.White])
  9325. .fontSize(21)
  9326. .effectStrategy(1)
  9327. Text(this.fastForwardSeconds)
  9328. .fontColor(Color.White)
  9329. .fontSize(10)
  9330. .fontWeight(FontWeight.Bold)
  9331. }
  9332. .padding({left:12,bottom:6})
  9333. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  9334. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9335. .onClick(()=>{
  9336. this.backForward()
  9337. })
  9338. Slider({
  9339. value: this.progressValue,
  9340. min: 0,
  9341. max: this.PROGRESS_MAX_VALUE,
  9342. step: 1,
  9343. style: SliderStyle.InSet
  9344. })
  9345. .height(20)
  9346. .blockColor('rgba(255,255,255,1)')
  9347. .trackColor('rgba(255,255,255,0.3)')
  9348. .selectedColor(Color.White)
  9349. .trackThickness(4)
  9350. .showSteps(false)
  9351. .showTips(true)
  9352. .layoutWeight(1)
  9353. .enabled(this.slideEnable)
  9354. .onChange((value: number, mode: SliderChangeMode) => {
  9355. // if (mode == 2) {
  9356. this.isSeekTo = true;
  9357. this.mDestroyPage = false;
  9358. this.showLoadIng();
  9359. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  9360. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  9361. this.seekTo(seekValue + "");
  9362. // this.setProgress()
  9363. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  9364. this.isSeekTo = false;
  9365. // }
  9366. })
  9367. Stack(){
  9368. SymbolGlyph($r('sys.symbol.arrow_clockwise'))
  9369. .fontColor([Color.White])
  9370. .fontSize(21)
  9371. .effectStrategy(1)
  9372. Text(this.fastForwardSeconds)
  9373. .fontColor(Color.White)
  9374. .fontSize(10)
  9375. .fontWeight(FontWeight.Bold)
  9376. }
  9377. .padding({right:10,bottom:6})
  9378. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  9379. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9380. .onClick(()=>{
  9381. this.fastForward()
  9382. })
  9383. }
  9384. .justifyContent(FlexAlign.Center)
  9385. .padding({left:20,right:20})
  9386. .width(this.isLandscape?'88%':'95%')
  9387. Row() {
  9388. Text(this.currentTime)
  9389. .fontSize(10)
  9390. .fontColor(Color.White)
  9391. .margin({left:25})
  9392. Blank()
  9393. Text(this.totalTime)
  9394. .fontSize(10)
  9395. .fontColor(Color.White)
  9396. .margin({right:25})
  9397. }
  9398. .width(this.isLandscape?'85%':'90%')
  9399. .height(10)
  9400. }
  9401. .width('100%')
  9402. .alignItems(HorizontalAlign.Center)
  9403. }
  9404. @Builder
  9405. playModeButton(){
  9406. Button({type:ButtonType.Circle,stateEffect:true}){
  9407. Column() {
  9408. if (this.playType === 0) {
  9409. Image($r('app.media.loop'))
  9410. .width(27)
  9411. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9412. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9413. } else if (this.playType === 1) {
  9414. Image($r('app.media.single'))
  9415. .width(27)
  9416. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9417. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9418. } else if (this.playType === 2) {
  9419. Image($r('app.media.normal_play'))
  9420. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9421. .width(27)
  9422. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9423. } else if (this.playType === 3) {
  9424. Image($r('app.media.random'))
  9425. .width(27)
  9426. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9427. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9428. }
  9429. }
  9430. }
  9431. .layoutWeight(1)
  9432. .margin({ left: 5 })
  9433. .height(45)
  9434. .width(45)
  9435. .backgroundColor(Color.Transparent)
  9436. .onClick(async () => {
  9437. this.setLoopMode()
  9438. })
  9439. }
  9440. //播放进度条
  9441. @Builder
  9442. BottomView(){
  9443. Row() {
  9444. this.playModeButton()
  9445. if(this.currentSong){
  9446. Button({type:ButtonType.Circle,stateEffect:true}){
  9447. Column() {
  9448. Image($r('app.media.rename2'))
  9449. .width(21)
  9450. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9451. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9452. }
  9453. }
  9454. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  9455. height: '99%',
  9456. dragBar: true,
  9457. showClose: true,
  9458. preferType: SheetType.BOTTOM,
  9459. title: { title: '编辑标签' }
  9460. })
  9461. .height(45)
  9462. .width(45)
  9463. .layoutWeight(1)
  9464. .backgroundColor(Color.Transparent)
  9465. .onClick(async () => {
  9466. this.initEditFields(this.currentSong)
  9467. this.tempLyricContent = this.lyricContent
  9468. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  9469. this.lyricConStr = this.tempLyricContent
  9470. }
  9471. this.isShowEdit = !this.isShowEdit;
  9472. })
  9473. }
  9474. Button({type:ButtonType.Circle,stateEffect:true}){
  9475. Column() {
  9476. Image($r('app.media.lyric'))
  9477. .width(26)
  9478. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9479. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9480. }
  9481. }
  9482. .height(45)
  9483. .width(45)
  9484. .layoutWeight(1)
  9485. .backgroundColor(Color.Transparent)
  9486. .onClick(async () => {
  9487. this.isLyricSetting = !this.isLyricSetting;
  9488. })
  9489. //播放列表
  9490. Button({type:ButtonType.Circle,stateEffect:true}){
  9491. Image($r('app.media.hm_playlist'))
  9492. .width(24)
  9493. .fillColor(Color.White)
  9494. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9495. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9496. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  9497. height: '95%',
  9498. dragBar: true,
  9499. showClose: true,
  9500. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9501. blurStyle: BlurStyle.Thin,
  9502. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  9503. title: {
  9504. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  9505. + `(${this.songList.length}首)`
  9506. }
  9507. })
  9508. }
  9509. .layoutWeight(1)
  9510. .height(45)
  9511. .width(45)
  9512. .backgroundColor(Color.Transparent)
  9513. .onClick(() => {
  9514. this.isShowSheetView = !this.isShowSheetView;
  9515. if(this.isPlayListBgGrass){
  9516. this.isFrontWhite = true
  9517. }else{
  9518. this.isFrontWhite = false
  9519. }
  9520. this.scrollIndex()
  9521. })
  9522. }
  9523. .width(this.isLandscape?'88%':'95%')
  9524. .justifyContent(FlexAlign.SpaceAround)
  9525. .height(30)
  9526. .animation({
  9527. duration: 666,
  9528. curve: 'ease-in-out' // 可选动画曲线
  9529. })
  9530. }
  9531. @Builder
  9532. fullButton(){
  9533. Button({type:ButtonType.Circle,stateEffect:true}){
  9534. Column() {
  9535. Image($r('app.media.full_4'))
  9536. .width(25)
  9537. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9538. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9539. }
  9540. }
  9541. .layoutWeight(1)
  9542. .backgroundColor(Color.Transparent)
  9543. .height(45)
  9544. .width(45)
  9545. .onClick(async () => {
  9546. if (this.isLandscape) {
  9547. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  9548. } else {
  9549. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  9550. }
  9551. })
  9552. }
  9553. //旧版本播放进度条
  9554. @Builder
  9555. playProgressView() {
  9556. Row() {
  9557. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9558. Column() {
  9559. if (this.playType === 0) {
  9560. Image($r('app.media.loop'))
  9561. .width($r('app.float.control_image_width'))
  9562. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9563. } else if (this.playType === 1) {
  9564. Image($r('app.media.single'))
  9565. .width($r('app.float.control_image_width'))
  9566. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9567. } else if (this.playType === 2) {
  9568. Image($r('app.media.normal_play'))
  9569. .width($r('app.float.control_image_width'))
  9570. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9571. } else if (this.playType === 3) {
  9572. Image($r('app.media.random'))
  9573. .width($r('app.float.control_image_width'))
  9574. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9575. }
  9576. }
  9577. }
  9578. .visibility(this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  9579. .animation({
  9580. duration: 666,
  9581. curve: 'ease-in-out' // 可选动画曲线
  9582. })
  9583. .backgroundColor(Color.Transparent)
  9584. .margin({ right: 10 })
  9585. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9586. .onClick(async () => {
  9587. this.setLoopMode()
  9588. })
  9589. Text(this.currentTime)
  9590. .fontSize($r('app.float.slider_font_size'))
  9591. .fontColor(Color.White)
  9592. .margin(3)
  9593. Slider({
  9594. value: this.progressValue,
  9595. min: 0,
  9596. max: this.PROGRESS_MAX_VALUE,
  9597. step: 1,
  9598. style: SliderStyle.OutSet
  9599. })
  9600. .width('600px')
  9601. .blockColor('rgba(255,255,255,1)')
  9602. .trackColor('rgba(255,255,255,0.3)')
  9603. .selectedColor(Color.White)
  9604. .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
  9605. .layoutWeight(1)
  9606. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  9607. .showSteps(false)
  9608. .showTips(true)
  9609. .enabled(this.slideEnable)
  9610. .onChange((value: number, mode: SliderChangeMode) => {
  9611. // if (mode == 2) {
  9612. this.isSeekTo = true;
  9613. this.mDestroyPage = false;
  9614. this.showLoadIng();
  9615. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  9616. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  9617. this.seekTo(seekValue + "");
  9618. // this.setProgress()
  9619. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  9620. this.isSeekTo = false;
  9621. // }
  9622. })
  9623. Text(this.totalTime)
  9624. .fontSize($r('app.float.slider_font_size'))
  9625. .fontColor(Color.White)
  9626. .margin(3)
  9627. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  9628. //播放列表
  9629. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9630. Image($r('app.media.hm_playlist'))
  9631. .width($r('app.float.control_image_width'))
  9632. .fillColor(Color.White)
  9633. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9634. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  9635. height: '95%',
  9636. dragBar: true,
  9637. showClose: true,
  9638. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9639. blurStyle: BlurStyle.Thin,
  9640. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  9641. title: {
  9642. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  9643. + `(${this.songList.length}首)`
  9644. }
  9645. })
  9646. }
  9647. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  9648. .animation({
  9649. duration: 666,
  9650. curve: 'ease-in-out' // 可选动画曲线
  9651. })
  9652. .backgroundColor(Color.Transparent)
  9653. .margin({ right: 20, left: 10 })
  9654. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9655. .onClick(() => {
  9656. this.isShowSheetView = !this.isShowSheetView;
  9657. if (this.isPlayListBgGrass) {
  9658. this.isFrontWhite = true
  9659. } else {
  9660. this.isFrontWhite = false
  9661. }
  9662. this.scrollIndex()
  9663. })
  9664. }
  9665. //x5的竖屏模式需要99%
  9666. .width(this.isPhonePortrait() ? '93.4%'
  9667. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  9668. .height(this.isPhoneLan() ? 25 : 33)
  9669. .animation({
  9670. duration: 666,
  9671. curve: 'ease-in-out' // 可选动画曲线
  9672. })
  9673. }
  9674. isBigScreen() {
  9675. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  9676. return true
  9677. }
  9678. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  9679. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  9680. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  9681. return false
  9682. } else {
  9683. return true
  9684. }
  9685. return false
  9686. }
  9687. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  9688. // 添加控制缩放的状态变量
  9689. @State scaleValueImage: number = 1
  9690. @State scaleValueText: number = 1
  9691. @Builder
  9692. CoverInfo() {
  9693. Column() {
  9694. Stack() {
  9695. Column() {
  9696. //方形封面布局
  9697. if (this.isCoverRectangle) {
  9698. this.RectangleCoverView()
  9699. } else {
  9700. //圆形封面布局
  9701. this.CicleCoverView()
  9702. }
  9703. this.musicNameInfo(false)
  9704. if (this.isPhoneLan()) {
  9705. Text(this.name)
  9706. .fontSize(18)
  9707. .fontWeight(FontWeight.Bold)
  9708. .margin({ top: 13 })
  9709. .textOverflow({ overflow: TextOverflow.Ellipsis })
  9710. .maxLines(1)
  9711. .width('99%')
  9712. .textAlign(TextAlign.Center)
  9713. .fontColor(Color.White)
  9714. }
  9715. }
  9716. .width('100%')
  9717. Column({ space: 8 }) {
  9718. Text(this.name)
  9719. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  9720. .fontWeight(FontWeight.Bold)
  9721. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9722. .maxLines(1)
  9723. .width('85%')
  9724. .textAlign(TextAlign.Center)
  9725. .fontColor(Color.White)
  9726. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  9727. Text(this.artist)
  9728. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  9729. .fontColor(Color.White)
  9730. .fontWeight(FontWeight.Bold)
  9731. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  9732. }
  9733. .justifyContent(FlexAlign.Start)
  9734. .zIndex(1)
  9735. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  9736. }
  9737. .margin({
  9738. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  9739. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  9740. top: this.isCoverOpacity() ? 0 : 20
  9741. })
  9742. if (this.isPhonePortrait() && this.isShowSingleLineLyric) {
  9743. this.SingleLyricView()
  9744. }
  9745. if (this.isPhoneLan()) {
  9746. Column() {
  9747. this.playCenterView()
  9748. // this.playProgressView()
  9749. }
  9750. .position({ left: 28, bottom: 38 })
  9751. } else {
  9752. this.BottomControl()
  9753. }
  9754. }
  9755. .width(CommonConstants.FULL_PERCENT)
  9756. .clip(true)
  9757. }
  9758. //方形封面布局
  9759. @Builder
  9760. RectangleCoverView(){
  9761. Stack({alignContent:Alignment.Center}){
  9762. Image(this.cover)
  9763. .height(this.isHiCar()?(px2vp(this.windowHeight)*0.43):
  9764. this.isCoverOpacity()?(px2vp(this.windowHeight)*0.54):'auto')
  9765. .width(this.isHiCar()||this.isCoverOpacity()?'auto':this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '88%')
  9766. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  9767. .alt($r('app.media.alt'))
  9768. .margin({ right: 8, left: 8, top: 8 })
  9769. .aspectRatio(1)
  9770. .geometryTransition('cover') // 绑定标识符
  9771. .opacity(this.opacityValueImage)
  9772. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  9773. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  9774. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  9775. .clip(true)
  9776. .rotate({
  9777. x: 0,
  9778. y: 0,
  9779. z: 1,
  9780. angle: this.rotateAngle
  9781. })
  9782. .animation({
  9783. duration: 1000, // 与 setInterval 同步
  9784. curve: Curve.Linear,
  9785. iterations: 1
  9786. })
  9787. .shadow({
  9788. radius: 22,
  9789. type: ShadowType.BLUR,
  9790. color: 'on_primary'
  9791. })
  9792. .onClick(() => {
  9793. this.isMusicBGCover = !this.isMusicBGCover
  9794. })
  9795. }
  9796. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  9797. // 设置左下角为缩放中心点
  9798. centerX: '0%',
  9799. centerY: '100%' })
  9800. }
  9801. @Builder
  9802. CicleCoverView() {
  9803. //圆形封面布局
  9804. Stack({alignContent:Alignment.Center}) {
  9805. Image($r('app.media.ic_music_disc'))
  9806. .width(245)
  9807. .height(245)
  9808. .margin({ right: 20, left: 20 ,top:this.isCoverRectangle||this.isLandscape?0:50 })
  9809. .aspectRatio(1)
  9810. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  9811. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  9812. .borderRadius('100%')
  9813. .align(Alignment.Center)
  9814. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  9815. .rotate({
  9816. angle: this.rotateAngle,
  9817. centerX: "50%",
  9818. centerY: "50%",
  9819. })
  9820. .animation({
  9821. duration: 1000, // 改为 1000ms 与 setInterval 同步
  9822. curve: Curve.Linear,
  9823. iterations: 1 // 只执行一次,下一次更新会触发新的动画
  9824. })
  9825. .shadow({
  9826. radius: 22,
  9827. type: ShadowType.BLUR,
  9828. color: 'on_primary'
  9829. })
  9830. Image(this.cover)
  9831. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
  9832. (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 168))
  9833. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  9834. .alt($r('app.media.alt'))
  9835. // .geometryTransition('cover') // 绑定标识符
  9836. .margin({ right: 20, left: 20,
  9837. top:this.isCoverRectangle||this.isLandscape?0:50})
  9838. .aspectRatio(1)
  9839. .opacity(this.opacityValueImage)
  9840. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  9841. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  9842. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  9843. .align(Alignment.Center)//
  9844. .clip(true)
  9845. .shadow({
  9846. radius: 22,
  9847. type: ShadowType.BLUR,
  9848. color: 'on_primary'
  9849. })
  9850. .rotate({
  9851. x: 0,
  9852. y: 0,
  9853. z: 1,
  9854. angle: this.rotateAngle
  9855. })
  9856. .animation({
  9857. duration: 1000, // 与 setInterval 同步
  9858. curve: Curve.Linear,
  9859. iterations: 1
  9860. })
  9861. .onClick(() => {
  9862. this.isMusicBGCover = !this.isMusicBGCover
  9863. })
  9864. // 唱针以左上角为点选择逆时针40度
  9865. Image($r('app.media.ic_music_cover_hand'))
  9866. .height(130)
  9867. .margin({ bottom: 200, top: 0 })
  9868. // .position({ x: this.windowWidth/2, y: 0 })
  9869. .align(Alignment.Top)
  9870. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  9871. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  9872. .visibility(this.isHiCar()||this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  9873. }
  9874. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  9875. // 设置左下角为缩放中心点
  9876. centerX: '0%',
  9877. centerY: '100%' })
  9878. }
  9879. @Builder
  9880. private musicNameInfo(isHidden: boolean) {
  9881. Row(){
  9882. Column({ space: 8 }) {
  9883. Text(this.name)
  9884. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 20)
  9885. .fontWeight(FontWeight.Bold)
  9886. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9887. .maxLines(1)
  9888. .width('99%')
  9889. .textAlign(TextAlign.Start)
  9890. .fontColor(Color.White)
  9891. Text(this.artist + ' ' + this.currentSong?.album)
  9892. .fontSize(this.isCoverOpacity() ? 12 : 15)
  9893. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9894. .fontColor(Color.White)
  9895. .textAlign(TextAlign.Start)
  9896. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  9897. .width('99%')
  9898. .maxLines(1)
  9899. }
  9900. .zIndex(1)
  9901. .layoutWeight(1)
  9902. .margin({ left: 15 })
  9903. Blank()
  9904. Row(){
  9905. Button({type:ButtonType.Circle,stateEffect:true}){
  9906. //添加或取消收藏
  9907. SymbolGlyph(Utility.getIsFav(this.favList,this.currentSong)?
  9908. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'))
  9909. .fontSize(22)
  9910. .fontColor([Color.White])
  9911. .alignSelf(ItemAlign.Center)
  9912. // .width(24)
  9913. .clickEffect({level:ClickEffectLevel.MIDDLE})
  9914. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9915. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9916. .onClick(async () => {
  9917. if(this.currentSong){
  9918. this.doFav(this.currentSong)
  9919. }
  9920. })
  9921. }
  9922. .margin({ left: 8,right:8 })
  9923. .backgroundColor(Color.Transparent)
  9924. .width(45)
  9925. .height(45)
  9926. }
  9927. }
  9928. .width(this.isLandscape?'83%':'90%')
  9929. .scale({ x: this.scaleValueText, y: this.scaleValueText }) // 添加缩放效果
  9930. .margin({ top:this.isCoverRectangle?10: 0 })
  9931. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  9932. }
  9933. @Builder
  9934. private PlayTitle() {
  9935. Row() {
  9936. Row() {
  9937. Image($r('app.media.ic_back_down'))
  9938. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  9939. .hitTestBehavior(HitTestMode.Transparent)
  9940. Text(this.name + ' ' + this.artist)
  9941. .fontColor(Color.White)
  9942. .fontSize($r('app.float.title_font_size'))
  9943. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  9944. .maxLines(1)
  9945. .visibility(Visibility.None)
  9946. .margin({ left: 2, right: 30 })
  9947. }
  9948. .layoutWeight(1)
  9949. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9950. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  9951. .onClick(() => {
  9952. this.setShowPlayFalse()
  9953. })
  9954. Column() {
  9955. AVCastPicker({
  9956. normalColor: Color.White,
  9957. onStateChange: this.onStateVastChange
  9958. })
  9959. .width(24)
  9960. .height(24)
  9961. }
  9962. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  9963. }
  9964. .width(PlayConstants.ROW_WIDTH)
  9965. }
  9966. @Builder
  9967. lyricSettingSheet(isPip: boolean) {
  9968. Scroll() {
  9969. this.lyricSetting(isPip)
  9970. }
  9971. .width('100%')
  9972. .height('100%')
  9973. }
  9974. @Builder
  9975. lyricSetting(isPip: boolean) {
  9976. Column() {
  9977. // 时间调节模块
  9978. if (!isPip) {
  9979. this.BuildTimeControls()
  9980. }
  9981. // 字号控制模块
  9982. this.BuildFontControls(isPip)
  9983. }
  9984. }
  9985. // 歌词时间偏移状态
  9986. @State timeOffset: number = 0.0
  9987. @State currentLyricColor: string = '#FFFFFF'
  9988. @State currentLyricColorPip: string = '#FFFFFF'
  9989. @State currentHighLightLyricColor: string = '#FF4081'
  9990. @State currentHighLightLyricColorPip: string = '#FF4081'
  9991. // 歌词字号状态
  9992. @State currentLyricSize: number = 20
  9993. @State currentLyricSizePip: number = 20
  9994. // 高亮歌词放大倍数
  9995. @State currentHightLyricSize: number = 1.2
  9996. @State currentHightLyricSizePip: number = 1.2
  9997. @State currentLyricLineSpace: number = 10
  9998. @State currentLyricLineSpacePip: number = 10
  9999. @State currentLyricAlignMode: number = 1
  10000. @State currentLyricAlignModePip: number = 1
  10001. @State blurDegree: number = 2
  10002. @State blurDegreePip: number = 2
  10003. @State isShowSelectColor: boolean = false
  10004. @State isShowHLSelectColor: boolean = false
  10005. @State isShowPipBgSelectColor: boolean = false
  10006. @State pipLyWidth: number = 330
  10007. @State pipLyHeight: number = 120
  10008. // 构建颜色选择器
  10009. @Builder
  10010. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  10011. Row({ space: 10 }) {
  10012. HSBColorPicker({
  10013. color: '#FFFFFF',
  10014. radius: 8,
  10015. layout: HSBColorPickerLayout.COLUMN,
  10016. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  10017. '#fa7105'],
  10018. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  10019. this.changeLyricColor(value, isPip, isBGPip)
  10020. })
  10021. .height(250)
  10022. .layoutWeight(1)
  10023. .padding(25)
  10024. }
  10025. .width('66%')
  10026. }
  10027. @State isOpenPip: boolean = false
  10028. @State pipBgIndex: number = 0
  10029. // 构建字号控制器
  10030. @Builder
  10031. BuildFontControls(isPip: boolean) {
  10032. Column() {
  10033. if (isPip) {
  10034. Column() {
  10035. Row() {
  10036. Text('悬浮歌词')
  10037. .margin({ left: 18 })
  10038. .fontSize(15)
  10039. .fontColor(Color.White)
  10040. .fontWeight(480)
  10041. .layoutWeight(1)
  10042. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  10043. .selectedColor(this.themeColor)
  10044. .switchPointColor(Color.White)
  10045. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10046. .margin({ right: 18 })
  10047. .onChange((checked: boolean) => {
  10048. this.isOpenPip = checked;
  10049. if (this.isOpenPip) {
  10050. this.startPip()
  10051. } else {
  10052. this.stopPip()
  10053. }
  10054. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  10055. })
  10056. .width(50)
  10057. .height(30);
  10058. }
  10059. .height(55)
  10060. }
  10061. .backgroundColor(Color.Transparent)
  10062. .borderRadius(15)
  10063. .margin({
  10064. left: 30,
  10065. right: 30,
  10066. top: 0,
  10067. bottom: 20
  10068. })
  10069. .padding(0)
  10070. .border({
  10071. color: Color.White,
  10072. width: 1.8
  10073. })
  10074. }else{
  10075. Column() {
  10076. Row() {
  10077. Text('单行歌词')
  10078. .margin({ left: 18 })
  10079. .fontSize(15)
  10080. .fontColor(Color.White)
  10081. .fontWeight(480)
  10082. .layoutWeight(1)
  10083. Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
  10084. .selectedColor(this.themeColor)
  10085. .switchPointColor(Color.White)
  10086. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10087. .margin({ right: 18 })
  10088. .onChange((checked: boolean) => {
  10089. this.isShowSingleLineLyric = checked;
  10090. PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
  10091. })
  10092. .width(50)
  10093. .height(30);
  10094. }
  10095. .height(55)
  10096. }
  10097. .backgroundColor(Color.Transparent)
  10098. .borderRadius(15)
  10099. .margin({
  10100. left: 30,
  10101. right: 30,
  10102. top: 10,
  10103. bottom: 10
  10104. })
  10105. .padding(0)
  10106. .border({
  10107. color: Color.White,
  10108. width: 1.8
  10109. })
  10110. }
  10111. Row() {
  10112. Text(`歌词居中:`)
  10113. .fontSize(14)
  10114. .fontColor(Color.White)
  10115. .margin({ left: 2 })
  10116. Row() {
  10117. ForEach(['居中', '居左'], (size: string, index: number) => {
  10118. Button(size)
  10119. .width(60)
  10120. .height(28)
  10121. .fontSize(12)
  10122. .fontColor('#FFFFFF')
  10123. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  10124. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  10125. .border({
  10126. color: (!isPip && this.currentLyricAlignMode === index) ||
  10127. (isPip && this.currentLyricAlignModePip === index) ?
  10128. '#007DFF' : '#DDDDDD',
  10129. width: 1.8
  10130. })
  10131. .onClick(() => {
  10132. this.setLyricAlignMode(index, isPip)
  10133. })
  10134. .margin({ left: 10, right: 8 })
  10135. })
  10136. }
  10137. .width('76%')
  10138. Blank()
  10139. }
  10140. .margin({
  10141. top: 10,
  10142. bottom: 10,
  10143. right: 20,
  10144. left: 20
  10145. })
  10146. if (isPip) {
  10147. Row() {
  10148. Text(`悬浮背景:`)
  10149. .fontSize(14)
  10150. .fontColor(Color.White)
  10151. Select([
  10152. { value: CommonConstants.PIP_LYRIC_BG[0] },
  10153. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  10154. .font({ size: 13, weight: FontWeight.Medium })
  10155. .fontColor(Color.White)
  10156. .margin({ left: 10 })
  10157. .selected(this.pipBgIndex)
  10158. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  10159. .onSelect(async (_index: number, text?: string | undefined) => {
  10160. this.pipBgIndex = _index
  10161. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  10162. if (this.pipBgIndex === 0) {
  10163. if (this.cover) {
  10164. this.pipBg = this.cover
  10165. } else {
  10166. this.pipBg = this.imageColor
  10167. }
  10168. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  10169. } else {
  10170. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  10171. }
  10172. })
  10173. Column() {
  10174. }
  10175. .backgroundColor(this.pipBg)
  10176. .margin({ left: 10, right: 10 })
  10177. .borderRadius(20)
  10178. .height(28)
  10179. .width(28)
  10180. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10181. Row() {
  10182. SymbolGlyph($r('sys.symbol.paintbrush'))
  10183. .fontColor([Color.White])
  10184. .effectStrategy(1)
  10185. Text(`选择颜色`)
  10186. .fontSize(13)
  10187. .margin({ left: 10 })
  10188. .fontColor(Color.White)
  10189. }
  10190. }
  10191. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  10192. .backgroundColor(Color.Transparent)
  10193. .border({
  10194. color: '#FFFFFF',
  10195. radius: 20,
  10196. width: 1.8
  10197. })
  10198. .height(36)
  10199. .width(110)
  10200. .onClick(() => {
  10201. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  10202. })
  10203. .bindPopup(this.isShowPipBgSelectColor, {
  10204. builder: this.SelectColor(false, isPip, true),
  10205. placement: Placement.Top,
  10206. mask: { color: '#33000000' },
  10207. enableArrow: false, //是否显示箭头
  10208. showInSubWindow: false,
  10209. onStateChange: (e) => {
  10210. if (!e.isVisible) {
  10211. this.isShowPipBgSelectColor = false
  10212. }
  10213. }
  10214. })
  10215. }
  10216. .width('76%')
  10217. .margin({ bottom: 5, right: 45, left: 20 })
  10218. }
  10219. if (!isPip) {
  10220. Row() {
  10221. Text(`高亮居中:`)
  10222. .fontSize(14)
  10223. .fontColor(Color.White)
  10224. Column() {
  10225. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  10226. .selectedColor(this.themeColor)
  10227. .switchPointColor(Color.White)
  10228. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10229. .onChange((checked: boolean) => {
  10230. this.isHightLightCenter = checked;
  10231. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  10232. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  10233. })
  10234. .width(50)
  10235. .height(30)
  10236. .alignSelf(ItemAlign.Start)
  10237. .margin({ left: 12 })
  10238. Blank()
  10239. }
  10240. .width('76%')
  10241. }
  10242. .margin({
  10243. left: 20,
  10244. right: 15,
  10245. top: 10,
  10246. bottom: 10
  10247. })
  10248. }
  10249. Row() {
  10250. Text(`歌词颜色:`)
  10251. .fontSize(14)
  10252. .fontColor(Color.White)
  10253. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  10254. .fontSize(15)
  10255. .fontColor(Color.White)
  10256. .margin({ left: 12, right: 12 })
  10257. Column() {
  10258. }
  10259. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  10260. .margin({ right: 12 })
  10261. .borderRadius(20)
  10262. .height(28)
  10263. .width(28)
  10264. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10265. Row() {
  10266. SymbolGlyph($r('sys.symbol.paintbrush'))
  10267. .fontColor([Color.White])
  10268. .effectStrategy(1)
  10269. Text(`选择颜色`)
  10270. .fontSize(13)
  10271. .margin({ left: 10 })
  10272. .fontColor(Color.White)
  10273. }
  10274. }
  10275. .backgroundColor(Color.Transparent)
  10276. .border({
  10277. color: '#FFFFFF',
  10278. radius: 20,
  10279. width: 1.8
  10280. })
  10281. .height(36)
  10282. .width(110)
  10283. .onClick(() => {
  10284. this.isShowSelectColor = !this.isShowSelectColor
  10285. })
  10286. .bindPopup(this.isShowSelectColor, {
  10287. builder: this.SelectColor(false, isPip),
  10288. placement: Placement.Top,
  10289. mask: { color: '#33000000' },
  10290. enableArrow: false, //是否显示箭头
  10291. showInSubWindow: false,
  10292. onStateChange: (e) => {
  10293. if (!e.isVisible) {
  10294. this.isShowSelectColor = false
  10295. }
  10296. }
  10297. })
  10298. }
  10299. .width('76%')
  10300. .margin({
  10301. top: 10,
  10302. bottom: 10,
  10303. right: 45,
  10304. left: 20
  10305. })
  10306. Row() {
  10307. Text(`高亮颜色:`)
  10308. .fontSize(14)
  10309. .fontColor(Color.White)
  10310. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  10311. .fontSize(15)
  10312. .fontColor(Color.White)
  10313. .margin({ left: 12, right: 12 })
  10314. Column() {
  10315. }
  10316. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  10317. .margin({ right: 12 })
  10318. .borderRadius(20)
  10319. .height(28)
  10320. .width(28)
  10321. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10322. Row() {
  10323. SymbolGlyph($r('sys.symbol.paintbrush'))
  10324. .fontColor([Color.White])
  10325. .effectStrategy(1)
  10326. Text(`选择颜色`)
  10327. .fontSize(13)
  10328. .margin({ left: 10 })
  10329. .fontColor(Color.White)
  10330. }
  10331. }
  10332. .backgroundColor(Color.Transparent)
  10333. .border({
  10334. color: '#FFFFFF',
  10335. radius: 20,
  10336. width: 1.8
  10337. })
  10338. .height(36)
  10339. .width(110)
  10340. .onClick(() => {
  10341. this.isShowHLSelectColor = !this.isShowHLSelectColor
  10342. })
  10343. .bindPopup(this.isShowHLSelectColor, {
  10344. builder: this.SelectColor(true, isPip),
  10345. placement: Placement.Top,
  10346. mask: { color: '#33000000' },
  10347. enableArrow: false, //是否显示箭头
  10348. showInSubWindow: false,
  10349. onStateChange: (e) => {
  10350. if (!e.isVisible) {
  10351. this.isShowHLSelectColor = false
  10352. }
  10353. }
  10354. })
  10355. }
  10356. .width('76%')
  10357. .margin({
  10358. top: 10,
  10359. bottom: 10,
  10360. right: 45,
  10361. left: 20
  10362. })
  10363. if (isPip) {
  10364. Row() {
  10365. Text(`显示宽度:`)
  10366. .fontSize(14)
  10367. .fontColor(Color.White)
  10368. Slider({
  10369. value: this.pipLyWidth,
  10370. min: 10,
  10371. max: 800,
  10372. step: 1,
  10373. style: SliderStyle.OutSet
  10374. })
  10375. .blockColor(this.themeColor)
  10376. .trackColor($r('app.color.speed_text_color'))
  10377. .selectedColor(Color.White)
  10378. .trackThickness(6)
  10379. .onChange((value: number) => {
  10380. this.pipLyWidth = value
  10381. if (this.pipController) {
  10382. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  10383. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  10384. }
  10385. })
  10386. .width('76%')
  10387. }
  10388. .margin({
  10389. left: 20,
  10390. right: 15,
  10391. top: 5,
  10392. bottom: 5
  10393. })
  10394. Row() {
  10395. Text(`显示高度:`)
  10396. .fontSize(14)
  10397. .fontColor(Color.White)
  10398. Slider({
  10399. value: this.pipLyHeight,
  10400. min: 10,
  10401. max: 1000,
  10402. step: 1,
  10403. style: SliderStyle.OutSet
  10404. })
  10405. .blockColor(this.themeColor)
  10406. .trackColor($r('app.color.speed_text_color'))
  10407. .selectedColor(Color.White)
  10408. .trackThickness(6)
  10409. .onChange((value: number) => {
  10410. this.pipLyHeight = value
  10411. if (this.pipController) {
  10412. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  10413. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  10414. }
  10415. })
  10416. .width('76%')
  10417. }
  10418. .margin({
  10419. left: 20,
  10420. right: 15,
  10421. top: 5,
  10422. bottom: 5
  10423. })
  10424. }
  10425. Row() {
  10426. Text(`歌词字号:`)
  10427. .fontSize(14)
  10428. .fontColor(Color.White)
  10429. Slider({
  10430. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  10431. min: 12,
  10432. max: 30,
  10433. step: 0.1,
  10434. style: SliderStyle.OutSet
  10435. })
  10436. .blockColor(this.themeColor)
  10437. .trackColor($r('app.color.speed_text_color'))
  10438. .selectedColor(Color.White)
  10439. .trackThickness(6)
  10440. .onChange((value: number) => {
  10441. this.setLyricTextSize(value, isPip)
  10442. })
  10443. .width('76%')
  10444. }
  10445. .margin({
  10446. left: 20,
  10447. right: 15,
  10448. top: 5,
  10449. bottom: 5
  10450. })
  10451. Row() {
  10452. Text(`高亮倍数:`)
  10453. .fontSize(14)
  10454. .fontColor(Color.White)
  10455. Slider({
  10456. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  10457. min: 1,
  10458. max: 2,
  10459. step: 0.1,
  10460. style: SliderStyle.OutSet
  10461. })
  10462. .blockColor(this.themeColor)
  10463. .trackColor($r('app.color.speed_text_color'))
  10464. .selectedColor(Color.White)
  10465. .trackThickness(6)
  10466. .onChange((value: number) => {
  10467. this.setHighLyricTextSize(value, isPip)
  10468. })
  10469. .width('76%')
  10470. }
  10471. .margin({
  10472. left: 20,
  10473. right: 15,
  10474. top: 5,
  10475. bottom: 5
  10476. })
  10477. Row() {
  10478. Text(`歌词间隙:`)
  10479. .fontSize(14)
  10480. .fontColor(Color.White)
  10481. Slider({
  10482. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  10483. min: 0,
  10484. max: 100,
  10485. step: 1,
  10486. style: SliderStyle.OutSet
  10487. })
  10488. .blockColor(this.themeColor)
  10489. .trackColor($r('app.color.speed_text_color'))
  10490. .selectedColor(Color.White)
  10491. .trackThickness(6)
  10492. .onChange((value: number) => {
  10493. this.setLyricLineSpace(value, isPip)
  10494. })
  10495. .width('76%')
  10496. }
  10497. .margin({
  10498. left: 20,
  10499. right: 15,
  10500. top: 5,
  10501. bottom: 5
  10502. })
  10503. //取值间隔为100,默认为400,取值越大,字体越粗
  10504. Row() {
  10505. Text(`歌词字重:`)
  10506. .fontSize(14)
  10507. .fontColor(Color.White)
  10508. Slider({
  10509. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  10510. min: 100,
  10511. max: 900,
  10512. step: 100,
  10513. style: SliderStyle.OutSet
  10514. })
  10515. .blockColor(this.themeColor)
  10516. .trackColor($r('app.color.speed_text_color'))
  10517. .selectedColor(Color.White)
  10518. .trackThickness(6)
  10519. .onChange((value: number) => {
  10520. if (isPip) {
  10521. this.lyricTextWeightPip = value
  10522. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  10523. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  10524. } else {
  10525. this.lyricTextWeight = value
  10526. this.lyricController.setTextWeight(this.lyricTextWeight)
  10527. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  10528. }
  10529. })
  10530. .width('76%')
  10531. }
  10532. .margin({
  10533. left: 20,
  10534. right: 15,
  10535. top: 5,
  10536. bottom: 5
  10537. })
  10538. Row() {
  10539. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  10540. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  10541. // this.pushLyricButton($r('app.media.white_search'), 1, '繁体转简体')
  10542. }
  10543. .justifyContent(FlexAlign.Center)
  10544. .margin({ top: 3, bottom: 10 })
  10545. }
  10546. }
  10547. private setBlurDegree(index: number, isPip: boolean) {
  10548. if (isPip) {
  10549. this.blurDegreePip = index
  10550. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  10551. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  10552. } else {
  10553. this.blurDegree = index
  10554. this.lyricController.setBlurDegree(this.blurDegree)
  10555. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  10556. }
  10557. }
  10558. private setLyricAlignMode(index: number, isPip: boolean) {
  10559. if (isPip) {
  10560. this.currentLyricAlignModePip = index
  10561. if (this.currentLyricAlignModePip === 1) {
  10562. this.lyricControllerXF.setAlignMode("left")
  10563. } else {
  10564. this.lyricControllerXF.setAlignMode("center")
  10565. }
  10566. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  10567. } else {
  10568. this.currentLyricAlignMode = index
  10569. if (this.currentLyricAlignMode === 1) {
  10570. this.lyricController.setAlignMode("left")
  10571. } else {
  10572. this.lyricController.setAlignMode("center")
  10573. }
  10574. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  10575. }
  10576. }
  10577. private setLyricTextSize(index: number, isPip: boolean) {
  10578. if (isPip) {
  10579. this.currentLyricSizePip = index
  10580. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  10581. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  10582. } else {
  10583. this.currentLyricSize = index
  10584. this.lyricController.setTextSize(this.currentLyricSize)
  10585. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  10586. }
  10587. }
  10588. private setHighLyricTextSize(scale: number, isPip: boolean) {
  10589. if (isPip) {
  10590. this.currentHightLyricSizePip = scale
  10591. this.lyricControllerXF
  10592. .setHighlightScale(this.currentHightLyricSizePip)
  10593. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  10594. } else {
  10595. this.currentHightLyricSize = scale
  10596. this.lyricController
  10597. .setHighlightScale(this.currentHightLyricSize)
  10598. PreferencesUtil.putSync('HighLyricTextSize', scale)
  10599. }
  10600. }
  10601. private setLyricLineSpace(index: number, isPip: boolean) {
  10602. if (isPip) {
  10603. this.currentLyricLineSpacePip = index
  10604. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  10605. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  10606. } else {
  10607. this.currentLyricLineSpace = index
  10608. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  10609. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  10610. }
  10611. }
  10612. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  10613. LogUtil.info('onecold isBG = ' + isBG)
  10614. if (isBG) { //如果是设置悬浮背景
  10615. this.pipBg = color
  10616. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  10617. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  10618. return
  10619. }
  10620. if (isPip) {
  10621. this.currentLyricColorPip = color
  10622. this.lyricControllerXF
  10623. .setTextColor(this.currentLyricColorPip)
  10624. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  10625. } else {
  10626. this.currentLyricColor = color
  10627. this.lyricController
  10628. .setTextColor(this.currentLyricColor)
  10629. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  10630. }
  10631. }
  10632. private changeLyricHightLightColor(color: string, isPip: boolean) {
  10633. if (isPip) {
  10634. this.currentHighLightLyricColorPip = color
  10635. this.lyricControllerXF
  10636. .setHighlightColor(this.currentHighLightLyricColorPip)
  10637. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  10638. } else {
  10639. this.currentHighLightLyricColor = color
  10640. this.lyricController
  10641. .setHighlightColor(this.currentHighLightLyricColor)
  10642. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  10643. }
  10644. }
  10645. // 构建时间控制器
  10646. @Builder
  10647. BuildTimeControls() {
  10648. Column() {
  10649. // 时间显示
  10650. Text(this.getTimeText())
  10651. .fontSize(18)
  10652. .fontColor(Color.White)
  10653. .margin({ bottom: 10 })
  10654. Row() {
  10655. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  10656. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  10657. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  10658. }
  10659. .justifyContent(FlexAlign.Center)
  10660. }
  10661. .margin({ top: 12, bottom: 8 })
  10662. }
  10663. // 精度按钮组件
  10664. @Builder
  10665. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  10666. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10667. Column() {
  10668. Image(icon)
  10669. .width(28)
  10670. .margin({ bottom: 5 })
  10671. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  10672. Text(label)
  10673. .fontSize(12)
  10674. .fontColor('#FFFFFF')
  10675. }
  10676. }
  10677. .backgroundColor(Color.Transparent)
  10678. .enabled(!this.isButtonDisabled(step))
  10679. .onClick(() => this.handlePrecisionAdjust(step))
  10680. .padding(5)
  10681. .width(66)
  10682. .height(66)
  10683. .margin({ left: 18, right: 18 })
  10684. .border({
  10685. color: '#FFFFFF',
  10686. width: 1.8
  10687. })
  10688. }
  10689. private handlePrecisionAdjust(step: number) {
  10690. if (step === 0) {
  10691. this.timeOffset = 0
  10692. return
  10693. }
  10694. // 精度处理:保留1位小数
  10695. const newOffset = Number((this.timeOffset + step).toFixed(5))
  10696. // 边界保护(±15.0秒)
  10697. if (newOffset < -30.0 || newOffset > 30.0) {
  10698. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  10699. return
  10700. }
  10701. // 状态更新
  10702. this.timeOffset = newOffset
  10703. }
  10704. // 按钮禁用逻辑
  10705. private isButtonDisabled(step: number): boolean {
  10706. const futureOffset = this.timeOffset + step
  10707. return (futureOffset < -30.0) || (futureOffset > 30.0)
  10708. }
  10709. // 时间显示文本升级
  10710. private getTimeText(): string {
  10711. const absValue = Math.abs(this.timeOffset)
  10712. return this.timeOffset === 0
  10713. ? '歌词时间已重置'
  10714. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  10715. }
  10716. // 导入 本地歌词 搜索歌词
  10717. @Builder
  10718. pushLyricButton(icon: Resource, step: number, label: string) {
  10719. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10720. Row() {
  10721. Image(icon)
  10722. .width(14)
  10723. .margin({ left: 13 })
  10724. Text(label)
  10725. .fontSize(12)
  10726. .margin({ left: 6 })
  10727. .fontColor('#FFFFFF')
  10728. }
  10729. }
  10730. .onClick(() => {
  10731. switch (step) {
  10732. case 0:
  10733. this.callFilePickerSelectFileForLyric()
  10734. break;
  10735. case 1:
  10736. //判断有没有设置api
  10737. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  10738. this.isLyricSetting = false
  10739. this.showTipsDialog()
  10740. return
  10741. }
  10742. if (StrUtil.isNotEmpty(this.videoUrl)) {
  10743. ToastUtil.showToast('正在获取')
  10744. this.isLyricSetting = false
  10745. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  10746. this.initLyric(lyricPath, true);
  10747. }
  10748. break;
  10749. }
  10750. })
  10751. .padding(5)
  10752. .width(110)
  10753. .backgroundColor(Color.Transparent)
  10754. .height(40)
  10755. .margin({ left: 6, right: 6 })
  10756. .border({
  10757. color: '#FFFFFF',
  10758. radius: 20,
  10759. width: 1.8
  10760. })
  10761. }
  10762. showVipDialog() {
  10763. DialogHelper.showCustomContentDialog({
  10764. dialogId: 'vip',
  10765. title: "友情提示",
  10766. autoCancel: false, //点击遮障层时,不关闭弹窗
  10767. backCancel: true, //点击返回键,不关闭弹窗
  10768. contentBuilder: () => {
  10769. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  10770. },
  10771. buttons: [],
  10772. })
  10773. }
  10774. //去赞助的自定义内容
  10775. @Builder
  10776. customVipBuilder(content: string) {
  10777. Column() {
  10778. Text(content)
  10779. .fontColor(Color.Gray)
  10780. .fontSize(16)
  10781. .alignSelf(ItemAlign.Start)
  10782. .margin({ bottom: 15 })
  10783. .fontSize(16)
  10784. Row() {
  10785. Button('取消')
  10786. .fontColor(Color.White)
  10787. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  10788. .height(50)
  10789. .layoutWeight(1)
  10790. .stateEffect(true)
  10791. .margin({ right: 6 })
  10792. .onClick(() => {
  10793. DialogHelper.closeDialog('vip'); //关闭弹框
  10794. })
  10795. Button('开通')
  10796. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  10797. .layoutWeight(1)
  10798. .height(50)
  10799. .backgroundColor(this.themeColor)
  10800. .stateEffect(true)
  10801. .margin({ left: 6 })
  10802. .onClick(() => {
  10803. DialogHelper.closeDialog('vip'); //关闭弹框
  10804. this.isShowPlay = false
  10805. this.mType = 1 //跳转到用户中心
  10806. // router.pushUrl({
  10807. // url: 'pages/VipPage'
  10808. // }, router.RouterMode.Single);
  10809. })
  10810. }
  10811. }
  10812. .width("100%")
  10813. .padding(10)
  10814. }
  10815. showTipsDialog() {
  10816. DialogHelper.showCustomContentDialog({
  10817. dialogId: 'tips',
  10818. title: "友情提示",
  10819. autoCancel: false, //点击遮障层时,不关闭弹窗
  10820. backCancel: true, //点击返回键,不关闭弹窗
  10821. contentBuilder: () => {
  10822. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  10823. },
  10824. buttons: [],
  10825. })
  10826. }
  10827. @Builder
  10828. customTipsBuilder(content: string) {
  10829. Column() {
  10830. Text(content)
  10831. .fontColor(Color.Gray)
  10832. .fontSize(16)
  10833. .alignSelf(ItemAlign.Start)
  10834. .margin({ bottom: 15 })
  10835. .fontSize(16)
  10836. Row() {
  10837. Button('取消')
  10838. .fontColor(Color.White)
  10839. .backgroundColor(this.themeColor)
  10840. .height(50)
  10841. .layoutWeight(1)
  10842. .stateEffect(true)
  10843. .margin({ right: 6 })
  10844. .onClick(() => {
  10845. DialogHelper.closeDialog('tips'); //关闭弹框
  10846. })
  10847. Button('跳转')
  10848. .fontColor(Color.White)//
  10849. .layoutWeight(1)
  10850. .height(50)
  10851. .backgroundColor(this.themeColor)
  10852. .stateEffect(true)
  10853. .margin({ left: 6 })
  10854. .onClick(() => {
  10855. DialogHelper.closeDialog('tips'); //关闭弹框
  10856. this.isShowEdit = false
  10857. this.longItemFilePath = ''
  10858. // if(this.isGridMusic&&!this.isShowPlay){
  10859. // this.longItemFilePath== ''
  10860. // }else{
  10861. // this.isShowEdit = false
  10862. // }
  10863. this.isShowMoreView = false;
  10864. this.isShowPlay = false
  10865. this.mType = 4
  10866. // router.pushUrl({
  10867. // url: 'pages/SettingPage'
  10868. // }, router.RouterMode.Single);
  10869. })
  10870. }
  10871. }
  10872. .width("100%")
  10873. .padding(10)
  10874. }
  10875. @Builder
  10876. PlayMoreSheet() {
  10877. Column() {
  10878. this.MoreList()
  10879. }
  10880. .width('100%')
  10881. .height('100%')
  10882. }
  10883. @Builder
  10884. MoreList() {
  10885. Scroll() {
  10886. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  10887. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  10888. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10889. Row() {
  10890. if (more.id === 3&&this.currentSong) {
  10891. Image(more.image)
  10892. .width(24)
  10893. .height(24)
  10894. .margin({ left: 10, right: 10 })
  10895. Text(more.title)
  10896. .fontSize(16)
  10897. .fontColor(Color.White)
  10898. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  10899. height: '99%',
  10900. dragBar: true,
  10901. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  10902. showClose: true,
  10903. blurStyle: BlurStyle.Thin,
  10904. backgroundColor: Color.Transparent,
  10905. title: { title: '歌曲信息' }
  10906. })
  10907. } else if (more.id === 15 && this.currentSong) { //编辑标签
  10908. Image(more.image)
  10909. .width(24)
  10910. .height(24)
  10911. .margin({ left: 10, right: 10 })
  10912. Text(more.title)
  10913. .fontSize(16)
  10914. .fontColor(Color.White)
  10915. } else if (more.id === 5) { //定时关闭
  10916. Image(more.image)
  10917. .width(24)
  10918. .height(24)
  10919. .margin({ left: 10, right: 10 })
  10920. Text(more.title)
  10921. .fontSize(16)
  10922. .fontColor(Color.White)
  10923. .onClick(() => {
  10924. this.doMore(more.id)
  10925. })
  10926. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  10927. height: this.isCoverOpacity() ? '95%' : '95%',
  10928. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  10929. dragBar: true,
  10930. showClose: true,
  10931. title: { title: $r('app.string.time_close') }
  10932. })
  10933. } else if (more.id === 2) { //歌词设置
  10934. Image(more.image)
  10935. .width(24)
  10936. .height(24)
  10937. .margin({ left: 10, right: 10 })
  10938. Text(more.title)
  10939. .fontSize(16)
  10940. .fontColor(Color.White)
  10941. } else if (more.id === 16) { //悬浮歌词设置
  10942. Image(more.image)
  10943. .width(24)
  10944. .height(24)
  10945. .margin({ left: 10, right: 10 })
  10946. Text(more.title)
  10947. .fontSize(16)
  10948. .fontColor(Color.White)
  10949. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  10950. height: '99%',
  10951. dragBar: true,
  10952. preferType: SheetType.CENTER,
  10953. showClose: true,
  10954. blurStyle: BlurStyle.Thin,
  10955. backgroundColor: Color.Transparent,
  10956. title: { title: '悬浮歌词' }
  10957. })
  10958. } else if (more.id === 11) {
  10959. Image(more.image)
  10960. .width(24)
  10961. .height(24)
  10962. .margin({ left: 10, right: 10 })
  10963. Text(more.title)
  10964. .fontSize(16)
  10965. .fontColor(Color.White)
  10966. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  10967. height: this.isCoverOpacity() ? '95%' : '60%',
  10968. dragBar: true,
  10969. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  10970. showClose: true,
  10971. blurStyle: BlurStyle.Thin,
  10972. backgroundColor: Color.Transparent,
  10973. title: { title: '跳过头尾' }
  10974. })
  10975. } else if (more.id === 12) { //投播
  10976. AVCastPicker({
  10977. customPicker: (): void => this.TPImageBuilder(more),
  10978. onStateChange: (state) => {
  10979. if (state == AVCastPickerState.STATE_APPEARING) {
  10980. console.log(' The picker starts showing.');
  10981. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  10982. console.log(' The picker finishes presenting.');
  10983. }
  10984. },
  10985. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  10986. sessionType: 'video'
  10987. })
  10988. .id('AVCastPicker')
  10989. } else {
  10990. Image(more.image)
  10991. .width(24)
  10992. .height(24)
  10993. .fillColor(Color.White)
  10994. .margin({ left: 10, right: 10 })
  10995. .onClick(() => {
  10996. this.doMore(more.id)
  10997. })
  10998. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  10999. .fontSize(16)
  11000. .fontColor(Color.White)
  11001. .onClick(() => {
  11002. this.doMore(more.id)
  11003. })
  11004. Select([//倍速
  11005. { value: '0.25x' },
  11006. { value: '0.5x' },
  11007. { value: '0.75x' },
  11008. { value: '1x' },
  11009. { value: '1.25x' },
  11010. { value: '1.5x' },
  11011. { value: '1.75x' },
  11012. { value: '2x' },
  11013. { value: '3x' }])
  11014. .font({ size: 16, weight: FontWeight.Medium })
  11015. .fontColor($r('sys.color.white'))
  11016. .margin({ left: 25 })
  11017. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  11018. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  11019. .value(Utility.optimizedFormat(this.playSpeed))
  11020. .onSelect(async (_index: number, text?: string | undefined) => {
  11021. let speed = parseFloat(text?.replace('x', '') || '1');
  11022. if (!CommonConstants.video_speed_list.includes(speed)) {
  11023. speed = 1;
  11024. }
  11025. this.playSpeed = speed
  11026. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  11027. })
  11028. Slider({
  11029. value: this.volume,
  11030. min: 0,
  11031. max: 1,
  11032. step: 0.1,
  11033. style: SliderStyle.OutSet
  11034. })
  11035. .margin({ left: 18, right: 8 })
  11036. .blockColor(this.themeColor)
  11037. .trackColor($r('app.color.speed_text_color'))
  11038. .selectedColor(Color.White)
  11039. .trackThickness(9)
  11040. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  11041. .onChange((value: number) => {
  11042. this.volume = value;
  11043. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  11044. PreferencesUtil.putSync('DefalutVolume',this.volume)
  11045. })
  11046. .layoutWeight(1)
  11047. Blank()
  11048. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  11049. .selectedColor(this.themeColor)
  11050. .switchPointColor(Color.White)
  11051. .margin({ right: 15 })
  11052. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11053. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  11054. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11055. if (more.id == 6) {
  11056. this.isMusicMemoryPlay = checked;
  11057. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  11058. if (this.isMusicMemoryPlay) {
  11059. ToastUtil.showToast('记忆播放已开启')
  11060. } else {
  11061. ToastUtil.showToast('记忆播放已关闭')
  11062. }
  11063. }
  11064. })
  11065. .width(48)
  11066. .height(24);
  11067. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  11068. .selectedColor(this.themeColor)
  11069. .switchPointColor(Color.White)
  11070. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11071. .margin({ right: 15 })
  11072. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  11073. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11074. if (more.id == 7) {
  11075. this.isMusicBGCover = checked;
  11076. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  11077. if (this.isMusicBGCover) {
  11078. ToastUtil.showToast('播放背景随音乐封面已开启')
  11079. } else {
  11080. ToastUtil.showToast('播放背景随音乐封面已关闭')
  11081. }
  11082. }
  11083. })
  11084. .width(48)
  11085. .height(24);
  11086. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  11087. .selectedColor(this.themeColor)
  11088. .switchPointColor(Color.White)
  11089. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11090. .margin({ right: 15 })
  11091. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  11092. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11093. if (more.id == 8) {
  11094. this.isSavePlayMode = checked;
  11095. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  11096. if (this.isSavePlayMode) {
  11097. ToastUtil.showToast('保存播放模式已开启')
  11098. } else {
  11099. ToastUtil.showToast('保存播放模式已关闭')
  11100. }
  11101. }
  11102. })
  11103. .width(48)
  11104. .height(24);
  11105. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  11106. .selectedColor(this.themeColor)
  11107. .switchPointColor(Color.White)
  11108. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11109. .margin({ right: 15 })
  11110. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  11111. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11112. if (more.id == 13) {
  11113. this.isCoverRectangle = checked;
  11114. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  11115. if (this.isCoverRectangle) {
  11116. ToastUtil.showToast('封面方形已开启')
  11117. this.animationRoFun()
  11118. } else {
  11119. ToastUtil.showToast('封面圆形已开启')
  11120. this.animationRoFun()
  11121. }
  11122. }
  11123. })
  11124. .width(48)
  11125. .height(24);
  11126. Toggle({ type: ToggleType.Switch, isOn: this.isShowBgLiuGUANG })
  11127. .selectedColor(this.themeColor)
  11128. .switchPointColor(Color.White)
  11129. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11130. .margin({ right: 15 })
  11131. .visibility(more.id == 21 ? Visibility.Visible : Visibility.None)
  11132. .onChange((checked: boolean) => { // 是否开启背景流光效果
  11133. if (more.id == 21) {
  11134. this.isShowBgLiuGUANG = checked;
  11135. PreferencesUtil.putSync('isShowBgLiuGUANG',this.isShowBgLiuGUANG)
  11136. }
  11137. })
  11138. .width(48)
  11139. .height(24);
  11140. }
  11141. }
  11142. .width('100%')
  11143. .height(45)
  11144. .padding(15)
  11145. .backgroundColor(Color.Transparent)
  11146. .borderRadius(12)
  11147. .margin({ bottom: 6 })
  11148. }
  11149. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  11150. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  11151. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  11152. .backgroundColor(Color.Transparent)
  11153. .onClick(() => {
  11154. this.doMore(more.id)
  11155. })
  11156. });
  11157. }
  11158. .width('100%')
  11159. .padding(16)
  11160. }.margin({ bottom: 18 })
  11161. }
  11162. @Builder
  11163. TPImageBuilder(more: MoreItem): void {
  11164. Row() {
  11165. Image($r('app.media.tuoping'))
  11166. .width(22)
  11167. .height(22)
  11168. .margin({ left: 10, right: 10 })
  11169. Text(more.title)
  11170. .fontSize(16)
  11171. .fontColor(Color.White)
  11172. }
  11173. .width('100%')
  11174. .layoutWeight(1)
  11175. .alignItems(VerticalAlign.Center)
  11176. .justifyContent(FlexAlign.Start)
  11177. }
  11178. private moreItems: MoreItem[] = [
  11179. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  11180. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  11181. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  11182. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  11183. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  11184. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  11185. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  11186. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  11187. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  11188. { id:20,image: $r("app.media.a_b"), title: 'AB循环' },
  11189. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  11190. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  11191. { id: 4, image: $r('app.media.share2'), title: '分享' },
  11192. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  11193. // { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  11194. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  11195. { id : 21, image: $r('app.media.kp_music'), title: '开启背景流光' },
  11196. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  11197. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  11198. ];
  11199. @State isShowBgLiuGUANG: boolean = false;
  11200. @State isShowMoreView: boolean = false;
  11201. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  11202. @State isShowTimeCloseMore: boolean = false
  11203. @State isShowDetailMore: boolean = false
  11204. @State isMusicBGCover: boolean = true
  11205. @State isSavePlayMode: boolean = true
  11206. @State isLyricSetting: boolean = false
  11207. @State isJumpSetting: boolean = false
  11208. @State isShowEdit: boolean = false
  11209. @State showPipLyric: boolean = false
  11210. async setRingTone() {
  11211. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  11212. return
  11213. }
  11214. // 确定后的逻辑
  11215. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  11216. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  11217. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  11218. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  11219. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  11220. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  11221. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  11222. , this.videoUrl, this.name).then(res => {
  11223. LogUtil.info('onecold setFlag :' + res);
  11224. });
  11225. }
  11226. doMore(moreId: number) {
  11227. switch (moreId) {
  11228. case 2: //歌词
  11229. this.isLyricSetting = !this.isLyricSetting;
  11230. this.isShowMoreView = false
  11231. break;
  11232. case 3: //详情
  11233. this.isShowDetailMore = !this.isShowDetailMore;
  11234. break;
  11235. case 4: //分享
  11236. if (this.currentSong !== undefined) {
  11237. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  11238. }
  11239. this.isShowMoreView = false
  11240. break;
  11241. case 5: //定时关闭
  11242. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  11243. break;
  11244. case 10: //设为铃声
  11245. this.setRingTone()
  11246. this.isShowMoreView = false
  11247. break;
  11248. case 11: //跳过头尾
  11249. this.isJumpSetting = !this.isJumpSetting;
  11250. break;
  11251. case 13: //倍速
  11252. break;
  11253. case 14: //搜索封面
  11254. if (this.currentSong !== undefined) {
  11255. this.doSearchCover(this.currentSong)
  11256. }
  11257. this.isShowMoreView = false
  11258. break;
  11259. case 15: //编辑标签
  11260. this.initEditFields(this.currentSong)
  11261. this.tempLyricContent = this.lyricContent
  11262. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  11263. this.lyricConStr = this.tempLyricContent
  11264. }
  11265. this.isShowEdit = !this.isShowEdit;
  11266. break;
  11267. case 16: //悬浮歌词
  11268. this.showPipLyric = !this.showPipLyric;
  11269. break;
  11270. case 17: //横屏模式
  11271. if (this.isLandscape) {
  11272. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  11273. } else {
  11274. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  11275. }
  11276. this.isShowMoreView = false
  11277. break;
  11278. case 20://AB循环
  11279. this.isABSheet = !this.isABSheet
  11280. break;
  11281. }
  11282. }
  11283. //AB循环
  11284. @State isOpenAB:boolean = false
  11285. @State jumpATime:number = 0
  11286. @State jumpBTime:number = 0
  11287. @State isABSheet:boolean = false
  11288. @Builder
  11289. ABLoopSheet() {
  11290. ABLoopComptent({
  11291. jumpATime:this.jumpATime,
  11292. jumpBTime:this.jumpBTime,
  11293. onClickAItem: async ()=>{
  11294. if(this.mIjkMediaPlayer){
  11295. this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
  11296. }
  11297. },
  11298. onClickBItem: async ()=>{
  11299. if(this.mIjkMediaPlayer){
  11300. this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
  11301. if(this.jumpBTime<=this.jumpATime){
  11302. ToastUtil.showToast('设置B点时间不能小于A点时间')
  11303. this.jumpBTime = 0
  11304. }
  11305. }
  11306. },
  11307. onCancleButtonClick: async ()=>{
  11308. this.isOpenAB = false
  11309. this.isABSheet = false
  11310. },
  11311. onStartButtonClick: async ()=>{
  11312. if(this.jumpBTime<=this.jumpATime||this.stringForTime(this.jumpATime)==this.stringForTime(this.jumpBTime)){
  11313. ToastUtil.showToast('设置B点时间不能小于或等于A点时间')
  11314. return
  11315. }
  11316. this.isABSheet = false
  11317. this.startABLoop()
  11318. },
  11319. })
  11320. }
  11321. //开始AB循环
  11322. startABLoop(){
  11323. if(this.mIjkMediaPlayer){
  11324. this.seekTo(this.jumpATime+'')
  11325. this.isOpenAB = true
  11326. }
  11327. }
  11328. /**
  11329. * 切换横竖屏
  11330. *
  11331. */
  11332. setOrientation(orientation: number) {
  11333. this.windowClass.setPreferredOrientation(orientation).then(() => {
  11334. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  11335. }).catch((err: BusinessError) => {
  11336. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  11337. });
  11338. }
  11339. /**
  11340. * 画中画功能(悬浮歌词功能)
  11341. *
  11342. */
  11343. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  11344. pipController?: PiPWindow.PiPController;
  11345. navigationId: string = '';
  11346. @State curState: string = '';
  11347. @State curError: ResourceStr = '';
  11348. @State pipBg: string = '#E8E8E8'
  11349. @State buttonAction: string = '';
  11350. //开启画中画功能
  11351. async startPip() {
  11352. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  11353. if (!this.pipController) {
  11354. await this.createPipController();
  11355. }
  11356. if (!this.pipController) {
  11357. Logger.info(`[${TAG}] pipController create error`);
  11358. return;
  11359. }
  11360. await this.pipController.startPiP();
  11361. }
  11362. async stopPip() {
  11363. if (!this.pipController) {
  11364. Logger.info(`[${TAG}] pipController is not exist`);
  11365. return;
  11366. }
  11367. this.isOpenPip = false
  11368. await this.pipController.stopPiP();
  11369. }
  11370. async createPipController() {
  11371. this.pipController = await PiPWindow.create({
  11372. context: getContext(this),
  11373. componentController: this.xcomponentController,
  11374. navigationId: this.navigationId,
  11375. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  11376. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  11377. customUIController: this.nodeController,
  11378. });
  11379. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  11380. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  11381. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  11382. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  11383. this.onStateChange(state, reason);
  11384. });
  11385. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  11386. this.onActionEvent(event, status);
  11387. });
  11388. }
  11389. destroyPipController() {
  11390. if (!this.pipController) {
  11391. return;
  11392. }
  11393. this.pipController.off('stateChange');
  11394. this.pipController.off('controlPanelActionEvent');
  11395. this.pipController = undefined;
  11396. }
  11397. onStateChange(state: PiPWindow.PiPState, reason: string) {
  11398. switch (state) {
  11399. case PiPWindow.PiPState.ABOUT_TO_START:
  11400. this.curState = 'ABOUT_TO_START';
  11401. this.curError = $r('app.string.current_error_hint');
  11402. break;
  11403. case PiPWindow.PiPState.STARTED:
  11404. this.curState = 'STARTED';
  11405. this.curError = $r('app.string.current_error_hint');
  11406. break;
  11407. case PiPWindow.PiPState.ABOUT_TO_STOP:
  11408. this.curState = 'ABOUT_TO_STOP';
  11409. this.curError = $r('app.string.current_error_hint');
  11410. break;
  11411. case PiPWindow.PiPState.STOPPED:
  11412. this.curState = 'STOPPED';
  11413. this.curError = $r('app.string.current_error_hint');
  11414. this.stopPip()
  11415. this.destroyPipController()
  11416. break;
  11417. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  11418. this.curState = 'ABOUT_TO_RESTORE';
  11419. this.curError = $r('app.string.current_error_hint');
  11420. break;
  11421. case PiPWindow.PiPState.ERROR:
  11422. this.curState = 'ERROR';
  11423. this.curError = reason;
  11424. break;
  11425. default:
  11426. break;
  11427. }
  11428. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  11429. }
  11430. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  11431. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  11432. switch (event) {
  11433. case 'playbackStateChanged':
  11434. if (status === 0) {
  11435. this.pause();
  11436. } else {
  11437. console.info('onecold startPlayOrResumePlay 9869')
  11438. this.startPlayOrResumePlay();
  11439. }
  11440. break;
  11441. case 'nextVideo':
  11442. // 切换到下一个视频
  11443. this.playNext().catch(() => {
  11444. Logger.error('heanup onActionEvent playNext', `播放下一首失败`);
  11445. });
  11446. break;
  11447. case 'previousVideo':
  11448. // 切换到上一个视频
  11449. this.playPrevious().catch(() => {
  11450. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败`);
  11451. });
  11452. break;
  11453. case 'previousVideo':
  11454. // 切换到上一个视频
  11455. this.playPrevious().catch(() => {
  11456. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败:`);
  11457. });
  11458. break;
  11459. default:
  11460. }
  11461. this.buttonAction = event + `-status:${status}`;
  11462. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  11463. }
  11464. /**
  11465. * 画中画功能(悬浮歌词功能)结束
  11466. *
  11467. */
  11468. async doSearchCover(item: VideoItem,title?:string,artist?:string): Promise<string> {
  11469. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  11470. this.isShowMoreView = false;
  11471. this.showTipsDialog();
  11472. return ''; // Return empty string when no API is configured
  11473. }
  11474. if (!item) {
  11475. return ''; // Return empty string if item is undefined
  11476. }
  11477. const titleS = title||item?.name || '';
  11478. const artistS = artist||item?.artist || ''; // Use empty string if artist is missing
  11479. return this.searchCover(item, titleS, artistS); // Await is not needed here as we return the promise directly
  11480. }
  11481. /**
  11482. *api搜索封面
  11483. *item,根据title和artist
  11484. */
  11485. searchCover(item: VideoItem, title: string, artist: string): Promise<string> {
  11486. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  11487. LogUtil.debug("onecold res =" + res);
  11488. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  11489. if (item.filePath == this.currentSong?.filePath) {
  11490. this.cover = res;
  11491. if (this.currentSong) {
  11492. this.currentSong.pixelMapPath = res;
  11493. }
  11494. }
  11495. // Update pixel map path but always return res regardless of success
  11496. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  11497. if (success) {
  11498. this.doUpdateData();
  11499. console.log("onecold 更新音乐封面成功,数据库已同步");
  11500. } else {
  11501. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  11502. }
  11503. // Note: We don't resolve/reject here because we already returned res
  11504. });
  11505. LogUtil.debug("onecold this.cover =" + this.cover);
  11506. }
  11507. return res; // Always return res regardless of updatePixelMapPath result
  11508. });
  11509. }
  11510. @State jumpTopTime: number = 0
  11511. @State jumpEndTime: number = 0
  11512. @State isOpenJump: boolean = false
  11513. @Builder
  11514. JumpTopEndSheet() {
  11515. Scroll() {
  11516. Column() {
  11517. Column() {
  11518. Text('仅对本播放列表有效')
  11519. .fontSize(16)
  11520. .fontColor($r('app.color.text_color'))
  11521. // 跳过头尾
  11522. Column() {
  11523. Row() {
  11524. Text('跳过片头:')
  11525. .fontSize(16)
  11526. .fontColor($r('app.color.text_color'))
  11527. Text(this.jumpTopTime + 's')
  11528. .fontSize(16)
  11529. .fontColor($r('app.color.text_color'))
  11530. }
  11531. .margin({ bottom: 5 })
  11532. Row() {
  11533. Slider({
  11534. value: this.jumpTopTime,
  11535. min: 0,
  11536. max: 120,
  11537. step: 1,
  11538. style: SliderStyle.OutSet
  11539. })
  11540. .blockColor(this.themeColor)
  11541. .trackColor($r('app.color.speed_text_color'))
  11542. .selectedColor(Color.White)
  11543. .trackThickness(8)
  11544. .onChange((value: number) => {
  11545. this.jumpTopTime = value;
  11546. })
  11547. .width('85%')
  11548. }
  11549. .alignItems(VerticalAlign.Top)
  11550. }
  11551. .margin({ top: 10, bottom: 10 })
  11552. // 跳过头尾
  11553. Column() {
  11554. Row() {
  11555. Text('跳过片尾:')
  11556. .fontSize(16)
  11557. .fontColor($r('app.color.text_color'))
  11558. Text(this.jumpEndTime + 's')
  11559. .fontSize(16)
  11560. .fontColor($r('app.color.text_color'))
  11561. }
  11562. .margin({ bottom: 5 })
  11563. Row() {
  11564. Slider({
  11565. value: this.jumpEndTime,
  11566. min: 0,
  11567. max: 120,
  11568. step: 1,
  11569. style: SliderStyle.OutSet
  11570. })
  11571. .blockColor(this.themeColor)
  11572. .trackColor($r('app.color.speed_text_color'))
  11573. .selectedColor(Color.White)
  11574. .trackThickness(8)
  11575. .onChange((value: number) => {
  11576. this.jumpEndTime = value;
  11577. })
  11578. .width('85%')
  11579. }
  11580. .alignItems(VerticalAlign.Top)
  11581. }
  11582. .margin({ top: 10, bottom: 10 })
  11583. Row() {
  11584. Button('保存设置')
  11585. .fontColor(Color.White)
  11586. .layoutWeight(1)
  11587. .height(40)
  11588. .width(80)
  11589. .backgroundColor(this.themeColor)
  11590. .stateEffect(true)
  11591. .margin({ left: 0, bottom: 20 })
  11592. .onClick(async () => {
  11593. if (!Utility.isNoble()) {
  11594. this.isJumpSetting = false
  11595. this.isShowMoreView = false
  11596. this.showVipDialog()
  11597. return
  11598. }
  11599. if (this.currentSong === undefined) {
  11600. return
  11601. }
  11602. if (this.modeType === 0) {
  11603. let parentPath = FileUtil.getParentPath(this.videoUrl)
  11604. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  11605. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  11606. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  11607. } else if (this.modeType === 1) { //媒体库
  11608. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  11609. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  11610. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  11611. } else if (this.modeType === 2) { //艺术家
  11612. if (this.currentSong?.artist) {
  11613. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  11614. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  11615. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  11616. }
  11617. } else if (this.modeType === 3) { //专辑
  11618. if (this.currentSong?.album) {
  11619. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  11620. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  11621. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  11622. }
  11623. }
  11624. ToastUtil.showShort("保存成功")
  11625. this.isJumpSetting = false
  11626. })
  11627. }
  11628. .margin({
  11629. left: 38,
  11630. right: 38,
  11631. top: 10,
  11632. bottom: 10
  11633. })
  11634. .width(120)
  11635. .height(50)
  11636. }
  11637. }
  11638. }
  11639. .width('100%')
  11640. .height('100%')
  11641. }
  11642. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  11643. private onStateVastChange(state: AVCastPickerState) {
  11644. if (state == AVCastPickerState.STATE_APPEARING) {
  11645. console.log('The picker starts showing.');
  11646. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  11647. console.log('The picker finishes presenting.');
  11648. }
  11649. }
  11650. private showSelectLyric() {
  11651. DialogHelper.showActionSheetDialog({
  11652. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  11653. // sheets: ["本地歌词", "搜索歌词"],
  11654. sheets: [
  11655. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  11656. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  11657. ],
  11658. maskColor: Color.Transparent,
  11659. backgroundColor: $r('app.color.bg_card'),
  11660. transition: AnimationHelper.transitionInDown(666),
  11661. onAction: (index) => {
  11662. switch (index) {
  11663. case 0:
  11664. this.callFilePickerSelectFileForLyric()
  11665. break;
  11666. case 1:
  11667. if (StrUtil.isNotEmpty(this.videoUrl)) {
  11668. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  11669. this.initLyric(lyricPath);
  11670. }
  11671. break;
  11672. }
  11673. }
  11674. })
  11675. }
  11676. // 拉起picker选择文件管理器
  11677. async callFilePickerSelectFileForLyric(): Promise<void> {
  11678. try {
  11679. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  11680. DocumentSelectOptions.maxSelectNumber = 1
  11681. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  11682. let documentPicker = new picker.DocumentViewPicker();
  11683. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  11684. Logger.info(TAG,
  11685. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  11686. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  11687. this.saveVideoDatasLyric(DocumentSelectResult)
  11688. }
  11689. }).catch((err: BusinessError) => {
  11690. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  11691. });
  11692. } catch (err) {
  11693. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  11694. }
  11695. }
  11696. async saveVideoDatasLyric(uris: string[]) {
  11697. if (ArrayUtil.isEmpty(uris)) {
  11698. return
  11699. }
  11700. let newUris: string[] = [];
  11701. for (let i = 0; i < uris.length; i++) {
  11702. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  11703. Logger.info(TAG, 'filePath uri: ' + filePath);
  11704. newUris.push(filePath)
  11705. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  11706. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  11707. fileIo.copyFileSync(file.fd, file2.fd)
  11708. fileIo.closeSync(file);
  11709. fileIo.closeSync(file2);
  11710. this.initLyric(filePath,false,false,true)
  11711. }
  11712. }
  11713. private initDelayPlay(context: object) {
  11714. this.mContext = context;
  11715. }
  11716. startPipLyric() {
  11717. if (this.pipController) {
  11718. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  11719. PiPWindow.PiPControlStatus.PLAY);
  11720. }
  11721. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  11722. if (this.isOpenPip) {
  11723. this.startPip()
  11724. } else {
  11725. this.stopPip()
  11726. }
  11727. }
  11728. //startOffset 从cue分轨时间开始播
  11729. private startPlayOrResumePlay(startOffset?:number) {
  11730. //针对dsf文件高采样率,统一转wav播放
  11731. const sampleRate = this.currentSong?.sampleRate||0
  11732. if(this.videoUrl.toLowerCase().endsWith('.dsf')&&sampleRate>=441000){
  11733. console.info('onecold 采样率 ='+sampleRate)
  11734. let newDsfPath = this.context.filesDir + '/'+FileUtil.getFileName(this.videoUrl)+'.wav'
  11735. console.info('onecold newDsfPath ='+newDsfPath)
  11736. if(!FileUtil.accessSync(newDsfPath)){
  11737. const task = new taskpool.Task(convertDsfToWav,this.videoUrl,newDsfPath);
  11738. taskpool.execute(task, taskpool.Priority.HIGH).then((data)=>{
  11739. this.videoUrl = newDsfPath
  11740. this.startPlay(startOffset)
  11741. }).catch((e:object)=>{
  11742. console.info("task1 catch e: " + e);
  11743. })
  11744. }else{
  11745. this.videoUrl = newDsfPath
  11746. this.startPlay(startOffset)
  11747. }
  11748. }else{
  11749. this.startPlay(startOffset)
  11750. }
  11751. // 提前缓存下一首
  11752. void this.preloadNextSongInternal();
  11753. }
  11754. startPlay(startOffset?:number) {
  11755. this.startPipLyric()
  11756. this.mDestroyPage = false;
  11757. this.animationState = AnimationStatus.Running
  11758. LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  11759. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  11760. this.stopProgressTask();
  11761. this.startProgressTask();
  11762. // 判断是否是HTTP或在线网盘视频,显示加载进度
  11763. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  11764. this.isPlayerLoading = true;
  11765. }
  11766. this.play(this.videoUrl.toString(),startOffset);
  11767. }
  11768. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  11769. this.mIjkMediaPlayer.start();
  11770. this.setProgress()
  11771. this.CONTROL_PlayStatus = PlayStatus.PLAY
  11772. }
  11773. this.setIsPlaying(true)
  11774. this.updateSessionPlayState(true)
  11775. this.watchStatus();
  11776. this.updateLastPlayTimeStr(this.videoUrl)
  11777. }
  11778. updateLastPlayTimeStr(filePath: string) {
  11779. // 检查是否为网络音频(WebDAV),如果是则不更新本地数据库
  11780. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  11781. Logger.info(`heanup 检测到网络音频播放,跳过数据库更新: ${filePath}`)
  11782. return;
  11783. }
  11784. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  11785. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  11786. if (success) {
  11787. this.getHistoryList(false)
  11788. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  11789. } else {
  11790. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  11791. }
  11792. });
  11793. }
  11794. private completionNum(num: number): string | number {
  11795. if (num < 10) {
  11796. return '0' + num;
  11797. } else {
  11798. return num;
  11799. }
  11800. }
  11801. private stringForTime(timeMs: number): string {
  11802. let totalSeconds: number | string = (timeMs / 1000);
  11803. let newSeconds: number | string = totalSeconds % 60;
  11804. let minutes: number | string = (totalSeconds / 60) % 60;
  11805. let hours: number | string = totalSeconds / 3600;
  11806. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  11807. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  11808. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  11809. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  11810. if (this.isCurrentTime) {
  11811. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  11812. this.oldSeconds = newSeconds
  11813. } else {
  11814. newSeconds = this.oldSeconds
  11815. }
  11816. }
  11817. newSeconds = this.completionNum(newSeconds);
  11818. if (hours > 0) {
  11819. return hours + ":" + minutes + ":" + newSeconds;
  11820. } else {
  11821. return minutes + ":" + newSeconds;
  11822. }
  11823. }
  11824. private setProgress() {
  11825. let position = this.mIjkMediaPlayer.getCurrentPosition();
  11826. let duration = this.mIjkMediaPlayer.getDuration();
  11827. if (duration <= 0 && this.duration > 0) {
  11828. duration = this.duration;
  11829. }
  11830. let pos = 0;
  11831. if (duration > 0) {
  11832. this.slideEnable = true;
  11833. let curPercent = position / duration;
  11834. pos = curPercent * 100;
  11835. if (pos > this.PROGRESS_MAX_VALUE) {
  11836. this.progressValue = this.PROGRESS_MAX_VALUE
  11837. } else {
  11838. this.progressValue = pos;
  11839. }
  11840. }
  11841. // LogUtils.getInstance()
  11842. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  11843. this.totalTime = this.stringForTime(duration);
  11844. if (position > duration) {
  11845. position = duration;
  11846. }
  11847. this.isCurrentTime = true;
  11848. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  11849. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000)
  11850. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000)
  11851. this.currentTime = this.stringForTime(position);
  11852. this.isCurrentTime = false
  11853. if (this.mIjkMediaPlayer.isPlaying()) {
  11854. this.randomColor =
  11855. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  11856. //如果是开启AB循环
  11857. if(this.isOpenAB){
  11858. if(position >=this.jumpBTime){
  11859. this.seekTo(this.jumpATime+'')
  11860. return
  11861. }
  11862. }
  11863. // 判断是否播放到结束时间
  11864. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  11865. if (position >= duration - this.jumpEndTime * 1000) {
  11866. if(this.playType == 1){//跳过尾部如果是单曲循环就选择单曲循环
  11867. this.CONTROL_PlayStatus = PlayStatus.INIT
  11868. this.startPlayOrResumePlay();
  11869. }else if (this.playType == 2) { //2:正常播放,单曲播完
  11870. this.showRePlay();
  11871. this.currentTime = this.stringForTime(this.mIjkMediaPlayer.getDuration());
  11872. this.progressValue = this.PROGRESS_MAX_VALUE;
  11873. this.slideEnable = false;
  11874. this.stop();
  11875. // ToastUtil.showToast('开始重新播放')
  11876. }else{
  11877. this.playNext().catch(() => {
  11878. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  11879. });
  11880. }
  11881. }
  11882. }
  11883. } else {
  11884. this.randomColor = 'rbg(0,0,0)'
  11885. }
  11886. }
  11887. private startProgressTask() {
  11888. let that = this;
  11889. this.updateProgressTimer = setInterval(() => {
  11890. //LogUtils.getInstance().LOGI("startProgressTask");
  11891. if (!that.mDestroyPage) {
  11892. that.setProgress();
  11893. }
  11894. }, 300);
  11895. }
  11896. private stopProgressTask() {
  11897. LogUtils.getInstance().LOGI("stopProgressTask");
  11898. clearInterval(this.updateProgressTimer);
  11899. }
  11900. private showLoadIng() {
  11901. this.loadingVisible = Visibility.Visible;
  11902. this.replayVisible = Visibility.None;
  11903. }
  11904. private hideLoadIng() {
  11905. this.loadingVisible = Visibility.None;
  11906. this.replayVisible = Visibility.None;
  11907. }
  11908. private showRePlay() {
  11909. this.loadingVisible = Visibility.None;
  11910. this.replayVisible = Visibility.Visible;
  11911. }
  11912. private async play(url: string,startOffset?:number) {
  11913. this.isShowBgLiuGUANG = PreferencesUtil.getBooleanSync('isShowBgLiuGUANG', false)
  11914. console.info('onecold this.url 1= '+url)
  11915. if(!url.toLowerCase().startsWith('http')){
  11916. let hasPermission = await PermissionUtil.activatePermission(url)
  11917. console.info('onecold this.hasPermission 1= '+hasPermission)
  11918. if(!url.includes(this.packName)){
  11919. const file = fs.openSync(url)
  11920. this.videoUrl = file.path
  11921. url= this.videoUrl
  11922. }
  11923. console.info('onecold this.hasPermission 1= '+hasPermission)
  11924. console.info('onecold this.videoUrl 1= '+this.videoUrl)
  11925. }
  11926. let that = this;
  11927. that.showLoadIng();
  11928. this.isOpenAB = false
  11929. //设置XComponent回调的context
  11930. if (!!this.mContext) {
  11931. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  11932. }
  11933. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  11934. this.mIjkMediaPlayer.reset();
  11935. }
  11936. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  11937. //设置debug模式
  11938. this.mIjkMediaPlayer.setDebug(false);
  11939. //初始化配置
  11940. this.mIjkMediaPlayer.native_setup();
  11941. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  11942. if(this.volumeSmall){
  11943. if(this.videoUrl.toLowerCase().endsWith('.dsf')){
  11944. this.mIjkMediaPlayer.setVolume('1', '1');
  11945. }else{
  11946. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  11947. }
  11948. }else{
  11949. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  11950. }
  11951. //设置视频源
  11952. Logger.info(TAG, `IjkPlayer setDataSource url=${url}`);
  11953. this.mIjkMediaPlayer.setDataSource(url);
  11954. // 构建规范的HTTP请求头(统一一次性设置,避免未带认证提前发起连接)
  11955. const headers = new Map<string, string>();
  11956. headers.set("User-Agent", "TTMusic-WebDAV/1.0");
  11957. headers.set("Accept", "*/*");
  11958. if (this.currentSong&&StrUtil.isEmpty(this.currentSong.pixelMapPath)
  11959. &&PreferencesUtil.getStringSync('COVER_API', '') != '') {
  11960. //如果封面为空,则搜索封面
  11961. this.searchCover(this.currentSong, this.currentSong.name, this.currentSong.artist||'')
  11962. }
  11963. // 如果是WebDAV网络音频,使用webdav_account_id获取认证信息(等待完成后再设置一次性头部)
  11964. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !isBaiduType(this.currentSong.type)) {
  11965. Logger.info(`heanup WebDAV歌曲认证 - 歌曲名: ${this.currentSong.name}, webdav_account_id: ${this.currentSong.webdav_account_id || '未设置'}`);
  11966. if (this.currentSong.webdav_account_id) {
  11967. try {
  11968. const webdavManager = RemoteDriveManager.getInstance();
  11969. const webDavHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  11970. if (webDavHeaders && webDavHeaders.size > 0) {
  11971. webDavHeaders.forEach((value, key) => headers.set(key, value));
  11972. Logger.info(`heanup 成功通过webdav_account_id获取并合并WebDAV认证头`);
  11973. } else {
  11974. Logger.warn(`heanup 通过webdav_account_id获取认证头失败,播放可能无法继续`);
  11975. }
  11976. } catch (error) {
  11977. const err = error as Error;
  11978. Logger.error(`heanup 获取WebDAV认证头时出错: ${err.message}`);
  11979. }
  11980. } else {
  11981. Logger.error(`heanup WebDAV歌曲 "${this.currentSong.name}" 缺少webdav_account_id,无法进行认证`);
  11982. }
  11983. }
  11984. // 统一设置带认证的请求头
  11985. // 百度类型也需要特殊请求头
  11986. if (this.currentSong && isBaiduType(this.currentSong.type)) {
  11987. try {
  11988. const webdavManager = RemoteDriveManager.getInstance();
  11989. const baiduHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  11990. baiduHeaders.forEach((value, key) => headers.set(key, value));
  11991. const headerSnapshot: Record<string, string> = {};
  11992. headers.forEach((value, key) => headerSnapshot[key] = value);
  11993. Logger.info(TAG, `Baidu播放请求头: ${JSON.stringify(headerSnapshot)}`);
  11994. } catch (error) {
  11995. Logger.error(`heanup 构建百度请求头失败: ${(error as Error).message}`);
  11996. }
  11997. }
  11998. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  11999. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && !isBaiduType(this.currentSong.type)) {
  12000. console.log(`heanup 为WebDAV播放设置IjkPlayer选项`);
  12001. // 网络超时设置(单位:微秒,文档显示应该是字符串格式)
  12002. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "30000000"); // 30秒
  12003. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "30000000"); // 连接超时30秒
  12004. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "listen_timeout", "30000000"); // 监听超时30秒
  12005. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "30000000"); // DNS缓存超时30秒
  12006. // 缓冲和播放优化设置
  12007. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "1024000"); // 增大缓冲区
  12008. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "50"); // 减少最小帧数
  12009. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1"); // 预加载启动
  12010. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0"); // 无缓冲播放
  12011. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "30000"); // 最大缓存30秒
  12012. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1"); // 无限制收流
  12013. // 网络相关设置
  12014. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1"); // 启用HTTP重定向
  12015. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", "TTMusic-WebDAV/1.0"); // 用户代理
  12016. // 重连设置
  12017. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "reconnect", "3"); // 重连3次
  12018. console.log(`heanup WebDAV IjkPlayer选项设置完成`);
  12019. } else if (this.currentSong && isBaiduType(this.currentSong.type)) {
  12020. console.log(`heanup 为百度网盘播放设置IjkPlayer选项`);
  12021. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "15000000");
  12022. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "15000000");
  12023. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1");
  12024. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "1");
  12025. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "2097152");
  12026. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "25");
  12027. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", BaiduConstants.USER_AGENT);
  12028. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", "3");
  12029. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http-detect-range-support", "1");
  12030. console.log(`heanup 百度网盘 IjkPlayer 选项设置完成`);
  12031. }
  12032. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  12033. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  12034. // }
  12035. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  12036. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  12037. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  12038. let bufferSize = 50 * 1024 ; // 默认缓冲区大小为1MB
  12039. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  12040. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  12041. //停止预读的最小帧数
  12042. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  12043. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  12044. // 设置其他缓冲相关选项
  12045. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  12046. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  12047. //启动预加载
  12048. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
  12049. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  12050. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  12051. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  12052. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  12053. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  12054. // 因此需要播放器丢包,才不会累积延时
  12055. // 这个和第三个参数packet-buffering无关。
  12056. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  12057. // 无限制收流
  12058. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  12059. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  12060. // 屏幕常亮
  12061. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  12062. // 开启hls起播优化 默认是关闭的
  12063. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "fetch_first", "on");
  12064. // 设置超时
  12065. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  12066. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  12067. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  12068. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  12069. // 变速播放
  12070. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  12071. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  12072. let Speed = this.mIjkMediaPlayer.getSpeed()
  12073. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  12074. //是否开启循环播放
  12075. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  12076. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = {
  12077. onVideoSizeChanged: (width: number, height: number, sar_num: number, sar_den: number) => {
  12078. if (height === 0) {
  12079. return;
  12080. }
  12081. const va = width / height;
  12082. const vpa = that.videoParentAspectRatio;
  12083. if (vpa > va) {
  12084. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  12085. } else {
  12086. that.videoWidth = '100%';
  12087. }
  12088. if (width && height) {
  12089. that.videoAspectRatio = width / height;
  12090. }
  12091. LogUtils.getInstance()
  12092. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  12093. that.hideLoadIng();
  12094. }
  12095. }
  12096. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  12097. let mOnPreparedListener: OnPreparedListener = {
  12098. onPrepared: async () => {
  12099. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  12100. // 隐藏加载进度
  12101. this.isPlayerLoading = false;
  12102. try {
  12103. //保存碰一碰分享的当前的歌曲
  12104. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  12105. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  12106. await this.initLyric(lyricPath);
  12107. const applyDuration = (durationMs: number): void => {
  12108. if (durationMs <= 0) {
  12109. return;
  12110. }
  12111. this.duration = durationMs;
  12112. this.durationTime = Math.floor(durationMs / 1000);
  12113. this.durationStringTime = secondToTime(this.durationTime);
  12114. this.totalTime = this.stringForTime(durationMs);
  12115. if (this.currentSong) {
  12116. this.currentSong.duration = this.totalTime;
  12117. try {
  12118. this.avSessionController.setAVMetadataMusic(this.currentSong, durationMs, this.lyricContent);
  12119. } catch (metaError) {
  12120. Logger.warn(TAG, `heanup 首次播放写入AVSession失败: ${(metaError as Error).message}`);
  12121. }
  12122. }
  12123. };
  12124. const fetchBaiduM3u8Duration = async (url: string): Promise<number> => {
  12125. if (!url || !isBaiduType(this.currentSong?.type ?? -1)) {
  12126. return 0;
  12127. }
  12128. const httpRequest = http.createHttp();
  12129. try {
  12130. const response = await httpRequest.request(url, {
  12131. method: http.RequestMethod.GET,
  12132. connectTimeout: 8000,
  12133. readTimeout: 8000,
  12134. expectDataType: http.HttpDataType.STRING,
  12135. header: {
  12136. 'User-Agent': BaiduConstants.STREAMING_USER_AGENT,
  12137. 'Host': 'pan.baidu.com',
  12138. 'Referer': 'https://pan.baidu.com/disk/home',
  12139. 'Accept-Encoding': 'identity'
  12140. }
  12141. });
  12142. if (response.responseCode !== 200 || typeof response.result !== 'string') {
  12143. return 0;
  12144. }
  12145. const text = response.result;
  12146. if (text.indexOf('#EXTM3U') < 0) {
  12147. return 0;
  12148. }
  12149. const lines = text.split('\n');
  12150. let totalSeconds = 0;
  12151. for (let i = 0; i < lines.length; i++) {
  12152. const line = lines[i].trim();
  12153. if (line.startsWith('#EXTINF:')) {
  12154. const colonIndex = line.indexOf(':');
  12155. if (colonIndex < 0) {
  12156. continue;
  12157. }
  12158. const content = line.substring(colonIndex + 1);
  12159. const commaIndex = content.indexOf(',');
  12160. const numberPart = commaIndex >= 0 ? content.substring(0, commaIndex) : content;
  12161. const seconds = Number(numberPart);
  12162. if (!Number.isNaN(seconds) && seconds > 0) {
  12163. totalSeconds += seconds;
  12164. }
  12165. }
  12166. }
  12167. if (totalSeconds > 0) {
  12168. return Math.floor(totalSeconds * 1000);
  12169. }
  12170. return 0;
  12171. } catch (fetchError) {
  12172. Logger.warn(TAG, `heanup 解析百度M3U8时长失败: ${(fetchError as Error).message}`);
  12173. return 0;
  12174. } finally {
  12175. httpRequest.destroy();
  12176. }
  12177. };
  12178. const fetchDurationFallback = async (): Promise<void> => {
  12179. const durationMs = await fetchBaiduM3u8Duration(this.videoUrl);
  12180. if (durationMs > 0) {
  12181. Logger.info(TAG, `heanup 通过M3U8推导出时长: ${durationMs}ms`);
  12182. applyDuration(durationMs);
  12183. return;
  12184. }
  12185. Logger.warn(TAG, 'heanup 首次播放未拿到时长,保持未知');
  12186. };
  12187. const preparedDuration = this.mIjkMediaPlayer.getDuration();
  12188. console.info("onecold preparedDuration--" + preparedDuration)
  12189. if (preparedDuration > 0) {
  12190. applyDuration(preparedDuration);
  12191. if (this.videoUrl.includes('method=streaming') && isBaiduType(this.currentSong?.type ?? -1)) {
  12192. const durationMs = await fetchBaiduM3u8Duration(this.videoUrl);
  12193. if (durationMs > 0 && Math.abs(durationMs - preparedDuration) > 1000) {
  12194. Logger.info(TAG, `heanup 使用M3U8时长覆盖播放器时长: ${preparedDuration}ms -> ${durationMs}ms`);
  12195. applyDuration(durationMs);
  12196. }
  12197. }
  12198. } else {
  12199. fetchDurationFallback();
  12200. }
  12201. setTimeout(() => {
  12202. this.avSessionController.initAvSession(false);
  12203. if (this.duration > 0) {
  12204. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  12205. }
  12206. this.setAvSessionListener();
  12207. this.updateSessionPlayState(true)
  12208. this.setCurrentPlayMode()
  12209. if(startOffset&&startOffset>0){//cue分轨播放
  12210. this.seekTo(startOffset + "");
  12211. this.saveLastPlayList()
  12212. return
  12213. }
  12214. }, 500)
  12215. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12216. let timeoutPlay = 0
  12217. if (StrUtil.isNotEmpty(this.videoUrl) &&
  12218. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  12219. timeoutPlay = 1000
  12220. }
  12221. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  12222. if (this.modeType === 0) { //文件夹
  12223. let parentPath = FileUtil.getParentPath(this.videoUrl)
  12224. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  12225. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  12226. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  12227. } else if (this.modeType === 1) { //媒体库
  12228. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  12229. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  12230. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  12231. } else if (this.modeType === 2) { //艺术家
  12232. if (this.currentSong?.artist) {
  12233. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  12234. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  12235. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  12236. }
  12237. } else if (this.modeType === 3) { //专辑
  12238. if (this.currentSong?.album) {
  12239. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  12240. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  12241. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  12242. }
  12243. }
  12244. this.duration = this.mIjkMediaPlayer.getDuration()
  12245. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  12246. if (this.mIjkMediaPlayer != null) {
  12247. let jumpTopTimeMs = this.jumpTopTime*1000;
  12248. if (jumpTopTimeMs <= this.duration) {
  12249. // 调用 seekTo 方法,跳到指定时间
  12250. if(PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY,true)){
  12251. console.log('onecold jumpTopTime = '+jumpTopTimeMs);
  12252. const position:number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  12253. console.log('onecold position = '+position);
  12254. if (position > jumpTopTimeMs) {
  12255. jumpTopTimeMs = position
  12256. }
  12257. }
  12258. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12259. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  12260. this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
  12261. }
  12262. }, timeoutPlay)
  12263. } else {
  12264. // 提示用户无法跳过
  12265. ToastUtil.showToast('跳过时间超过视频时长');
  12266. }
  12267. }
  12268. } else {
  12269. this.jumpTopTime = 0
  12270. this.jumpEndTime = 0
  12271. // console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  12272. // console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  12273. // console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  12274. // PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  12275. //记忆播放(每一首都会记忆播放)
  12276. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  12277. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12278. if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  12279. this.restorePlaybackPosition() //读取播放记忆功能
  12280. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  12281. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  12282. this.restorePlaybackPosition() //读取播放记忆功能
  12283. }
  12284. this.isFirstStartPlay = false
  12285. }, timeoutPlay)
  12286. } else {
  12287. this.isFirstStartPlay = false
  12288. }
  12289. }
  12290. this.saveLastPlayList()
  12291. } catch (error) {
  12292. let err: BusinessError = error as BusinessError;
  12293. console.error('onecold failed with err: ' + JSON.stringify(err));
  12294. }
  12295. }
  12296. }
  12297. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  12298. let mOnTimedTextListener: OnTimedTextListener = {
  12299. onTimedText: () => {
  12300. }
  12301. }
  12302. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  12303. let mOnCompletionListener: OnCompletionListener = {
  12304. onCompletion: () => {
  12305. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  12306. if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
  12307. // 异步调用playNext
  12308. this.playNext().catch(() => {
  12309. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  12310. });
  12311. } else if (this.playType == 1) { //1:单片重复播放
  12312. this.CONTROL_PlayStatus = PlayStatus.INIT
  12313. that.startPlayOrResumePlay();
  12314. } else if (this.playType == 2) { //2:正常播放,单曲播完
  12315. that.showRePlay();
  12316. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  12317. that.progressValue = this.PROGRESS_MAX_VALUE;
  12318. that.slideEnable = false;
  12319. that.stop();
  12320. // ToastUtil.showToast('开始重新播放')
  12321. } else if (this.playType == 3) { //3:随机播放
  12322. // 异步调用randomPlay
  12323. this.randomPlay().catch(() => {
  12324. Logger.error('heanup OnCompletionListener randomPlay', `随机播放失败`);
  12325. });
  12326. }
  12327. }
  12328. }
  12329. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  12330. let mOnBufferingUpdateListener: OnBufferingUpdateListener = {
  12331. onBufferingUpdate: (percent: number) => {
  12332. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  12333. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  12334. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  12335. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  12336. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  12337. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  12338. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  12339. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  12340. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  12341. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  12342. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  12343. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  12344. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  12345. let Looping = this.mIjkMediaPlayer.isLooping()
  12346. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  12347. }
  12348. }
  12349. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  12350. let mOnSeekCompleteListener: OnSeekCompleteListener = {
  12351. onSeekComplete: () => {
  12352. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  12353. console.info('onecold startPlayOrResumePlay 10643')
  12354. that.startPlayOrResumePlay();
  12355. }
  12356. }
  12357. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  12358. let mOnInfoListener: OnInfoListener = {
  12359. onInfo: (what: number, extra: number) => {
  12360. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  12361. that.hideLoadIng();
  12362. }
  12363. }
  12364. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  12365. let mOnErrorListener: OnErrorListener = {
  12366. onError: (what: number, extra: number) => {
  12367. // 隐藏加载进度
  12368. this.isPlayerLoading = false;
  12369. this.stopProgressTask();
  12370. console.info("heanup OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  12371. console.info('heanup 播放错误,歌曲详情:' + JSON.stringify(this.currentSong))
  12372. // 检查是否为WebDAV播放错误
  12373. let isWebDavError = false;
  12374. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.currentSong.filePath) {
  12375. try {
  12376. const globalContext = GlobalContext.getContext();
  12377. const webDavAuthInfo = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
  12378. if (webDavAuthInfo) {
  12379. isWebDavError = true;
  12380. }
  12381. } catch (error) {
  12382. console.error('OnErrorListener-->go: 获取WebDAV认证信息失败');
  12383. }
  12384. }
  12385. if (isWebDavError) {
  12386. console.info(`heanup WebDAV播放错误 - what: ${what}, extra: ${extra}, URL: ${this.videoUrl}`);
  12387. // 播放失败时清空实例变量中的WebDAV认证信息,防止错误账户持续使用
  12388. // this.currentWebDavAuthInfo = null;
  12389. console.info('heanup WebDAV播放失败,保留认证信息用于后续歌曲切换');
  12390. // 根据错误代码提供更具体的错误信息
  12391. let errorMessage = "WebDAV播放失败";
  12392. if (what === -1) { // 网络错误
  12393. errorMessage = "网络连接失败,请检查WebDAV服务器连接";
  12394. } else if (what === -1004) { // HTTP 404
  12395. errorMessage = "文件未找到,请检查WebDAV服务器上的文件";
  12396. } else if (what === -1001) { // 超时
  12397. errorMessage = "连接超时,请检查网络或WebDAV服务器状态";
  12398. } else if (what === -1003) { // 无法解析主机
  12399. errorMessage = "无法连接到WebDAV服务器";
  12400. }
  12401. ToastUtil.showToast(errorMessage);
  12402. } else {
  12403. if (StrUtil.isNotEmpty(this.videoUrl) &&
  12404. !this.videoUrl.startsWith('http') &&
  12405. this.currentSong &&this.currentSong.type==CommonConstants.TYPE_LOCAL&&
  12406. !FileUtil.accessSync(this.videoUrl)) {
  12407. console.info('heanup 播放.文件不存在');
  12408. ToastUtil.showToast(Utility.resourceToString(this.context, $r('app.string.file_not_exist')))
  12409. }
  12410. }
  12411. that.hideLoadIng();
  12412. }
  12413. }
  12414. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  12415. this.mIjkMediaPlayer.setMessageListener();
  12416. this.mIjkMediaPlayer.prepareAsync();
  12417. this.mIjkMediaPlayer.start();
  12418. }
  12419. //保存最后播放的那首歌和已经对应的播放列表
  12420. saveLastPlayList() {
  12421. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  12422. PreferencesUtil.putSync('LastMusicList', this.songList)
  12423. }
  12424. // 清空播放记录
  12425. clearVideoHistory() {
  12426. this.table.clearPlayHistory((success: boolean, error?: string) => {
  12427. if (success) {
  12428. this.historyList = [];
  12429. this.updateListData(this.historyList)
  12430. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  12431. ToastUtil.showToast('清空播放记录成功')
  12432. } else {
  12433. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  12434. }
  12435. });
  12436. }
  12437. public async setAvSessionListener() {
  12438. if (!this.avSessionController) {
  12439. return;
  12440. }
  12441. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  12442. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  12443. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  12444. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  12445. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  12446. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  12447. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  12448. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  12449. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  12450. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  12451. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  12452. }
  12453. setLoopMode() {
  12454. let itype = this.playType + 1
  12455. if (itype >= 4) {
  12456. this.playType = 0
  12457. ToastUtil.showToast('连续播放')
  12458. } else if (itype === 1) {
  12459. this.playType = 1
  12460. ToastUtil.showToast('单曲循环')
  12461. } else if (itype === 2) {
  12462. this.playType = 2
  12463. ToastUtil.showToast('单曲播完')
  12464. } else if (itype === 3) {
  12465. this.playType = 3
  12466. ToastUtil.showToast('随机播放')
  12467. } else if (itype === 0) {
  12468. this.playType = 0
  12469. ToastUtil.showToast('连续播放')
  12470. }
  12471. PreferencesUtil.putSync('musicPlayType', this.playType)
  12472. this.setCurrentPlayMode()
  12473. }
  12474. private sessionSetLoopModeCallback = (mode: number) => {
  12475. if (this.mIjkMediaPlayer != null) {
  12476. ToastUtil.showToast('当前播放模式:' + mode)
  12477. Logger.info('onecold 当前播放模式= ' + mode)
  12478. let hmPlayMode = mode + 1
  12479. if (hmPlayMode >= 4) {
  12480. hmPlayMode = 0
  12481. }
  12482. if (hmPlayMode === 1) {
  12483. this.playType = 1
  12484. ToastUtil.showToast('单曲循环')
  12485. } else if (hmPlayMode === 0) {
  12486. this.playType = 2
  12487. ToastUtil.showToast('单曲播完')
  12488. } else if (hmPlayMode === 3) {
  12489. this.playType = 3
  12490. ToastUtil.showToast('随机播放')
  12491. } else if (hmPlayMode === 2) {
  12492. this.playType = 0
  12493. ToastUtil.showToast('连续播放')
  12494. }
  12495. PreferencesUtil.putSync('musicPlayType', this.playType)
  12496. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  12497. let playBackState: avSession.AVPlaybackState = {
  12498. loopMode: hmPlayMode,
  12499. };
  12500. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  12501. console.info(`set setLoopMode AVPlaybackState successfully`);
  12502. }).catch((err: BusinessError) => {
  12503. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  12504. });
  12505. }
  12506. }
  12507. setCurrentPlayMode() {
  12508. if (!this.avSessionController) {
  12509. return;
  12510. }
  12511. let mLoopMode = 0
  12512. switch (this.playType) {
  12513. case 0:
  12514. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  12515. break;
  12516. case 1:
  12517. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  12518. break;
  12519. case 2:
  12520. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  12521. break;
  12522. case 3:
  12523. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  12524. break;
  12525. }
  12526. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  12527. let playBState: avSession.AVPlaybackState = {
  12528. loopMode: mLoopMode,
  12529. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  12530. };
  12531. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  12532. console.info(`set setLoopMode AVPlaybackState successfully`);
  12533. }).catch((err: BusinessError) => {
  12534. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  12535. });
  12536. }
  12537. private sessionToggleFavoriteCallback = (assetId: string) => {
  12538. if (this.mIjkMediaPlayer != null && this.currentSong) {
  12539. console.info(`on toggleFavorite `);
  12540. // 应用收到收藏命令,进行收藏处理。
  12541. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  12542. this.doFav(this.currentSong)
  12543. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  12544. let playbackState: avSession.AVPlaybackState = {
  12545. isFavorite: !this.isFac,
  12546. };
  12547. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  12548. console.info(`SetAVPlaybackState successfully`);
  12549. }).catch((err: BusinessError) => {
  12550. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  12551. });
  12552. }
  12553. }
  12554. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  12555. device: avSession.OutputDeviceInfo) => {
  12556. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  12557. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  12558. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  12559. await this.startCasting();
  12560. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  12561. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  12562. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  12563. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  12564. if (device) {
  12565. this.endCasting();
  12566. }
  12567. }
  12568. };
  12569. private async startCasting() {
  12570. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  12571. this.setPlaybackStateChangeListener();
  12572. this.pause();
  12573. this.initQueueItem();
  12574. this.prepare();
  12575. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  12576. refToIsCasting?.set(true);
  12577. this.castSeek = true;
  12578. this.isCastPlaying = true;
  12579. }
  12580. async changeCasting() {
  12581. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  12582. this.initQueueItem();
  12583. this.prepare();
  12584. this.setPlaybackStateChangeListener();
  12585. this.isCastPlaying = true;
  12586. this.castSeek = true;
  12587. }
  12588. public endCasting() {
  12589. this.avSessionController.getAvSession()?.stopCasting();
  12590. this.stopCast();
  12591. this.isCastPlaying = false;
  12592. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  12593. refToIsCasting?.set(false);
  12594. this.pause();
  12595. this.setIsPlaying(false);
  12596. // if (this.curIndex === this.curSource.index) {
  12597. // this.play
  12598. // this.seek(this.currentTime * 1000);
  12599. // this.setIsPlaying(true);
  12600. // } else {
  12601. // this.pauseVideo();
  12602. // this.setIsPlaying(false);
  12603. // }
  12604. }
  12605. public setIsPlaying(isPlayer: boolean) {
  12606. this.isPlaying = isPlayer;
  12607. // 发送播放状态变化事件给歌单详情页面
  12608. try {
  12609. const eventPlaybackStatus: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYBACK_STATUS }
  12610. const currentFilePath = this.currentSong?.filePath || ''
  12611. const eventData: emitter.EventData = {
  12612. data: {
  12613. isPlaying: this.isPlaying,
  12614. curIndex: this.curIndex,
  12615. currentFilePath: currentFilePath
  12616. }
  12617. };
  12618. emitter.emit(eventPlaybackStatus, eventData)
  12619. Logger.info(`heanup 发送播放状态变化事件: isPlaying=${this.isPlaying}, curIndex=${this.curIndex}, currentFilePath=${currentFilePath}`)
  12620. } catch (error) {
  12621. Logger.error('heanup 发送播放状态变化事件失败: ' + error)
  12622. }
  12623. }
  12624. private setPlaybackStateChangeListener(): void {
  12625. this.castController?.on('playbackStateChange', 'all', this.playbackStateChangeListener);
  12626. this.castController?.on('endOfStream', this.reloadCasting);
  12627. this.castController?.on('playNext', this.playNextCallback);
  12628. this.castController?.on('playPrevious', this.playPreviousCallback);
  12629. }
  12630. private updateSessionPlayState(isPlay: boolean): void {
  12631. // if(!this.isBgPlayOpen)
  12632. // return
  12633. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  12634. this.setAVSessionPlayState({
  12635. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  12636. position: {
  12637. elapsedTime: this.mIjkMediaPlayer.getCurrentPosition(),
  12638. updateTime: new Date().getTime()
  12639. }
  12640. });
  12641. }
  12642. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  12643. this.avSessionController.setAvSessionPlayState(playbackState)
  12644. }
  12645. private positionChange(position: number) {
  12646. this.currentTime2 = position / 1000;
  12647. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  12648. }
  12649. private playDurationChange(duration: number) {
  12650. this.duration = duration;
  12651. this.durationTime = Math.floor(this.duration / 1000);
  12652. this.durationStringTime = secondToTime((this.durationTime));
  12653. }
  12654. private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
  12655. const duration = playbackState?.extras?.duration;
  12656. if (typeof duration === 'number') {
  12657. this.playDurationChange(duration as number);
  12658. }
  12659. if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
  12660. this.positionChange(playbackState?.position?.elapsedTime);
  12661. }
  12662. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PAUSE ||
  12663. playbackState.state === CommonConstants2.PLAYBACK_STATE_STOP ||
  12664. playbackState.state === CommonConstants2.PLAYBACK_STATE_PREPARE ||
  12665. playbackState.state === CommonConstants2.PLAYBACK_STATE_INITIAL) {
  12666. this.isCastPlaying = false;
  12667. }
  12668. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  12669. this.isCastPlaying = true;
  12670. }
  12671. };
  12672. private reloadCasting = async () => {
  12673. let item = this.songList[this.curIndex];
  12674. let uri = fileUri.getUriFromPath(item.filePath);
  12675. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  12676. // description.startPosition = 0;
  12677. this.castItem = {
  12678. itemId: this.curIndex,
  12679. description: {
  12680. assetId: item.filePath,
  12681. title: item.name,
  12682. artist: '',
  12683. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  12684. // mediaUri: item.filePath,
  12685. fdSrc: {
  12686. fd: file.fd
  12687. },
  12688. // 该字段大写,音频'AUDIO',视频'VIDEO'
  12689. mediaType: 'VIDEO',
  12690. mediaSize: item.videoSize,
  12691. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  12692. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  12693. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  12694. duration: this.duration,
  12695. // albumCoverUri: 'https://www.example.jpeg',
  12696. // albumTitle: '《ExampleAlbum》',
  12697. appName: this.appName,
  12698. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  12699. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  12700. }
  12701. };
  12702. this.prepare();
  12703. this.isCastPlaying = true;
  12704. };
  12705. public playNextCallback = (): void => {
  12706. this.playNext().catch(() => {
  12707. Logger.error('heanup playNextCallback', `播放下一首失败`);
  12708. });
  12709. };
  12710. public playPreviousCallback = (): void => {
  12711. this.playPrevious().catch(() => {
  12712. Logger.error('heanup playNextCallback', `播放上一首失败`);
  12713. });
  12714. };
  12715. async prepare() {
  12716. await this.castController?.prepare(this.castItem);
  12717. await this.castController?.start(this.castItem);
  12718. }
  12719. public initQueueItem() {
  12720. let item = this.songList[this.curIndex];
  12721. let time = this.currentTime;
  12722. let uri = fileUri.getUriFromPath(item.filePath);
  12723. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  12724. this.castItem = {
  12725. itemId: this.curIndex,
  12726. description: {
  12727. assetId: item.filePath,
  12728. title: item.name,
  12729. artist: '',
  12730. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  12731. fdSrc: {
  12732. fd: file.fd
  12733. },
  12734. // 该字段大写,音频'AUDIO',视频'VIDEO'
  12735. mediaType: 'AUDIO',
  12736. mediaSize: item.videoSize,
  12737. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  12738. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  12739. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  12740. duration: this.duration,
  12741. // albumCoverUri: 'https://www.example.jpeg',
  12742. // albumTitle: '《ExampleAlbum》',
  12743. appName: this.appName,
  12744. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  12745. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  12746. }
  12747. };
  12748. }
  12749. async stopCast() {
  12750. try {
  12751. this.castController?.off('playbackStateChange');
  12752. this.castController?.off('endOfStream');
  12753. this.castController?.off('playNext');
  12754. this.castController?.off('playPrevious');
  12755. this.castController?.off('error');
  12756. } catch (error) {
  12757. hilog.info(0x0000, TAG, `Failed to setAVCastController. code: ${error.code}, message: ${error.message}`);
  12758. }
  12759. }
  12760. private sessionPlayCallback = (): void => {
  12761. this.playOrPause()
  12762. };
  12763. private sessionPauseCallback = (): void => {
  12764. this.pause()
  12765. };
  12766. private playOrPause() {
  12767. if (!this.debounce()) {
  12768. return;
  12769. }
  12770. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  12771. this.pause();
  12772. } else {
  12773. console.info('onecold startPlayOrResumePlay 11064')
  12774. this.startPlayOrResumePlay();
  12775. this.playChange()
  12776. }
  12777. }
  12778. private sessionPlayNextCallback = (): void => {
  12779. this.playNext().catch(() => {
  12780. Logger.error('heanup sessionPlayPreviousCallback', `播放下 一首失败`);
  12781. });
  12782. };
  12783. private sessionPlayPreviousCallback = (): void => {
  12784. this.playPrevious().catch(() => {
  12785. Logger.error('heanup sessionPlayPreviousCallback', `播放上一首失败`);
  12786. });
  12787. };
  12788. private sessionStopCallback = (): void => {
  12789. this.stop()
  12790. };
  12791. private sessionFastForwardCallback = (time?: number) => {
  12792. if (!time) {
  12793. return;
  12794. }
  12795. if (this.mIjkMediaPlayer != null) {
  12796. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  12797. let seeTime = curPosition + time * 1000;
  12798. // 限制 seekValue 在合法范围内
  12799. if (seeTime < 0) {
  12800. seeTime = 0;
  12801. } else if (seeTime > this.duration) {
  12802. seeTime = this.duration;
  12803. }
  12804. Logger.info('onecold seeTime= ' + seeTime)
  12805. this.setSeekToActionProgress(seeTime)
  12806. this.seekTo(seeTime + "")
  12807. }
  12808. };
  12809. /**
  12810. * Gesture method onActionUpdate.
  12811. *
  12812. * @param event Gesture event.手势拖动设置快进和后退
  12813. */
  12814. private setSeekToActionProgress(position: number) {
  12815. // let position = this.mIjkMediaPlayer.getCurrentPosition();
  12816. let duration = this.mIjkMediaPlayer.getDuration();
  12817. let pos = 0;
  12818. if (duration > 0) {
  12819. this.slideEnable = true;
  12820. let curPercent = position / duration;
  12821. pos = curPercent * 100;
  12822. if (pos > this.PROGRESS_MAX_VALUE) {
  12823. this.progressValue = this.PROGRESS_MAX_VALUE
  12824. } else {
  12825. this.progressValue = pos;
  12826. }
  12827. }
  12828. // LogUtils.getInstance()
  12829. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  12830. this.totalTime = this.stringForTime(duration);
  12831. if (position > duration) {
  12832. position = duration;
  12833. }
  12834. this.isCurrentTime = true;
  12835. this.currentTime = this.stringForTime(position);
  12836. this.isCurrentTime = false
  12837. }
  12838. private sessionRewindCallback = (time?: number) => {
  12839. if (!time) {
  12840. return;
  12841. }
  12842. if (this.mIjkMediaPlayer != null) {
  12843. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  12844. let seeTime = curPosition - time * 1000;
  12845. // 限制 seekValue 在合法范围内
  12846. if (seeTime < 0) {
  12847. seeTime = 0;
  12848. } else if (seeTime > this.duration) {
  12849. seeTime = this.duration;
  12850. }
  12851. Logger.info('onecold seeTime= ' + seeTime)
  12852. this.setSeekToActionProgress(seeTime)
  12853. this.seekTo(seeTime + "")
  12854. }
  12855. };
  12856. private sessionSeekCallback = (seekTime: number) => {
  12857. if (this.mIjkMediaPlayer != null) {
  12858. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  12859. this.seekTo(seekTime + "")
  12860. }
  12861. };
  12862. private async getFileSize(filePath: string): Promise<number> {
  12863. try {
  12864. const stat = await fs.stat(filePath);
  12865. return stat.size;
  12866. } catch (err) {
  12867. console.error('Failed to get file size: ' + err.message);
  12868. return 0;
  12869. }
  12870. }
  12871. private pause() {
  12872. if (this.mIjkMediaPlayer.isPlaying()) {
  12873. this.savePlaybackPosition();
  12874. this.mIjkMediaPlayer.pause();
  12875. this.setProgress();
  12876. this.mDestroyPage = true;
  12877. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  12878. this.updateSessionPlayState(false)
  12879. this.playChange()
  12880. if (this.pipController) {
  12881. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  12882. PiPWindow.PiPControlStatus.PAUSE);
  12883. }
  12884. }
  12885. }
  12886. private stop() {
  12887. this.savePlaybackPosition();
  12888. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12889. this.mIjkMediaPlayer.stop();
  12890. this.mIjkMediaPlayer.release();
  12891. this.stopProgressTask();
  12892. this.updateSessionPlayState(false)
  12893. this.playChange()
  12894. this.watchStatus();
  12895. }
  12896. //保持记忆播放功能
  12897. private savePlaybackPosition() {
  12898. if (this.mIjkMediaPlayer != null) {
  12899. const position = this.mIjkMediaPlayer.getCurrentPosition();
  12900. // ToastUtil.showToast('保存记忆播放 = ' + position)
  12901. const duration = this.mIjkMediaPlayer.getDuration();
  12902. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  12903. // 如果播放位置接近视频末尾,则保存 position 为 0
  12904. const playbackPosition = (duration - position < threshold) ? 0 : position;
  12905. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  12906. }
  12907. }
  12908. //获取记忆播放功能
  12909. private restorePlaybackPosition() {
  12910. const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  12911. // ToastUtil.showToast('position = ' + position)
  12912. if (this.mIjkMediaPlayer != null && position > 0) {
  12913. // ToastUtil.showToast('seekTo = ' + position)
  12914. this.seekTo(position + "");
  12915. }
  12916. }
  12917. private seekTo(value: string) {
  12918. if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  12919. ToastUtil.showToast('wma格式不支持拖动快进。')
  12920. return
  12921. }
  12922. this.isSeekTo = true
  12923. this.mIjkMediaPlayer.seekTo(value);
  12924. console.info('onecold startPlayOrResumePlay 11227')
  12925. // this.startPlayOrResumePlay()
  12926. // 在这里恢复计时器状态
  12927. this.setProgress()
  12928. this.isSeekTo = false
  12929. }
  12930. // 添加到下一首播放
  12931. private addToNextPlay(song: VideoItem) {
  12932. if (!this.debounce()) {
  12933. return;
  12934. }
  12935. if (this.currentSong) {
  12936. if (this.currentSong === song) {
  12937. ToastUtil.showToast('当前已经在播放这首歌了!')
  12938. return
  12939. }
  12940. }
  12941. // 如果未开始播放或队列为空
  12942. if (this.curIndex === -1 || this.songList.length === 0) {
  12943. this.songList = [song];
  12944. this.curIndex = 0;
  12945. this.doPlay(song)
  12946. return;
  12947. }
  12948. // 插入到当前索引+1的位置
  12949. const insertPos = this.curIndex + 1;
  12950. this.songList.splice(insertPos, 0, song);
  12951. this.songList = [...this.songList]; // 触发状态更新
  12952. this.sonDataSource.pushArrayData(this.songList)
  12953. ToastUtil.showToast('已添加至下一首播放')
  12954. }
  12955. //后退10s,可再设置设置默认几秒
  12956. backForward() {
  12957. if(this.mIjkMediaPlayer){
  12958. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  12959. let value = pos - Number(this.fastForwardSeconds) * 1000;
  12960. this.seekTo(value+"");
  12961. }
  12962. }
  12963. //快进10s,可再设置设置默认几秒
  12964. fastForward() {
  12965. if(this.mIjkMediaPlayer){
  12966. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  12967. let value = pos + Number(this.fastForwardSeconds) * 1000;
  12968. this.seekTo(value+"");
  12969. }
  12970. }
  12971. //下一个
  12972. private async playNext() {
  12973. if (!this.debounce()) {
  12974. return;
  12975. }
  12976. if (this.playType == 3) { //3:随机播放
  12977. await this.randomPlay()
  12978. return;
  12979. }
  12980. if (ArrayUtil.isNotEmpty(this.songList)) {
  12981. if (this.curIndex >= this.songList.length - 1) {
  12982. await this.tryLoadNextPageForPlayback();
  12983. }
  12984. if (this.curIndex >= this.songList.length - 1) {
  12985. this.curIndex = 0;
  12986. } else {
  12987. this.curIndex++;
  12988. }
  12989. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12990. this.stop();
  12991. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  12992. this.currentSong = this.songList[this.curIndex];
  12993. Logger.info('heanup playNext', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  12994. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  12995. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  12996. context: this.context,
  12997. autoParseMusicName: this.autoParseMusicName
  12998. });
  12999. this.artist = this.songList[this.curIndex].artist
  13000. this.name = this.songList[this.curIndex].name
  13001. //this.cover = this.songList[this.curIndex].pixelMapPath
  13002. this.changeImageAnimation()
  13003. }
  13004. }
  13005. changeImageAnimation() {
  13006. if(this.openSkipSongAnimate){
  13007. // 第一步:淡出动画
  13008. this.getUIContext()?.animateTo({
  13009. duration: 500,
  13010. curve: Curve.EaseOut,
  13011. }, () => {
  13012. this.opacityValueImage = 0.1;
  13013. if(this.isCoverRectangle){
  13014. this.scaleValueImage = 0.88
  13015. }
  13016. });
  13017. // 第二步:切换图片后淡入
  13018. setTimeout(() => {
  13019. this.cover = this.songList[this.curIndex].pixelMapPath
  13020. this.getUIContext()?.animateTo({
  13021. duration: 500,
  13022. curve: Curve.EaseIn,
  13023. }, () => {
  13024. this.opacityValueImage = 1;
  13025. this.scaleValueImage = 1 // 图标恢复到原始大小
  13026. this.startPlayOrResumePlay()
  13027. });
  13028. }, 500);
  13029. }else{
  13030. this.cover = this.songList[this.curIndex].pixelMapPath
  13031. this.startPlayOrResumePlay()
  13032. }
  13033. }
  13034. // 内部方法:提前缓存下一首
  13035. private async preloadNextSongInternal(): Promise<void> {
  13036. await preloadNextSongIfNeeded(this.songList, this.curIndex, this.playType);
  13037. }
  13038. // 存储已播放的歌曲索引
  13039. private playedIndices: Set<number> = new Set();
  13040. //随机播放
  13041. private async randomPlay() {
  13042. // if (!this.debounce()) {
  13043. // return;
  13044. // }
  13045. if (ArrayUtil.isNotEmpty(this.songList)) {
  13046. if (this.songList.length > 3) {
  13047. // 如果所有歌曲都播放过一次,清空已播放索引集合
  13048. if (this.playedIndices.size === this.songList.length) {
  13049. this.playedIndices.clear();
  13050. }
  13051. // 随机选择一个未播放的歌曲索引
  13052. let newIndex: number;
  13053. // 添加超时机制防止无限循环
  13054. let attempt = 0;
  13055. const maxAttempts = 100; // 根据需求调整
  13056. do {
  13057. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  13058. attempt++;
  13059. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  13060. if (attempt >= maxAttempts) {
  13061. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  13062. newIndex = Math.floor(Math.random() * this.songList.length);
  13063. }
  13064. this.curIndex = newIndex;
  13065. this.playedIndices.add(newIndex);
  13066. } else {
  13067. // 当歌曲数量小于或等于3时,直接播放下一首
  13068. if (this.curIndex == this.songList.length - 1) {
  13069. this.curIndex = 0;
  13070. } else {
  13071. this.curIndex++;
  13072. }
  13073. }
  13074. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13075. this.stop();
  13076. this.currentSong = this.songList[this.curIndex];
  13077. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13078. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13079. context: this.context,
  13080. autoParseMusicName: this.autoParseMusicName
  13081. });
  13082. this.name = this.songList[this.curIndex].name;
  13083. this.artist = this.songList[this.curIndex].artist
  13084. // this.cover = this.songList[this.curIndex].pixelMapPath
  13085. this.changeImageAnimation()
  13086. }
  13087. }
  13088. private async playIndex(index: number) {
  13089. if (!this.debounce()) {
  13090. return;
  13091. }
  13092. if (ArrayUtil.isNotEmpty(this.songList)) {
  13093. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13094. this.stop();
  13095. this.curIndex = index;
  13096. this.currentSong = this.songList[index];
  13097. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13098. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13099. context: this.context,
  13100. autoParseMusicName: this.autoParseMusicName
  13101. });
  13102. this.name = this.currentSong.name
  13103. this.artist = this.currentSong.artist
  13104. this.changeImageAnimation()
  13105. }
  13106. }
  13107. //上一个
  13108. private async playPrevious() {
  13109. if (!this.debounce()) {
  13110. return;
  13111. }
  13112. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  13113. this.randomModePlayFromHistory()
  13114. return;
  13115. }
  13116. if (this.curIndex == 0) {
  13117. this.curIndex = this.songList.length - 1;
  13118. } else {
  13119. this.curIndex--;
  13120. }
  13121. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13122. this.stop();
  13123. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  13124. this.currentSong = this.songList[this.curIndex];
  13125. Logger.info('heanup playPrevious', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  13126. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13127. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13128. context: this.context,
  13129. autoParseMusicName: this.autoParseMusicName
  13130. });
  13131. this.name = this.songList[this.curIndex].name
  13132. this.artist = this.songList[this.curIndex].artist
  13133. this.changeImageAnimation()
  13134. }
  13135. //随机播放模式下点击上一首: 上一首应该应该播放历史记录的第二首
  13136. private async randomModePlayFromHistory() {
  13137. if (this.historyList.length >= 2) {
  13138. // 播放历史记录的第二首
  13139. const prevSong = this.historyList[1];
  13140. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  13141. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13142. this.stop();
  13143. // 直接使用历史记录中的歌曲信息,历史记录中的数据应该是完整的
  13144. this.currentSong = prevSong;
  13145. Logger.info('heanup randomModePlayFromHistory', `直接使用历史歌曲信息: ${prevSong.name}, type: ${prevSong.type}`);
  13146. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13147. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13148. context: this.context,
  13149. autoParseMusicName: this.autoParseMusicName
  13150. });
  13151. this.cover = prevSong.pixelMapPath
  13152. this.artist = prevSong.artist
  13153. this.name = prevSong.name;
  13154. console.info('onecold startPlayOrResumePlay 11434')
  13155. this.startPlayOrResumePlay();
  13156. } else {
  13157. // 如果历史记录不足两首,可根据需求处理,这里简单按普通逻辑处理
  13158. if (this.curIndex === 0) {
  13159. this.curIndex = this.songList.length - 1;
  13160. } else {
  13161. this.curIndex--;
  13162. }
  13163. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13164. this.stop();
  13165. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  13166. this.currentSong = this.songList[this.curIndex];
  13167. Logger.info('heanup randomModePlayFromHistory', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  13168. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13169. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13170. context: this.context,
  13171. autoParseMusicName: this.autoParseMusicName
  13172. });
  13173. this.artist = this.songList[this.curIndex].artist
  13174. this.name = this.songList[this.curIndex].name;
  13175. this.changeImageAnimation()
  13176. }
  13177. }
  13178. debounce() {
  13179. const delay = 600;
  13180. let cur = new Date().getTime();
  13181. if (cur - this.last > delay) {
  13182. this.last = cur;
  13183. return true;
  13184. }
  13185. return false;
  13186. }
  13187. /**
  13188. * Sets whether the screen is a constant based on the playback status.
  13189. */
  13190. watchStatus() {
  13191. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  13192. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  13193. this.windowClass.setWindowKeepScreenOn(true);
  13194. } else {
  13195. this.windowClass.setWindowKeepScreenOn(false);
  13196. }
  13197. }
  13198. /**
  13199. * Volume gesture method onActionStart.
  13200. *
  13201. * @param event Gesture event.
  13202. */
  13203. private customDialogComponentIdMM: number = 0
  13204. @Builder
  13205. customDialogComponentMM() {
  13206. Column() {
  13207. Row() {
  13208. Blank()
  13209. Text('验证密码')
  13210. .fontSize(22)
  13211. .fontColor($r('app.color.pri_bg'))
  13212. .margin({ top: 18 })
  13213. Blank()
  13214. Image($r('app.media.close'))
  13215. .fillColor(Color.White)
  13216. .margin({ top: 18, right: 18 })
  13217. .width(20)
  13218. .onClick(() => {
  13219. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  13220. })
  13221. }
  13222. .width('100%') // 使Row占据整个宽度
  13223. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  13224. Verify({
  13225. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  13226. });
  13227. }.height('60%')
  13228. .backgroundColor($r('app.color.index_background'))
  13229. .justifyContent(FlexAlign.SpaceBetween)
  13230. }
  13231. private handleVerifyCompleted(isSuccess: boolean) {
  13232. if (isSuccess) {
  13233. console.log('验证成功');
  13234. // 在这里处理验证成功后的逻辑
  13235. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  13236. this.currentPath = this.lockPath
  13237. this.getSortedFiles(this.currentPath)
  13238. } else {
  13239. // console.log('验证失败');
  13240. ToastUtil.showToast('验证失败')
  13241. }
  13242. }
  13243. private showVerifyDialog() {
  13244. promptAction.openCustomDialog({
  13245. transition: TransitionEffect.asymmetric(
  13246. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  13247. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  13248. ,
  13249. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  13250. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  13251. ),
  13252. builder: () => {
  13253. this.customDialogComponentMM()
  13254. },
  13255. isModal: true,
  13256. autoCancel: true,
  13257. maskColor: Color.Transparent,
  13258. alignment: DialogAlignment.Bottom,
  13259. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  13260. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  13261. console.log("dialog onWillDismiss")
  13262. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  13263. dismissDialogAction.dismiss()
  13264. }
  13265. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  13266. dismissDialogAction.dismiss()
  13267. }
  13268. }
  13269. }).then((dialogId: number) => {
  13270. this.customDialogComponentIdMM = dialogId
  13271. })
  13272. }
  13273. //左滑操作 移动文件 重命名 删除等操作
  13274. @Builder
  13275. DeleteButton(item: VideoItem, index: number, filePath: string) {
  13276. Row() {
  13277. //加入收藏
  13278. Button() {
  13279. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  13280. .fillColor(Color.White)
  13281. .width(20)
  13282. }
  13283. .width(40)
  13284. .height(40)
  13285. .type(ButtonType.Circle)
  13286. .backgroundColor(this.themeColor)
  13287. .margin(5)
  13288. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13289. .onClick(() => {
  13290. if (item) {
  13291. this.doFav(item)
  13292. }
  13293. })
  13294. //加入下一首播放
  13295. Button() {
  13296. Image($r('app.media.next_to_play'))
  13297. .fillColor(Color.White)
  13298. .width(20)
  13299. }
  13300. .width(40)
  13301. .height(40)
  13302. .type(ButtonType.Circle)
  13303. .backgroundColor(this.themeColor)
  13304. .margin(5)
  13305. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13306. .onClick(() => {
  13307. this.addToNextPlay(item);
  13308. })
  13309. //复制文件
  13310. Button() {
  13311. Image($r('app.media.copy'))
  13312. .fillColor(Color.White)
  13313. .width(20)
  13314. }
  13315. .width(40)
  13316. .height(40)
  13317. .type(ButtonType.Circle)
  13318. .backgroundColor(this.themeColor)
  13319. .margin(5)
  13320. .id(filePath + 'copy')
  13321. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13322. .onClick(() => {
  13323. this.showCopyDialog(false, item, index, filePath + 'copy');
  13324. })
  13325. //移动文件
  13326. Button() {
  13327. Image($r('app.media.cut'))
  13328. .fillColor(Color.White)
  13329. .width(20)
  13330. }
  13331. .width(40)
  13332. .height(40)
  13333. .type(ButtonType.Circle)
  13334. .backgroundColor(this.themeColor)
  13335. .margin(5)
  13336. .id(filePath)
  13337. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13338. .onClick(() => {
  13339. this.showCutDialog(false, item, index, filePath);
  13340. })
  13341. Button() {
  13342. Image($r('app.media.cut_current'))
  13343. .fillColor(Color.White)
  13344. .width(20)
  13345. }
  13346. .width(40)
  13347. .height(40)
  13348. .type(ButtonType.Circle)
  13349. .backgroundColor(this.themeColor)
  13350. .margin(5)
  13351. .id(filePath + 'current')
  13352. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  13353. (this.isHasDir ? Visibility.Visible : Visibility.None))
  13354. .onClick(() => {
  13355. this.showCutDialog(true, item, index, filePath + 'current');
  13356. })
  13357. //重命名
  13358. Button() {
  13359. Image($r('app.media.rename2'))
  13360. .fillColor(Color.White)
  13361. .width(20)
  13362. }
  13363. .width(40)
  13364. .height(40)
  13365. .type(ButtonType.Circle)
  13366. .backgroundColor(this.themeColor)
  13367. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  13368. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  13369. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  13370. .margin(5)
  13371. .onClick(() => {
  13372. this.showReNameDialog(item, index + '', filePath)
  13373. })
  13374. Button() {
  13375. Image($r('app.media.delete2'))
  13376. .fillColor(Color.White)
  13377. .width(20)
  13378. }
  13379. .width(40)
  13380. .height(40)
  13381. .type(ButtonType.Circle)
  13382. .backgroundColor(this.themeColor)
  13383. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  13384. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  13385. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  13386. .margin(5)
  13387. .onClick(() => {
  13388. this.selectedFiles.push(item)
  13389. this.showWarnIsDelete()
  13390. // this.showWarnIsDeleteFile(item, index + '', filePath)
  13391. })
  13392. Button() {
  13393. Image($r('app.media.share2'))
  13394. .fillColor(Color.White)
  13395. .width(20)
  13396. }
  13397. .width(40)
  13398. .height(40)
  13399. .type(ButtonType.Circle)
  13400. .backgroundColor(this.themeColor)
  13401. .margin(5)
  13402. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13403. .onClick(() => {
  13404. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  13405. })
  13406. }
  13407. }
  13408. /**
  13409. * 穿山甲banner广告
  13410. */
  13411. // private declare bannerAd: CSJNativeExpressAd;
  13412. // @State private status: string = "未加载"
  13413. // @State private isShowAd: boolean = false
  13414. // private declare mAdSlot: AdSlot;
  13415. // private mBiddingAdm = '' //服务端bidding才需要设置
  13416. // private expressLoadAdListener: NativeExpressAdListener = {
  13417. // /**
  13418. // * 加载失败的回调
  13419. // *
  13420. // * @param code
  13421. // * @param message
  13422. // */
  13423. // onError: (code: number, message: string) => {
  13424. // console.error("加载广告失败,code=" + code + ",message=" + message);
  13425. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  13426. // },
  13427. //
  13428. // /**
  13429. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  13430. // *
  13431. // * @param ads 返回的广告列表
  13432. // */
  13433. //
  13434. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  13435. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  13436. // if (ads && ads.length > 0) {
  13437. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  13438. // ad.setExpressInteractionListener({
  13439. // /**
  13440. // *广告的点击回调
  13441. // * @param type 广告的交互类型
  13442. // */
  13443. // onAdClicked: (type: number) => {
  13444. // console.log("BannerExpressAdPage==onAdClicked......");
  13445. // },
  13446. //
  13447. // /**
  13448. // * 广告的展示回调 每个广告仅回调一次
  13449. // * @param type 广告的交互类型
  13450. // */
  13451. // onAdShow: (type: number) => {
  13452. // console.log("BannerExpressAdPage==onAdShow......");
  13453. // },
  13454. //
  13455. // /**
  13456. // * 模板渲染失败
  13457. // */
  13458. // onRenderFail: (code: number, msg: string) => {
  13459. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  13460. // },
  13461. //
  13462. // /**
  13463. // * 模板渲染成功
  13464. // * @param width 返回view的宽 单位 vp
  13465. // * @param height 返回view的高 单位 vp
  13466. // */
  13467. // onRenderSuccess: (width: number, height: number) => {
  13468. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  13469. // this.bannerAd = ad;
  13470. // this.status = "广告加载完成待展示";
  13471. //
  13472. // this.showBannerAd()
  13473. // }
  13474. // })
  13475. // //渲染广告
  13476. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  13477. // this.setDislikeCallback(ad); //设置dislike
  13478. // ad.render(this.getUIContext())
  13479. // this.status = "广告加载中...";
  13480. // });
  13481. // }
  13482. // }
  13483. // }
  13484. //
  13485. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  13486. // ad.setDislikeCallback({
  13487. // /**
  13488. // * dislike show
  13489. // */
  13490. // onShow: () => {
  13491. // console.log("BannerExpressAdPage==dislike......show");
  13492. // },
  13493. //
  13494. // /**
  13495. // * @param position 选择的位置
  13496. // * @param value 选择的内容
  13497. // * @param enforceRemove 是否强制关闭广告
  13498. // */
  13499. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  13500. // this.isShowAd = false;
  13501. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  13502. // ",enforce=" + enforceRemove);
  13503. // },
  13504. //
  13505. // /**
  13506. // * 点击取消
  13507. // */
  13508. // onCancel: () => {
  13509. // console.log("BannerExpressAdPage==dislike......onCancel");
  13510. // }
  13511. //
  13512. // })
  13513. // }
  13514. /**
  13515. * 加载Banner广告
  13516. */
  13517. loadBannerAd(rit: string) {
  13518. // if (Utility.isNoble()) {
  13519. // return
  13520. // }
  13521. // if (!Utility.isPassInstallTime(2)) {
  13522. // return
  13523. // }
  13524. // this.isShowAd = false;
  13525. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  13526. // this.mAdSlot = new AdSlotBuilder()
  13527. // .setCodeId(rit)
  13528. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  13529. // .setAdCount(1)
  13530. // .setBidAdm(this.mBiddingAdm)
  13531. // .build()
  13532. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  13533. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  13534. // this.status = "广告加载中..."
  13535. }
  13536. /**
  13537. * 展示Banner广告
  13538. */
  13539. // showBannerAd() {
  13540. // if (!this.bannerAd) {
  13541. // return
  13542. // }
  13543. // this.isShowAd = true
  13544. // this.status = "已展示"
  13545. // }
  13546. /**
  13547. * 穿山甲广告代码结束
  13548. */
  13549. /**
  13550. * 处理歌单播放请求
  13551. */
  13552. private async handlePlaylistPlayRequest(playlistId: string, playlistName:
  13553. string, songFilePaths: string[], startIndex: number,isJump: boolean) {
  13554. try {
  13555. Logger.info(`heanup 处理歌单播放请求: ${playlistName}, 歌曲数量: ${songFilePaths.length}, 开始索引: ${startIndex}`)
  13556. // 检查是否为WebDAV播放请求
  13557. if (playlistId === 'webdav-playlist') {
  13558. Logger.info(`heanup 检测到WebDAV播放请求,从内存读取videoItems`)
  13559. // 从全局内存读取videoItems数据
  13560. const videoItems = getWebdavVideoItems();
  13561. const currentPlayIndex = getWebdavCurrentPlayIndex();
  13562. Logger.info(`heanup 从内存读取到WebDAV歌曲列表,长度:${videoItems.length},索引:${currentPlayIndex}`)
  13563. if (videoItems && videoItems.length > 0) {
  13564. // 验证webdav_account_id设置情况
  13565. const accountIds = videoItems.map(item => item.webdav_account_id).filter(id => id);
  13566. Logger.info(`heanup 有 ${accountIds.length}/${videoItems.length} 首歌曲设置了webdav_account_id`)
  13567. if(isJump){
  13568. this.setShowPlayTrue()//显示播放页
  13569. }
  13570. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName)
  13571. return
  13572. } else {
  13573. return
  13574. }
  13575. }
  13576. if (playlistId === 'navidrome-playlist') {
  13577. Logger.info(`heanup 检测到Navidrome播放请求,从内存读取videoItems`);
  13578. const videoItems = getNavidromeVideoItems();
  13579. const currentPlayIndex = getNavidromeCurrentPlayIndex();
  13580. Logger.info(`heanup Navidrome歌曲列表长度: ${videoItems.length}`);
  13581. if (videoItems && videoItems.length > 0) {
  13582. if(isJump){
  13583. this.setShowPlayTrue()//显示播放页
  13584. }
  13585. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName);
  13586. return;
  13587. } else {
  13588. Logger.warn('heanup Navidrome播放请求缺少歌曲数据');
  13589. return;
  13590. }
  13591. }
  13592. // 从数据库重新加载这些歌曲,使用索引记录位置以保持顺序
  13593. const songMap: Map<number, VideoItem> = new Map()
  13594. let completedQueries = 0
  13595. Logger.info(`heanup 开始从数据库查询 ${songFilePaths.length} 首歌曲`)
  13596. // 遍历所有文件路径,使用索引记录位置
  13597. for (let i = 0; i < songFilePaths.length; i++) {
  13598. const filePath = songFilePaths[i]
  13599. const index = i
  13600. // Logger.info(`heanup 正在查询歌曲[${index}]: ${filePath}`)
  13601. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  13602. const queryPromise = this.table.queryVideoByFilePath(filePath)
  13603. // Logger.info(`heanup 创建了查询Promise,开始等待结果[${index}]: ${filePath}`)
  13604. queryPromise.then((videoItem) => {
  13605. completedQueries++
  13606. // Logger.info(`heanup 查询Promise返回结果[${index}]: ${filePath}, 找到歌曲: ${videoItem ? videoItem.name : 'null'}`)
  13607. if (videoItem) {
  13608. // 使用索引作为key保存到Map中,保持原始顺序
  13609. songMap.set(index, videoItem)
  13610. // Logger.info(`heanup 从数据库找到歌曲[${index}]: ${videoItem.name} (${completedQueries}/${songFilePaths.length})`)
  13611. } else {
  13612. Logger.warn(`heanup 数据库中未找到歌曲[${index}]: ${filePath} (${completedQueries}/${songFilePaths.length})`)
  13613. }
  13614. // 检查是否所有歌曲都已加载完成
  13615. if (completedQueries === songFilePaths.length) {
  13616. // Logger.info(`heanup 所有数据库查询完成,共找到 ${songMap.size} 首歌曲`)
  13617. // 按照索引顺序重建歌曲数组
  13618. const songs: VideoItem[] = []
  13619. for (let j = 0; j < songFilePaths.length; j++) {
  13620. const song = songMap.get(j)
  13621. if (song) {
  13622. songs.push(song)
  13623. // Logger.info(`heanup 按顺序添加歌曲[${j}]: ${song.name}`)
  13624. }
  13625. }
  13626. Logger.info(`heanup 最终歌曲列表顺序: ${songs.map((s, idx) => `[${idx}]${s.name}`).join(', ')}`)
  13627. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  13628. }
  13629. }).catch((error: Error) => {
  13630. completedQueries++
  13631. Logger.error(`heanup 查询歌曲失败[${index}]: ${filePath}, 错误: ${error.message} (${completedQueries}/${songFilePaths.length})`)
  13632. // 即使出错也要检查是否完成所有查询
  13633. if (completedQueries === songFilePaths.length) {
  13634. Logger.info(`heanup 所有数据库查询完成(包含错误),共找到 ${songMap.size} 首歌曲`)
  13635. // 按照索引顺序重建歌曲数组
  13636. const songs: VideoItem[] = []
  13637. for (let j = 0; j < songFilePaths.length; j++) {
  13638. const song = songMap.get(j)
  13639. if (song) {
  13640. songs.push(song)
  13641. }
  13642. }
  13643. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  13644. }
  13645. })
  13646. }
  13647. } catch (error) {
  13648. Logger.error('heanup 处理简化歌单播放请求失败: ' + error)
  13649. ToastUtil.showToast('播放失败')
  13650. }
  13651. }
  13652. /**
  13653. * 完成歌单加载并开始播放
  13654. */
  13655. private finishLoadingPlaylist(songs: VideoItem[], startIndex: number, playlistName: string) {
  13656. if (songs.length === 0) {
  13657. Logger.error('heanup 没有找到任何可播放的歌曲')
  13658. ToastUtil.showToast('没有找到可播放的歌曲')
  13659. return
  13660. }
  13661. this.songList = songs
  13662. this.sonDataSource.pushArrayData(songs)
  13663. this.sonDataSource.notifyDataReload()
  13664. this.curIndex = startIndex
  13665. if (songs[startIndex]) {
  13666. // 确保当前播放的歌曲也更新到存储
  13667. AppStorage.setOrCreate('currentSong', songs[startIndex])
  13668. // 设置isFromSonPlayList=true,避免doPlay方法重新从全局列表构建播放列表
  13669. this.doPlay(songs[startIndex], startIndex, true)
  13670. }
  13671. PreferencesUtil.putSync('LastMusicList', this.songList)
  13672. // ToastUtil.showToast(`开始播放歌单: ${playlistName}`)
  13673. }
  13674. }
  13675. //视频气泡窗口的布局
  13676. @Builder
  13677. function customPopupBuilder(dataBu: BubbleBean) {
  13678. List() {
  13679. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  13680. ListItem() {
  13681. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13682. Row() {
  13683. Column() {
  13684. Image(dataBu.imageRes[index])
  13685. .height(28)
  13686. .fillColor(dataBu.color)
  13687. .alignSelf(ItemAlign.Center)
  13688. }
  13689. .width(32)
  13690. Text(item)
  13691. .padding({
  13692. top: 10,
  13693. bottom: 10,
  13694. right: 10,
  13695. left: 10
  13696. })
  13697. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  13698. .textAlign(TextAlign.Start)
  13699. .width("100%")
  13700. }
  13701. }
  13702. .backgroundColor($r('app.color.settings_background_main'))
  13703. .margin({ top: 6, bottom: 6 })
  13704. }
  13705. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  13706. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  13707. TransitionEffect.scale({ x: 0, y: 0 })))
  13708. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  13709. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  13710. .onClick(() => {
  13711. dataBu.onItemClick?.(index)
  13712. })
  13713. })
  13714. }
  13715. .scrollBar(BarState.Off)
  13716. .width(120)
  13717. .divider({
  13718. strokeWidth: 1,
  13719. color: "#22FFFFFF"
  13720. })
  13721. }
  13722. // Function to calculate a hash for the file list
  13723. function simpleHash(fileList: string[]): string {
  13724. let hash = 0;
  13725. const str = fileList.join(',');
  13726. for (let i = 0; i < str.length; i++) {
  13727. const char = str.charCodeAt(i);
  13728. hash = (hash << 5) - hash + char;
  13729. hash |= 0; // Convert to 32bit integer
  13730. }
  13731. return hash.toString();
  13732. }
  13733. interface MoreItem {
  13734. id: number;
  13735. image: Resource;
  13736. title: string;
  13737. }
  13738. //视频气泡窗口的布局
  13739. @Builder
  13740. function cutPopupBuilder(dataBu: BubbleBean) {
  13741. Column() {
  13742. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  13743. .padding({
  13744. top: 10,
  13745. bottom: 10,
  13746. right: 10,
  13747. left: 10
  13748. })
  13749. .textAlign(TextAlign.Start)
  13750. .width(160)
  13751. .fontWeight(666)
  13752. .fontSize(16)
  13753. List() {
  13754. ForEach(dataBu.data, (item: string, index: number) => {
  13755. ListItem() {
  13756. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13757. Row() {
  13758. Column() {
  13759. Image($r('app.media.music_group'))
  13760. .height(28)
  13761. .fillColor(dataBu.color)
  13762. .alignSelf(ItemAlign.Center)
  13763. }
  13764. .width(32)
  13765. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  13766. .padding({
  13767. top: 10,
  13768. bottom: 10,
  13769. right: 10,
  13770. left: 10
  13771. })
  13772. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  13773. .fontSize(15)
  13774. }
  13775. }
  13776. .backgroundColor(Color.Transparent)
  13777. .margin({ top: 7, bottom: 7 })
  13778. }
  13779. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  13780. .animation({ duration: 500 }),
  13781. TransitionEffect.scale({ x: 0, y: 0 })))
  13782. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  13783. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  13784. .onClick(() => {
  13785. dataBu.onItemClick?.(index)
  13786. })
  13787. })
  13788. }
  13789. .scrollBar(BarState.Off)
  13790. .width(150)
  13791. .divider({
  13792. strokeWidth: 1,
  13793. color: "#22FFFFFF"
  13794. })
  13795. }
  13796. .height(300)
  13797. .padding({
  13798. bottom: 30
  13799. })
  13800. }
  13801. function getFileDirName(filePath: string,rootPath:string): string{
  13802. if(filePath===rootPath){
  13803. return '首页'
  13804. }
  13805. let result = FileUtil.getFileName(filePath)
  13806. if(StrUtil.isEmpty(result))
  13807. return ''
  13808. if(result.startsWith('.'))
  13809. result = result.replace(/\./g, '')
  13810. return result
  13811. }
  13812. //只扫描当前目录下文件(不扫描子文件夹)的方法
  13813. @Concurrent
  13814. async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
  13815. const table: MediaTable = new MediaTable(context);
  13816. try {
  13817. // 直接获取当前目录下的文件列表
  13818. const files = FileUtil.listFileSync(dirPath);
  13819. await Promise.all(files.map(async (file) => {
  13820. const fPath = `${dirPath}/${file}`;
  13821. // 跳过目录,只处理文件
  13822. if (FileUtil.isDirectory(fPath)) {
  13823. return;
  13824. }
  13825. // 跳过特定格式文件
  13826. if (fPath.endsWith('.lrc') || fPath.endsWith('.srt')) {
  13827. return;
  13828. }
  13829. // 检查是否为媒体文件
  13830. if (Utility.isMeidaByExtension(fPath)) {
  13831. let mType = CommonConstants.TYPE_LOCAL;
  13832. if (fPath.includes(lockPath)) {
  13833. mType = CommonConstants.TYPE_LOCK;
  13834. }
  13835. const mediaItem = await Utility.uriGetMusicAssetsFromFile(
  13836. context, fPath, mType, true
  13837. );
  13838. table.insert(mediaItem, (id: number) => {
  13839. // 插入回调函数
  13840. }, cover_api);
  13841. }
  13842. }));
  13843. } catch (error) {
  13844. console.error(' 扫描当前目录失败:', error);
  13845. }
  13846. }
  13847. //内嵌标签后更新库
  13848. @Concurrent
  13849. async function updateInfoDb(
  13850. context: Context,
  13851. filePath: string,
  13852. titleStr: string,
  13853. artistStr: string,
  13854. albumStr: string,
  13855. lyricConStr: string,
  13856. yearStr: string,
  13857. genreStr: string,
  13858. trackStr: string,
  13859. albumArtistStr: string,
  13860. composerStr: string,
  13861. lyricistStr: string,
  13862. commentStr: string,
  13863. discStr: string,
  13864. ): Promise<boolean> {
  13865. const table: MediaTable = new MediaTable(context);
  13866. await new Promise<void>((resolve, reject) => {
  13867. table.getRdbStore(context, (err:Error) => {
  13868. err ? reject(err) : resolve();
  13869. });
  13870. });
  13871. return await new Promise<boolean>((resolve) => {
  13872. table.updateMediaInfo(filePath, titleStr, artistStr, albumStr, lyricConStr,
  13873. yearStr, genreStr, trackStr, albumArtistStr, composerStr, lyricistStr, commentStr, discStr,
  13874. (success: boolean, error?: string) => {
  13875. if (success) {
  13876. console.log("onecold 编辑信息成功,数据库已同步");
  13877. } else {
  13878. console.error("onecold 编辑信息数据库失败原因: " + error);
  13879. }
  13880. resolve(success);
  13881. });
  13882. });
  13883. }