LocalMusic.ets 534 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487
  1. import TitleBar from './TitleBar'
  2. import { curves, display, MenuModifier,PiPWindow, promptAction, router, SymbolGlyphModifier, window } from '@kit.ArkUI';
  3. import { VideoItem } from '../viewmodel/VideoItem';
  4. import { LengthMetrics, SegmentButton,SegmentButtonOptions } from '@kit.ArkUI';
  5. import { getWebdavVideoItems, getWebdavCurrentPlayIndex } from '../pages/WebDavMainPage';
  6. import {
  7. ButtonFancyModifier,
  8. ImageFancyModifier,
  9. ShadowModifier,
  10. SymbolGlyphFancyModifier } from '../common/util/AttributeModifierUtil'
  11. import {
  12. AppUtil,
  13. ArrayUtil,
  14. Base64Util,
  15. DateUtil,
  16. DeviceUtil,
  17. FileUtil,
  18. GlobalContext,
  19. LogUtil,
  20. MD5,
  21. PreferencesUtil,
  22. RandomUtil,
  23. StrUtil,
  24. ToastUtil
  25. } from '@pura/harmony-utils';
  26. import { imagePathToPixelMap } from '../common/util/CommUtils';
  27. import { unifiedDataChannel, uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData';
  28. import { CommonConstants } from '../common/constants/CommonConstants';
  29. import { EventConstants } from '../common/constants/EventConstants';
  30. import Logger from '../common/util/Logger';
  31. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  32. import { BusinessError, emitter } from '@kit.BasicServicesKit';
  33. import { BubbleBean } from '../viewmodel/BubbleBean';
  34. import { PopupPosition, XPopup } from '@chinalike/popup';
  35. import { common, ConfigurationConstant } from '@kit.AbilityKit';
  36. import { AnimationHelper, DialogAction, DialogHelper } from '@pura/harmony-dialog';
  37. import { fileIo, fileUri, picker } from '@kit.CoreFileKit';
  38. import { MessageEvents, util, worker, ErrorEvent } from '@kit.ArkTS';
  39. import { Verify } from './Verify';
  40. import { taskpool } from '@kit.ArkTS';
  41. import { RotatingCover } from './RotatingCover';
  42. import { PlayConstants } from '../common/constants/PlayConstants';
  43. import { effectKit } from '@kit.ArkGraphics2D';
  44. import { ColorConversion } from '../common/util/ColorConversion';
  45. import { LyricController, LyricParser, LyricView2 } from '@seagazer/cclyric';
  46. import { AvSessionController } from '../controller/AvSessionController';
  47. import { repairAudioMetadata, convertDsfToWav, getApiLyric,changeMusicCover} from '../common/util/MusicTagUtils';
  48. import { FFMpegTags,Utility } from '../common/util/Utility';
  49. import { TagsContentCover } from '../view/TagsContentCover';
  50. import {
  51. // DeviceChangeReason,
  52. IjkMediaPlayer,
  53. InterruptEvent,
  54. InterruptHintType,
  55. LogUtils,
  56. OnBufferingUpdateListener,
  57. OnCompletionListener,
  58. OnErrorListener,
  59. OnInfoListener,
  60. OnPreparedListener,
  61. OnSeekCompleteListener,
  62. OnTimedTextListener,
  63. OnVideoSizeChangedListener
  64. } from '@ohos/ijkplayer';
  65. import { PlayStatus } from '../common/PlayStatus';
  66. import fs from '@ohos.file.fs';
  67. import { image } from '@kit.ImageKit';
  68. import { AVCastPicker, AVCastPickerState, AVCastPickerStyle, avSession } from '@kit.AVSessionKit';
  69. import { UniversalDetector } from '@ohos/juniversalchardet';
  70. import { SettingPage } from '../pages/SettingPage';
  71. import { secondToTime,getTransverterText } from '../common/util/CommUtils';
  72. import { CommonConstants2 } from '../common/util/CommonConstants2';
  73. import { hilog } from '@kit.PerformanceAnalysisKit';
  74. import { LazyDataSource } from '../common/util/LazyDataSource';
  75. import MediaTable from '../common/util/MediaTable';
  76. import FileDeletionWatcher from '../common/util/FileDeletionWatcher';
  77. import NetAxiosUtil from '../common/util/NetAxiosUtil';
  78. import ImageUtils from '../common/util/ImageUtils';
  79. import { ringtone } from '@kit.RingtoneKit';
  80. import { BreakpointType, BreakpointTypeEnum } from '../common/util/BreakpointSystem';
  81. import { resourceManager } from '@kit.LocalizationKit';
  82. import { deviceInfo } from '@kit.BasicServicesKit';
  83. import { RemoteCacheManager } from '../common/network/RemoteCacheManager';
  84. import '../common/network/RemoteCacheRegistry';
  85. import { RemoteCacheType } from '../common/network/RemoteSongCache';
  86. import { findWebDavCacheIfExists, triggerWebDavCacheDownload } from '../common/network/WebDavFileCache';
  87. import { navidromeApi } from '../common/network/NavidromeApi';
  88. import { HSBColorPicker, HSBColorPickerLayout } from '@keke/color-picker'
  89. import app from '@system.app';
  90. import { TextNodeController } from './PipLyricTextBuilder';
  91. import { IndexerView } from './IndexerView';
  92. import { KeyCode } from '@kit.InputKit';
  93. import { KnockController } from '../controller/KnockController';
  94. import { DeleteComptent } from '../view/DeleteComptent';
  95. import { ABLoopComptent } from '../view/ABLoopComptent';
  96. import { FixMessyView } from '../view/FixMessyView';
  97. import { parseCueFile,CueTrack,CueInfo } from '../common/util/CueUtils';
  98. import { CueComptent } from '../view/CueComptent';
  99. import PlaylistTable from '../common/util/PlaylistTable';
  100. import { showAddToPlaylistDialog } from '../dialog/AddToPlaylistDialog';
  101. import { showCreatePlaylistDialog } from '../dialog/PlaylistDialog';
  102. import { convertPlaylistSongsToVideoItems, emptyView,updateAllSongsSortOrder } from '../pages/PlaylistDetailPage';
  103. import { Playlist, PlaylistSong } from '../viewmodel/Playlist';
  104. import { Song } from '../viewmodel/Song';
  105. import { SongType } from '../common/enums/SongType';
  106. import { RemoteDriveManager, WebDavAuthInfo as WebDavManagerAuthInfo,
  107. buildHttpHeadersWithWebDav,
  108. WebDavAuthItem} from '../common/util/RemoteDriveManager';
  109. import PermissionUtil from '../common/util/PermissionUtil'
  110. import { EditAudio, setRingTone } from './EditAudio';
  111. import { ExtractAccompaniment } from './ExtractAccompaniment';
  112. import { ExtractAudioFromVideo } from './ExtractAudioFromVideo';
  113. import { AudioFormatConverter } from './AudioFormatConverter';
  114. import { MergeAudio } from './MergeAudio';
  115. import { AIVoiceSeparation } from './AIVoiceSeparation';
  116. import { WebDavUrlUtil } from '../common/util/WebDavUrlUtil';
  117. import { ChangeTone } from './ChangeTone';
  118. import {
  119. hdsEffect,
  120. HdsVisualComponent,
  121. HdsSceneController,
  122. HdsSceneType,
  123. HdsVisualComponentAttribute,
  124. } from '@kit.UIDesignKit';
  125. import { GlobalAlphabetIndexerModifier } from '../Styels/GlobalStyles'
  126. import { getFirstLetter } from '../Constants';
  127. const TAG = 'LocalMusic';
  128. /**
  129. * 歌单播放事件数据
  130. */
  131. interface PlaylistEventData {
  132. playlistId: string;
  133. playlistName: string;
  134. songCount: number;
  135. startIndex: number;
  136. songFilePaths: string[];
  137. webDavAuthInfo?: WebDavAuthItem; // 新增WebDAV认证信息
  138. }
  139. const DEFAULT_INDEX =
  140. ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  141. 'X', 'Y', 'Z']
  142. //排序类型
  143. function getTypeOrder(type: number) {
  144. switch (type) {
  145. case CommonConstants.TYPE_IS_DIR:
  146. return 1; // First
  147. case CommonConstants.TYPE_IS_CSJAD:
  148. return 2; // Middle
  149. case CommonConstants.TYPE_LOCAL:
  150. return 3; // Last
  151. case CommonConstants.TYPE_WEBDAV:
  152. case CommonConstants.TYPE_SMB:
  153. case CommonConstants.TYPE_NAVIDROME:
  154. return 3;
  155. default:
  156. return 4; // Unknown types, if any, go last
  157. }
  158. }
  159. function isWebDavType(type: number): boolean {
  160. return type === CommonConstants.TYPE_WEBDAV;
  161. }
  162. function isSmbType(type: number): boolean {
  163. return type === CommonConstants.TYPE_SMB;
  164. }
  165. function isNavidromeType(type: number): boolean {
  166. return type === CommonConstants.TYPE_NAVIDROME;
  167. }
  168. function isFtpType(type: number): boolean {
  169. return type === CommonConstants.TYPE_FTP;
  170. }
  171. function isRemoteCloudType(type: number): boolean {
  172. return isWebDavType(type) || isSmbType(type) || isNavidromeType(type) || isFtpType(type);
  173. }
  174. function getShareNameFromFilePath(filePath?: string): string | undefined {
  175. if (!filePath) {
  176. return undefined;
  177. }
  178. const match = filePath.match(/^smb:\/\/[^/]+\/([^/]+)/i);
  179. return match && match[1] ? match[1] : undefined;
  180. }
  181. function removeSharePrefixFromPath(path: string, primaryShare?: string, secondaryShare?: string): string {
  182. const uniqueShares: string[] = [];
  183. [primaryShare, secondaryShare].forEach((name?: string) => {
  184. const cleaned = name ? name.replace(/^\/+|\/+$/g, '') : '';
  185. if (cleaned.length > 0 && !uniqueShares.some(item => item.toLowerCase() === cleaned.toLowerCase())) {
  186. uniqueShares.push(cleaned);
  187. }
  188. });
  189. if (uniqueShares.length === 0) {
  190. return path;
  191. }
  192. let result = path;
  193. for (let i = 0; i < uniqueShares.length; i++) {
  194. const share = uniqueShares[i];
  195. const lowerPath = result.toLowerCase();
  196. const lowerShare = share.toLowerCase();
  197. if (lowerPath === lowerShare) {
  198. result = '';
  199. break;
  200. }
  201. const prefix = `${lowerShare}/`;
  202. if (lowerPath.startsWith(prefix)) {
  203. result = result.substring(share.length + 1);
  204. break;
  205. }
  206. }
  207. return result;
  208. }
  209. function extractSmbRelativePath(song: VideoItem, shareNameOverride?: string): string {
  210. const shareFromFilePath = getShareNameFromFilePath(song.filePath);
  211. const shareName = shareNameOverride ?? shareFromFilePath;
  212. if (song.remote_rel_path && song.remote_rel_path.length > 0) {
  213. const cleaned = song.remote_rel_path.replace(/^\/+/, '');
  214. return removeSharePrefixFromPath(cleaned, shareName, shareFromFilePath);
  215. }
  216. if (!song.filePath) {
  217. return '';
  218. }
  219. const match = song.filePath.match(/^smb:\/\/[^/]+\/([^/]+)(\/.*)?$/i);
  220. if (!match) {
  221. return song.filePath.replace(/^\/+/, '');
  222. }
  223. const remainder = match[2] ? match[2].replace(/^\/+/, '') : '';
  224. if (remainder.length === 0) {
  225. return '';
  226. }
  227. return remainder;
  228. }
  229. function extractFtpRelativePath(song: VideoItem): string {
  230. if (song.remote_rel_path && song.remote_rel_path.length > 0) {
  231. return song.remote_rel_path.replace(/^\/+/, '');
  232. }
  233. if (!song.filePath) {
  234. return '';
  235. }
  236. const match = song.filePath.match(/^ftp:\/\/[^/]+(?::\d+)?(\/.*)$/i);
  237. if (match && match[1]) {
  238. return match[1].replace(/^\/+/, '');
  239. }
  240. return song.filePath.replace(/^\/+/, '');
  241. }
  242. const workerInstance = new worker.ThreadWorker("entry/ets/workers/Worker.ets");
  243. interface MetadataExtractionOptions {
  244. context?: common.Context;
  245. autoParseMusicName?: boolean;
  246. }
  247. interface WorkerEditMusicResult {
  248. success: boolean;
  249. error?: string;
  250. coverResult?: boolean;
  251. needRefreshList?: boolean;
  252. metadataResult?: boolean;
  253. }
  254. interface LocalEditMusicPayload {
  255. context: Context;
  256. item: VideoItem;
  257. titleStr: string;
  258. artistStr: string;
  259. ablumStr: string;
  260. yearStr: string;
  261. genreStr: string;
  262. trackStr: string;
  263. albumArtistStr: string;
  264. composerStr: string;
  265. lyricistStr: string;
  266. commentStr: string;
  267. discStr: string;
  268. lyricConStr: string;
  269. imagePathStr: string;
  270. currentPath: string;
  271. packName: string;
  272. modeType: number;
  273. autoParseMusicName: boolean;
  274. }
  275. interface WorkerMetadataPayload {
  276. originFilePath: string;
  277. originId?: string;
  278. bit_rate?: string;
  279. duration?: string;
  280. sampleRate?: string;
  281. mimeType?: string;
  282. md5Str?: string;
  283. videoSize?: number;
  284. size?: string;
  285. pixelMapPath?: string;
  286. artist?: string;
  287. album?: string;
  288. name?: string;
  289. lyricContent?: string;
  290. bits_per_raw_sample?: string;
  291. channels?: string;
  292. channel_layout?: string;
  293. start_time?: string;
  294. genre?: string;
  295. year?: string;
  296. probe_score?: number;
  297. track?: string;
  298. disc?: string;
  299. ALBUMARTIST?: string;
  300. COMPOSER?: string;
  301. COMMENT?: string;
  302. LYRICIST?: string;
  303. nb_streams?: number;
  304. nb_programs?: number;
  305. error?: string;
  306. }
  307. interface WebDavMetadataUpdatePayload {
  308. filePath: string;
  309. pixelMapPath?: string;
  310. name?: string;
  311. artist?: string;
  312. }
  313. const metadataExtractionInFlight: Set<string> = new Set();
  314. function scheduleMetadataExtractionFromCache(
  315. song: VideoItem,
  316. cachePath: string,
  317. options?: MetadataExtractionOptions
  318. ): void {
  319. if (!song || !cachePath || !song.filePath || !options || !options.context) {
  320. return;
  321. }
  322. if (!isRemoteCloudType(song.type ?? -1)) {
  323. return;
  324. }
  325. if (metadataExtractionInFlight.has(song.filePath)) {
  326. return;
  327. }
  328. if (song.bit_rate && song.sampleRate && song.duration) {
  329. return;
  330. }
  331. metadataExtractionInFlight.add(song.filePath);
  332. workerInstance.postMessage({
  333. code: 5,
  334. data: options.context,
  335. data2: cachePath,
  336. data3: song.type,
  337. data4: {
  338. name:song.name,
  339. originFilePath: song.filePath,
  340. originId: song.id,
  341. autoParseMusicName: options.autoParseMusicName ?? false
  342. }
  343. });
  344. }
  345. function sanitizePlaybackUrl(rawUrl: string | null | undefined): string {
  346. if (!rawUrl) {
  347. return '';
  348. }
  349. try {
  350. const decoded = decodeURI(rawUrl);
  351. const encoded = encodeURI(decoded);
  352. // encodeURI 不会处理 #,手动转义避免播放器把剩余内容当作片段
  353. return encoded.replace(/#/g, '%23');
  354. } catch (error) {
  355. const err = error as Error;
  356. Logger.warn(TAG, `URL 编码失败,使用降级方案: ${err?.message}`);
  357. return rawUrl.replace(/ /g, '%20').replace(/#/g, '%23');
  358. }
  359. }
  360. function cloneVideoItem(item: VideoItem): VideoItem {
  361. const copy = new VideoItem(
  362. item.name,
  363. item.id,
  364. item.filePath,
  365. item.type,
  366. item.videoSize,
  367. item.cTime,
  368. item.size,
  369. item.pixelMapPath,
  370. item.artist,
  371. item.album,
  372. item.fileName,
  373. item.lastPlayed
  374. );
  375. copy.parentPath = item.parentPath;
  376. copy.isFav = item.isFav;
  377. copy.size = item.size;
  378. copy.pixelMapPath = item.pixelMapPath;
  379. copy.artist = item.artist;
  380. copy.album = item.album;
  381. copy.duration = item.duration;
  382. copy.mimeType = item.mimeType;
  383. copy.sampleRate = item.sampleRate;
  384. copy.trackCount = item.trackCount;
  385. copy.lastPlayedStr = item.lastPlayedStr;
  386. copy.playCount = item.playCount;
  387. copy.lyricContent = item.lyricContent;
  388. copy.md5Str = item.md5Str;
  389. copy.extra_json = item.extra_json;
  390. copy.pyStr = item.pyStr;
  391. copy.bit_rate = item.bit_rate;
  392. copy.probe_score = item.probe_score;
  393. copy.year = item.year;
  394. copy.nb_streams = item.nb_streams;
  395. copy.nb_programs = item.nb_programs;
  396. copy.genre = item.genre;
  397. copy.track = item.track;
  398. copy.bits_per_raw_sample = item.bits_per_raw_sample;
  399. copy.channels = item.channels;
  400. copy.channel_layout = item.channel_layout;
  401. copy.start_time = item.start_time;
  402. copy.ALBUMARTIST = item.ALBUMARTIST;
  403. copy.COMPOSER = item.COMPOSER;
  404. copy.LYRICIST = item.LYRICIST;
  405. copy.COMMENT = item.COMMENT;
  406. copy.disc = item.disc;
  407. copy.webdav_account_id = item.webdav_account_id;
  408. copy.remote_rel_path = item.remote_rel_path;
  409. return copy;
  410. }
  411. /**
  412. * 异步设置videoUrl的辅助方法,处理WebDAV URL的构建
  413. * @param song 歌曲对象
  414. * @returns Promise<string> 完整的URL
  415. */
  416. /**
  417. * 设置videoUrl,通过webdav_account_id设置完整的 URL
  418. * @param song 歌曲对象
  419. * @returns Promise<string> 完整的URL
  420. */
  421. async function setVideoUrlForSong(song: VideoItem, options?: MetadataExtractionOptions): Promise<string> {
  422. const metadataOptions = options ?? {};
  423. if (isWebDavType(song.type) && song.webdav_account_id) {
  424. try {
  425. Logger.info(TAG, `WebDAV 路径信息 remote_rel_path: ${song.remote_rel_path}`);
  426. Logger.info(TAG, `WebDAV 路径信息 filePath: ${song.filePath}`);
  427. const relativePath = song.remote_rel_path || song.filePath;
  428. const manager = RemoteDriveManager.getInstance();
  429. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  430. if (account) {
  431. const cachePath = await findWebDavCacheIfExists(account, relativePath);
  432. if (cachePath) {
  433. Logger.info(TAG, `WebDAV 缓存命中,直接播放: ${cachePath}`);
  434. scheduleMetadataExtractionFromCache(song, cachePath, metadataOptions);
  435. return cachePath;
  436. }
  437. const fullUrlFromAccount = WebDavUrlUtil.buildFullUrl(account, relativePath);
  438. if (fullUrlFromAccount) {
  439. const sanitizedUrl = sanitizePlaybackUrl(fullUrlFromAccount);
  440. const downloadPromise = triggerWebDavCacheDownload(account, relativePath, sanitizedUrl);
  441. if (downloadPromise) {
  442. downloadPromise.then((completedPath?: string | null) => {
  443. if (completedPath) {
  444. scheduleMetadataExtractionFromCache(song, completedPath, metadataOptions);
  445. }
  446. }).catch((error: Error) => {
  447. Logger.error(TAG, `WebDAV 缓存后台下载失败: ${error.message}`);
  448. });
  449. }
  450. Logger.info(TAG, `WebDAV 启动异步缓存: ${relativePath}`);
  451. return sanitizedUrl;
  452. }
  453. }
  454. const fallbackUrl = await WebDavUrlUtil.buildFullUrlByAccountId(song.webdav_account_id, relativePath);
  455. if (fallbackUrl) {
  456. Logger.warn(TAG, `WebDAV 使用全局查询到的URL: ${fallbackUrl}`);
  457. return sanitizePlaybackUrl(fallbackUrl);
  458. }
  459. Logger.error(TAG, `WebDAV URL构建失败,使用原始路径: ${relativePath}`);
  460. return sanitizePlaybackUrl(relativePath);
  461. } catch (error) {
  462. Logger.error(TAG, `WebDAV URL构建出错: ${(error as Error).message}`);
  463. const fallbackPath = song.remote_rel_path || song.filePath;
  464. return sanitizePlaybackUrl(fallbackPath);
  465. }
  466. }
  467. if (isNavidromeType(song.type) && song.webdav_account_id) {
  468. try {
  469. const manager = RemoteDriveManager.getInstance();
  470. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  471. if (!account) {
  472. throw new Error('Navidrome账号不可用');
  473. }
  474. const navSongId = song.remote_rel_path || song.id || song.filePath;
  475. const streamUrl = await navidromeApi.buildStreamUrl(account, navSongId);
  476. Logger.info(TAG, `Navidrome 流地址构建成功: ${streamUrl}`);
  477. return sanitizePlaybackUrl(streamUrl);
  478. } catch (error) {
  479. const err = error as Error;
  480. Logger.error(TAG, `Navidrome URL构建失败: ${err.message}`);
  481. throw new Error(err.message);
  482. }
  483. }
  484. if (isSmbType(song.type) && song.webdav_account_id) {
  485. try {
  486. const manager = RemoteDriveManager.getInstance();
  487. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  488. if (!account) {
  489. throw new Error('SMB账号不可用');
  490. }
  491. const relativePath = extractSmbRelativePath(song, account.smbShare);
  492. const cachedPath = await RemoteCacheManager.ensureCached(RemoteCacheType.SMB, {
  493. account,
  494. remotePath: relativePath
  495. });
  496. Logger.info(TAG, `SMB 缓存路径: ${cachedPath}`);
  497. scheduleMetadataExtractionFromCache(song, cachedPath, metadataOptions);
  498. return cachedPath;
  499. } catch (error) {
  500. const err = error as Error;
  501. Logger.error(TAG, `SMB 缓存失败: ${err.message}`);
  502. throw new Error(err.message);
  503. }
  504. }
  505. if (isFtpType(song.type) && song.webdav_account_id) {
  506. try {
  507. const manager = RemoteDriveManager.getInstance();
  508. const account = await manager.getWebDavAccountById(song.webdav_account_id);
  509. if (!account) {
  510. throw new Error('FTP账号不可用');
  511. }
  512. const relativePath = extractFtpRelativePath(song);
  513. const cachedPath = await RemoteCacheManager.ensureCached(RemoteCacheType.FTP, {
  514. account,
  515. remotePath: relativePath
  516. });
  517. Logger.info(TAG, `FTP 缓存路径: ${cachedPath}`);
  518. scheduleMetadataExtractionFromCache(song, cachedPath, metadataOptions);
  519. return cachedPath;
  520. } catch (error) {
  521. const err = error as Error;
  522. Logger.error(TAG, `FTP 缓存失败: ${err.message}`);
  523. throw new Error(err.message);
  524. }
  525. }
  526. if (isWebDavType(song.type)) {
  527. Logger.warn(TAG, `WebDAV歌曲缺少webdav_account_id,使用原始路径: ${song.filePath}`);
  528. return sanitizePlaybackUrl(song.filePath);
  529. }
  530. if (isSmbType(song.type)) {
  531. Logger.warn(TAG, `SMB歌曲缺少webdav_account_id,使用原始路径: ${song.filePath}`);
  532. return song.filePath;
  533. }
  534. if (isFtpType(song.type)) {
  535. Logger.warn(TAG, `FTP歌曲缺少webdav_account_id,使用原始路径: ${song.filePath}`);
  536. return song.filePath;
  537. }
  538. if (isNavidromeType(song.type)) {
  539. throw new Error('Navidrome歌曲缺少webdav_account_id,无法构建播放链接');
  540. }
  541. return song.filePath;
  542. }
  543. // 定义接口
  544. interface HiCarAspectRatio {
  545. ratio: number;
  546. name: string;
  547. }
  548. interface GeneratedObjectLiteralInterface_1 {
  549. assetId: string;
  550. title: string;
  551. artist: string;
  552. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  553. mediaUri: string;
  554. // 该字段大写,音频'AUDIO',视频'VIDEO'
  555. mediaType: string;
  556. mediaSize: number;
  557. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  558. startPosition: number;
  559. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  560. duration: number;
  561. albumCoverUri: string;
  562. albumTitle: string;
  563. appName: string;
  564. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  565. drmScheme: string;
  566. }
  567. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  568. const ITEM_HEIGHT: number = 65; // 列表项中高度
  569. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  570. //功能强大的音乐播放器
  571. @Preview
  572. @Component
  573. export struct LocalMusic {
  574. // 字母表
  575. @State alphaBet: string[] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
  576. 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  577. @State alphaBetStyle: GlobalAlphabetIndexerModifier = new GlobalAlphabetIndexerModifier()
  578. @State selectAlphaBetIndex: number = 0
  579. @State isShowAlphaBet: boolean = false
  580. @State isScrolling: boolean = false
  581. @State isTouchingAlphaBet: boolean = false
  582. @State alphabetHeight: number = 0
  583. public enableShowAlphabet: boolean = true // 是否显示字母表
  584. @State isShowPrecious: boolean = false //播控条显示上一首按钮
  585. //背景两侧流光控制器
  586. @State sceneBgController: HdsSceneController|undefined = deviceInfo.sdkApiVersion>=20
  587. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  588. new HdsSceneController()
  589. .setSceneParams({
  590. backgroundMaskColors: [Color.Green, Color.Red],
  591. firstEdgeFlowLight: {
  592. startPos: 0,
  593. endPos: 0.5,
  594. color: Color.Red
  595. },
  596. secondEdgeFlowLight: {
  597. startPos: 0,
  598. endPos: -0.5,
  599. color: Color.Green
  600. }
  601. }) : undefined;
  602. //背景流光控制器
  603. @State bgController: hdsEffect.ShaderEffectController|undefined = deviceInfo.sdkApiVersion>=20
  604. &&canIUse("SystemCapability.UIDesign.HDSComponent.Core")?
  605. new hdsEffect.ShaderEffectController():undefined;
  606. @State showAddSheet:boolean = false
  607. searchController: SearchController = new SearchController()
  608. @State rightTopImage:Resource = $r('sys.symbol.sort')
  609. @State isEditAudio:boolean = false
  610. @State isExtractAcc:boolean = false
  611. @State isConverter:boolean = false
  612. @State isAIVoiceSeparation:boolean = false
  613. @State isExtractAudio:boolean = false
  614. @State isMergeAudio:boolean = false
  615. @State isCopyFileToDownLoad: boolean = false
  616. @State isChangeTone:boolean = false
  617. @State offHeight: number = 75
  618. @State currentSongList: Array<VideoItem> = []//当前歌单
  619. @Consume currentSongListName:string //当前歌单名称
  620. @Consume @Watch('onIDChange') currentSongListID:string //当前歌单ID
  621. @State isRefreshing: boolean = false;
  622. @State maxRefreshingHeight: number = 100.0;
  623. private contentNode?: ComponentContent<Object> = undefined;
  624. // WebDAV相关实例变量(现在改为从内存读取,不再需要存储)
  625. @State ratioL: number = 1;
  626. @State mediaKuCount: number = 0;
  627. @State albumCount: number = 0;
  628. @State artistCount: number = 0;
  629. @State fastForwardSeconds: string = '10'
  630. @State isShowBackFast: boolean = true//快进快退按钮
  631. @State isCanAuto:boolean = true
  632. @State opacityValueImage: number = 1;
  633. @State tipPopup:boolean = false
  634. @Consume mType: number;
  635. @StorageProp('themeColor') themeColor: string =
  636. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  637. themeMode: number = 0;
  638. @State titleName: string = '首页'
  639. @State textStr: string = ''
  640. // static readonly STR_MUSIC_VIDEO: string = 'Audios';
  641. // private download_path: string = '';
  642. @Consume rootPath: string //音频根目录
  643. @Consume currentPath: string
  644. static readonly STR_LOCK_VIDEO: string = '.私密音频';
  645. static readonly STR_FAC_VIDEO: string = '.我的收藏';
  646. @State lockPath: string = ''
  647. @State favPath: string = ''
  648. static readonly STR_HISTORY_MUSIC: string = '.最近播放';
  649. @State historyPath: string = ''
  650. @State historyList: Array<VideoItem> = []
  651. @Consume isHistory: boolean
  652. static readonly HISTORY_MUSIC: string = 'music_historyList';
  653. private table: MediaTable = new MediaTable(getContext(this))
  654. private playlistTable: PlaylistTable | null = null
  655. private deletionWatcher: FileDeletionWatcher | null = null
  656. @State allPlaylists: Playlist[] = []
  657. @State isZero: boolean = false
  658. @State fileList: Array<string> = []
  659. @State dirList: Array<VideoItem> = []
  660. @Consume videoLocalList:VideoItem[]
  661. @State dataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.videoLocalList)
  662. @State listRefreshKey: number = 0
  663. // @State mediaKuList: Array<VideoItem> = []; //媒体库文件
  664. @StorageProp('mediaKuList') mediaKuList: Array<VideoItem> = []; //媒体库文件
  665. @State artistList: Array<VideoItem> = []; //艺术家文件
  666. @State artistMap: Map<string, VideoItem[]> = new Map(); //艺术家Map
  667. @State albumList: Array<VideoItem> = []; //专辑文件
  668. @State albumMap: Map<string, VideoItem[]> = new Map(); //专辑Map
  669. private mScrollMap: Map<string, number> = new Map(); // 艺术家、专辑名->滚动index
  670. @State imageOpacities: number[] = [];
  671. @Consume isCanBack: boolean
  672. @Consume @Watch('onModeChange') modeType: number; // 0首页,1媒体库,2艺术家,3专辑
  673. @State showSingleLyric: boolean = false
  674. @State sortType: number = 4 //默认排序方式
  675. @State isShowSimi: boolean = false //是否显示私密音频
  676. @State isShowFAV: boolean = true //是否显示我的收藏
  677. @State @Watch('onTopBarhange')isShowTitleBar: boolean = true //是否显示分类导航条
  678. @State isShowAllBar: boolean = true //是否显示播放全部条
  679. @State isShowSingleLineLyric: boolean = false //是否显示单行歌词
  680. @State isShowHistory: boolean = true //是否显示最近播放
  681. @State @Watch('onColorModeChange') isCustomizeBg: boolean = false //自定义背景界面
  682. @State isGridMusic: boolean = false //是否网格布局
  683. @State isCircleBtn: boolean = false //是否圆形播放按钮
  684. @State twoFingerType: number = 3 //双支放大缩小的类型
  685. @State isScrollHide: boolean = false //是否滚动隐藏
  686. @State isSameTimePlay: boolean = false //是否和其他app同时播放
  687. @State isStartAutoPlay: boolean = false //启动后自动播放
  688. @State isShowPlayPageBack: boolean = false //是否显示播放页返回键
  689. @State isShowHeader: boolean = true
  690. @State isPlayListBgGrass: boolean = true //是否播放列表玻璃透明效果
  691. @State isMemoryLastPlay: boolean = false //是否启用应用退出记忆最后一首的播放进度
  692. @State isCoverTopBig: boolean = false //顶部大封面部分手机显示会和播放控制页重叠
  693. @State isSwipe: boolean = false //listItem的左滑开关
  694. @State openSkipSongAnimate: boolean = true//切歌动画效果
  695. @State customizeBgPath: string | undefined = '';
  696. @State isDarkMode: boolean = false
  697. @State lyricTextWeight: number = 400
  698. @State lyricTextWeightPip: number = 400
  699. @State currentSwiperIndex: number = 0
  700. @State blurValue: number = 0 //背景模糊
  701. @State bgBrightness: number = 0 //背景亮度
  702. private listScroller: ListScroller = new ListScroller()
  703. private playListScroller: Scroller = new Scroller()
  704. @State isOneKeyTags:boolean = false
  705. @State isFixMessy:boolean = false
  706. @StorageProp('isLandscape') @Watch('onIsLandscapeChange') isLandscape: boolean = false;
  707. @StorageProp('topSafeHeight') topSafeHeight: number = 0;
  708. @StorageProp('bottomSafeHeight') bottomSafeHeight: number = 0;
  709. @StorageProp('windowWidth') windowWidth: number = 0;
  710. @StorageProp('windowHeight') windowHeight: number = 0;
  711. @StorageProp('isHiCarStatus') isHiCarStatus: boolean = false;
  712. @StorageProp('curDisplayIsHiCar') curDisplayIsHiCar: boolean = false;
  713. private UNKONWN:string = '';
  714. private listArea: Area = {
  715. width: 0,
  716. height: 0,
  717. position: {},
  718. globalPosition: {}
  719. }
  720. @StorageProp('currentColorMode') @Watch('onColorModeChange') currentMode: number =
  721. ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET;
  722. // WebDAV认证信息缓存(作为实例变量,比全局上下文更可靠)
  723. private currentWebDavAuthInfo: WebDavAuthItem | null = null;
  724. //瀑布流的列数横竖屏动态切换
  725. onIsLandscapeChange() {
  726. if(this.isLandscape){
  727. this.columns = 4
  728. }else{
  729. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  730. }
  731. }
  732. onColorModeChange() {
  733. this.isDarkMode = this.currentMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  734. }
  735. //bar导航条显示状态变化,不显示的话把topBarHeight=0
  736. onTopBarhange(){
  737. if(this.isShowTitleBar){
  738. console.log('onecold 导航条显示')
  739. this.topBarHeight = 50
  740. this.offHeight = 75
  741. }else{
  742. console.log('onecold 导航条隐藏')
  743. this.topBarHeight = 0
  744. if(this.twoFingerType!=4){
  745. this.offHeight = 30
  746. }
  747. }
  748. }
  749. //点击某个歌单id发生变化的时候回调
  750. onIDChange(){
  751. console.log('onecold 歌单id发生变化this.currentSongListID='+this.currentSongListID)
  752. console.log('onecold 歌单id发生变化this.currentSongListName='+this.currentSongListName)
  753. if(this.modeType==4){
  754. this.isShowTitleBar = false
  755. this.titleName = this.currentSongListName
  756. this.rightTopImage = $r('sys.symbol.sort')
  757. //获取缓存
  758. const cacheSongs:string =PreferencesUtil.getStringSync(this.currentSongListID+'currentSongList', '')
  759. console.log('onecold 歌单id发生变化获取缓存2 cacheSongs = '+cacheSongs)
  760. if(StrUtil.isNotEmpty(cacheSongs)){
  761. this.currentSongList = JSON.parse(cacheSongs) as VideoItem[]
  762. this.updateListData(this.currentSongList, true)
  763. }
  764. this.doSongListTask()//获取歌单信息
  765. }
  766. }
  767. async doSongListTask() {
  768. // 初始化歌单数据库
  769. const playlistTable = new PlaylistTable(this.context);
  770. // 查询歌单中的所有歌曲
  771. const playlistSongs: PlaylistSong[] = await playlistTable.queryPlaylistSongs(this.currentSongListID);
  772. console.log('onecold 歌单id发生变化获取缓存7 playlistSongs='+playlistSongs.length)
  773. if (ArrayUtil.isEmpty(playlistSongs)) {
  774. this.updateListData([], true)
  775. } else {
  776. this.currentSongList = await convertPlaylistSongsToVideoItems(this.context, playlistSongs);
  777. console.log('onecold 从数据库读取的歌曲为 playlistSongs='+this.currentSongList.length)
  778. this.updateListData(this.currentSongList, true)
  779. if (ArrayUtil.isNotEmpty(this.currentSongList)&&this.currentSongList.length > 100) {
  780. // 只保存前100条记录到缓存中
  781. let canceList = this.currentSongList.slice(0, 100);
  782. PreferencesUtil.putSync(this.currentSongListID+'currentSongList',
  783. JSON.stringify(canceList))
  784. } else {
  785. PreferencesUtil.putSync(this.currentSongListID+'currentSongList', JSON.stringify(this.currentSongList));
  786. }
  787. }
  788. this.isRefreshing = false
  789. }
  790. onModeChange() {
  791. this.isFavMusic = false
  792. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, false)
  793. switch (this.modeType) {
  794. case 0:
  795. this.getSortedFiles(this.currentPath)
  796. break
  797. case 1:
  798. this.rightTopImage = $r('sys.symbol.sort')
  799. this.updateListData(this.mediaKuList)
  800. this.titleName = Utility.resourceToString(this.context,$r('app.string.media_ku'))
  801. break
  802. case 2:
  803. this.rightTopImage = $r('sys.symbol.sort')
  804. this.updateListData(this.artistList)
  805. this.titleName = Utility.resourceToString(this.context,$r('app.string.artist'))
  806. break
  807. case 3:
  808. this.rightTopImage = $r('sys.symbol.sort')
  809. this.updateListData(this.albumList)
  810. this.titleName = Utility.resourceToString(this.context,$r('app.string.album'))
  811. break
  812. }
  813. }
  814. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  815. // @StorageLink('isPlay') isPlay: boolean = false;
  816. @StorageLink('isShowPlay') isShowPlay: boolean = false;
  817. @StorageLink('songList') songList: Array<VideoItem> = [];
  818. @State translateY: number = 0;
  819. @State isShowSheet: boolean = false;
  820. @State isShowSheetView: boolean = false;
  821. @State isShowTimeCloseView: boolean = false;
  822. private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Vertical });
  823. @StorageLink('currIndex') curIndex: number = 0;
  824. @Consume isShowDrawer: boolean;
  825. @Consume offsetX: number;
  826. @State isFac: boolean = false;
  827. @State favList: Array<VideoItem> = []
  828. @Consume isFavMusic: boolean
  829. @State isClickedPLayAll: boolean = false;
  830. private scrollerForlist: ListScroller = new ListScroller();
  831. private knockController: KnockController | undefined = undefined;
  832. // 修改为:
  833. imagesF: ImageFrameInfo[] = CommonConstants.IMAGE_FRAME_INFO;
  834. @StorageProp('animationState') animationState: AnimationStatus = AnimationStatus.Initial
  835. // 缓存机制
  836. private cache: Map<string, Array<VideoItem>> = new Map();
  837. private stringCache: Map<string, string> = new Map(); // 新增字符串缓存
  838. // 持久化缓存
  839. private async saveCacheToStorage() {
  840. const cacheArray = Array.from(this.cache.entries());
  841. const stringCacheArray = Array.from(this.stringCache.entries());
  842. await PreferencesUtil.putSync('music_cache', JSON.stringify(cacheArray));
  843. await PreferencesUtil.putSync('music_string_cache', JSON.stringify(stringCacheArray));
  844. }
  845. // 载入缓存
  846. private async loadCacheFromStorage() {
  847. const cacheString = await PreferencesUtil.getStringSync('music_cache', '');
  848. const stringCacheString = await PreferencesUtil.getStringSync('music_string_cache', ''); // 载入字符串缓存
  849. if (cacheString) {
  850. const cacheArray: [string, Array<VideoItem>][] = JSON.parse(cacheString);
  851. this.cache = new Map(cacheArray);
  852. }
  853. if (stringCacheString) {
  854. const stringCacheArray: [string, string][] = JSON.parse(stringCacheString);
  855. this.stringCache = new Map(stringCacheArray);
  856. }
  857. }
  858. // 查找缓存
  859. private findCache(key: string): Array<VideoItem> | undefined {
  860. return this.cache.get(key);
  861. }
  862. // 查找字符串缓存
  863. private findStringCache(key: string): string | undefined {
  864. return this.stringCache.get(key);
  865. }
  866. // 添加缓存
  867. private addCache(key: string, value: Array<VideoItem>) {
  868. this.cache.set(key, value);
  869. }
  870. // 添加字符串缓存
  871. private addStringCache(key: string, value: string) {
  872. this.stringCache.set(key, value);
  873. }
  874. // 删除缓存
  875. private deleteCache(key: string) {
  876. this.cache.delete(key);
  877. this.saveCacheToStorage()
  878. }
  879. // 删除字符串缓存
  880. private deleteStringCache(key: string) {
  881. this.stringCache.delete(key);
  882. }
  883. // 多选机制
  884. @State selectedFiles: Array<VideoItem> = [];
  885. @State isMultiSelect: boolean = false;
  886. @State isAllSelected: boolean = false;
  887. @State appName: string = ''
  888. @State isHasDir: boolean = false
  889. @State packName: string = ''
  890. context = this.getUIContext().getHostContext() as common.UIAbilityContext
  891. doSwipBack() {
  892. if(this.isSearchMode){
  893. console.info('onecold doSwipBack = ' +this.isSearchMode)
  894. this.isSearchMode = false
  895. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  896. this.searchText = ''
  897. this.getSortedFiles(this.currentPath)
  898. return
  899. }
  900. this.onSearchInput('')
  901. return
  902. }
  903. this.isZero = false
  904. if (this.modeType !== 0 && this.isCanBack) {
  905. this.onModeChange()
  906. this.isCanBack = false
  907. // 返回专辑列表时恢复滚动偏移量,支持列表和网格
  908. setTimeout(() => {
  909. if (this.modeType == 2) {
  910. if (this.isGridMusic||this.twoFingerType==4) {
  911. let lastOffset = this.mScrollMap.get('lastGridArtistScrollOffset') ?? 0
  912. let lastWaterOffset = this.mScrollMap.get('lastWaterArtistScrollOffset') ?? 0
  913. if(this.twoFingerType==4){
  914. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  915. }else{
  916. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  917. }
  918. } else {
  919. let lastOffset = this.mScrollMap.get('lastListArtistScrollOffset') ?? 0
  920. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  921. }
  922. } else if (this.modeType == 3) {
  923. if (this.isGridMusic||this.twoFingerType==4) {
  924. let lastOffset = this.mScrollMap.get('lastGridAlBumScrollOffset') ?? 0
  925. let lastWaterOffset = this.mScrollMap.get('lastWaterAlBumScrollOffset') ?? 0
  926. if(this.twoFingerType==4){
  927. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  928. }else{
  929. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  930. }
  931. } else {
  932. let lastOffset = this.mScrollMap.get('lastListAlBumScrollOffset') ?? 0
  933. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  934. }
  935. }
  936. }, 200)
  937. return
  938. }
  939. if (this.isHistory || this.isFavMusic) {
  940. this.isHistory = false
  941. this.getSortedFiles(this.currentPath)
  942. return
  943. }
  944. if (this.currentPath === this.rootPath || this.modeType !== 0) {
  945. animateTo({ duration: 555 }, () => {
  946. // 动画闭包内控制Image组件的出现和消失
  947. this.isShowDrawer = !this.isShowDrawer
  948. this.offsetX = 0
  949. })
  950. return
  951. }
  952. //返回上一级歌单的滚动位置
  953. setTimeout(() => {
  954. if (this.modeType == 0) {
  955. if (this.isGridMusic||this.twoFingerType==4) {
  956. let lastOffset = this.mScrollMap.get('lastGridDirScrollOffset') ?? 0
  957. let lastWaterOffset = this.mScrollMap.get('lastWaterDirScrollOffset') ?? 0
  958. if(this.twoFingerType==4){
  959. this.waterScroller.scrollTo({ xOffset: 0, yOffset: lastWaterOffset })
  960. }else{
  961. this.scroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  962. }
  963. } else {
  964. let lastOffset = this.mScrollMap.get('lastListDirScrollOffset') ?? 0
  965. this.listScroller.scrollTo({ xOffset: 0, yOffset: lastOffset })
  966. }
  967. }
  968. }, 300)
  969. this.currentPath = Utility.getParentDirectory(this.currentPath)
  970. Logger.info('this.currentPath2 = ' + this.currentPath)
  971. this.getSortedFiles(this.currentPath)
  972. }
  973. // 组件生命周期
  974. aboutToAppear() {
  975. console.info('onecold aboutToAppear sdkApiVersion = '+deviceInfo.sdkApiVersion)
  976. if(ArrayUtil.isNotEmpty(this.videoLocalList)&&this.modeType==0){
  977. this.updateListData(this.videoLocalList)
  978. }
  979. // 初始化 PlaylistTable
  980. this.playlistTable = new PlaylistTable(getContext(this))
  981. this.sonTwoFingerType = PreferencesUtil.getNumberSync('sonTwoFingerType', 3);
  982. this.columns = PreferencesUtil.getNumberSync('lastColumns', 2);
  983. if(PreferencesUtil.getBooleanSync('isFirstTiped',true)){
  984. this.tipPopup = !this.tipPopup
  985. PreferencesUtil.putSync('isFirstTiped',false)
  986. }
  987. this.initSetting()
  988. this.UNKONWN = Utility.resourceToString(this.context, $r('app.string.unknown'));
  989. Utility.getAppName(getContext(this)).then((appName: string) => {
  990. this.appName = appName
  991. })
  992. this.packName = AppUtil.getBundleName()
  993. this.tabSelectedIndexes[0] = this.modeType//SegmentButton的索引
  994. this.loadCacheFromStorage(); // 加载文件夹缓存
  995. // 在首页初始化时读取媒体库,艺术家,专辑等缓存数据
  996. this.initLoadCache()
  997. this.mkDownLoadDir()
  998. let eventMusic: emitter.InnerEvent = { eventId: EventConstants.EVENT_AUDIO_OPEN }
  999. // 监听广播事件(打开其他应用处理)
  1000. emitter.on(eventMusic, (eventData: emitter.EventData) => {
  1001. this.saveVideoDatas([eventData.data?.message], true)
  1002. });
  1003. //侧滑广播接收时间
  1004. let eventUpdateSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_UPDATE }
  1005. // 监听广播事件(打开其他应用处理)
  1006. emitter.on(eventUpdateSwipeBack, (eventData: emitter.EventData) => {
  1007. animateTo({ duration: 555 }, () => {
  1008. this.doSwipBack()
  1009. })
  1010. });
  1011. //ScanFilePage广播接收时间
  1012. let eventScanUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_SCAN_UPDATE }
  1013. // 监听ScanFilePage广播事件(更新数据库)
  1014. emitter.on(eventScanUpdate, (eventData: emitter.EventData) => {
  1015. this.doUpdateData()
  1016. });
  1017. // 监听歌单播放请求事件
  1018. let eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY }
  1019. emitter.on(eventPlaylistPlay, async (eventData: emitter.EventData) => {
  1020. const data = eventData.data as Record<string, Object>
  1021. if (!data) {
  1022. Logger.error('heanup eventPlaylistPlay: eventData.data is undefined or null')
  1023. return
  1024. }
  1025. // 检查歌单播放数据结构
  1026. if (data.playlistId && data.songFilePaths && data.startIndex !== undefined) {
  1027. const playlistData: PlaylistEventData = {
  1028. playlistId: data.playlistId as string,
  1029. playlistName: data.playlistName as string,
  1030. songCount: data.songCount as number,
  1031. startIndex: data.startIndex as number,
  1032. songFilePaths: data.songFilePaths as string[]
  1033. }
  1034. await this.handlePlaylistPlayRequest(
  1035. playlistData.playlistId,
  1036. playlistData.playlistName,
  1037. playlistData.songFilePaths,
  1038. playlistData.startIndex
  1039. )
  1040. return
  1041. }
  1042. Logger.error('heanup eventPlaylistPlay: 接收到无效的数据结构')
  1043. });
  1044. let eventRefreshSort: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_REFRESH_SORT }
  1045. // 监听广播事件(通用设置配置更新)
  1046. emitter.on(eventRefreshSort, (eventData: emitter.EventData) => {
  1047. if(this.modeType ==4){
  1048. this.doSongListTask()//获取歌单信息
  1049. }
  1050. });
  1051. let eventSetting: emitter.InnerEvent = { eventId: EventConstants.EVENT_SETTING_UPDATE }
  1052. // 监听广播事件(通用设置配置更新)
  1053. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  1054. this.doChangeSetting()
  1055. });
  1056. let event: Callback<InterruptEvent> = (event) => {
  1057. // LogUtils.getInstance().LOGI(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`);
  1058. console.info(`onecold 与其他应用音频冲突 被截断点event: ${JSON.stringify(event)}`)
  1059. this.savePlaybackPosition()
  1060. if (event.hintType === InterruptHintType.INTERRUPT_HINT_PAUSE) {
  1061. this.pause();
  1062. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_RESUME) {
  1063. console.info(`onecold audioInterrupt startPlayOrResumePlay: ${JSON.stringify(event)}`)
  1064. console.info('onecold startPlayOrResumePlay 514')
  1065. this.startPlayOrResumePlay();
  1066. } else if (event.hintType === InterruptHintType.INTERRUPT_HINT_STOP) {
  1067. this.stop();
  1068. }
  1069. }
  1070. this.mIjkMediaPlayer.on('audioInterrupt', event);
  1071. // 音频设备断连回调处理
  1072. // let deviceChangeEvent: Callback<InterruptEvent> = (event) => {
  1073. // LogUtils.getInstance().LOGI(`Heanup deviceChange event: ${JSON.stringify(event)}`);
  1074. // if (event.reason === DeviceChangeReason.REASON_NEW_DEVICE_AVAILABLE) { // 音频设备连接
  1075. //
  1076. // } else if (event.reason === DeviceChangeReason.REASON_OLD_DEVICE_UNAVAILABLE) { // 音频设备断开连接
  1077. // this.pause();
  1078. // }
  1079. // }
  1080. // // 订阅音频设备断开和连接事件
  1081. // this.mIjkMediaPlayer.on('deviceChange', deviceChangeEvent);
  1082. const eventPause: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAY_PAUSE }
  1083. // 监听广播事件(hicar断开暂停播放)
  1084. emitter.on(eventPause, (eventData: emitter.EventData) => {
  1085. this.pause();
  1086. });
  1087. this.makeWorker()
  1088. //折叠屏的屏幕显示模式变化
  1089. display.on('foldDisplayModeChange', (data) => {
  1090. this.doChangeBarHeight()
  1091. });
  1092. display.on('foldStatusChange', (data) => {
  1093. Logger.info('onecold foldStatusChange ')
  1094. });
  1095. this.isCoverRectangle = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_RECTANGLE, true)
  1096. // 读取 themeMode 并同步 currentColorMode
  1097. this.themeMode = PreferencesUtil.getNumberSync(SettingPage.THEME_MODE, 0)
  1098. this.applyThemeMode(this.themeMode)
  1099. let themeColor = PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  1100. AppStorage.setOrCreate('themeColor', themeColor);
  1101. this.themeColor = themeColor;
  1102. this.doChangeSetting()
  1103. this.windowClass.on('windowSizeChange', (size) => {
  1104. LogUtil.info('onecold windowSizeChange')
  1105. this.doChangeBarHeight()
  1106. let viewWidth = px2vp(size.width);
  1107. let viewHeight = px2vp(size.height);
  1108. if(this.isPhoneLan()){
  1109. this.is_auto_hide_progress = false
  1110. if(this.isHiCar()){
  1111. return
  1112. }
  1113. setTimeout(() => {
  1114. this.is_auto_hide_progress = true
  1115. }, 6000)
  1116. }else{
  1117. this.startAutoHide()
  1118. }
  1119. });
  1120. this.eventHub.on('onStateChange', (fg: boolean) => {
  1121. if (fg && this.curState === 'STARTED') {
  1122. this.stopPip();
  1123. }
  1124. });
  1125. }
  1126. //载入媒体库,艺术家,专辑等缓存
  1127. initLoadCache(){
  1128. this.mediaKuCount = PreferencesUtil.getNumberSync('mediaKuCount', 0)
  1129. this.artistCount = PreferencesUtil.getNumberSync('artistCount', 0)
  1130. this.albumCount = PreferencesUtil.getNumberSync('albumCount', 0)
  1131. let cachedListStr:string = PreferencesUtil.getStringSync('mediaKuList', '[]');
  1132. let cachedList = JSON.parse(cachedListStr) as Array<VideoItem>;
  1133. if(ArrayUtil.isNotEmpty(cachedList)){
  1134. this.mediaKuList = cachedList
  1135. if(this.modeType==1){
  1136. this.updateListData(this.mediaKuList)
  1137. }
  1138. }
  1139. let artistListStr:string = PreferencesUtil.getStringSync('artistList', '[]');
  1140. let artistCachedList = JSON.parse(artistListStr) as Array<VideoItem>;
  1141. if(ArrayUtil.isNotEmpty(artistCachedList)){
  1142. this.artistList = artistCachedList
  1143. let artistMapStr:string = PreferencesUtil.getStringSync('artistMap', '[]');
  1144. const parsedArray = JSON.parse(artistMapStr) as [string, VideoItem[]][];
  1145. this.artistMap = new Map(parsedArray);
  1146. // this.artistMap = JSON.parse(artistMapStr) as Map<string, VideoItem[]>;
  1147. if(this.modeType==2){
  1148. this.updateListData(this.artistList)
  1149. }
  1150. }
  1151. let albumListStr:string = PreferencesUtil.getStringSync('albumList', '[]');
  1152. let albumCachedList = JSON.parse(albumListStr) as Array<VideoItem>;
  1153. if(ArrayUtil.isNotEmpty(albumCachedList)){
  1154. this.albumList = albumCachedList
  1155. let albumMapStr:string = PreferencesUtil.getStringSync('albumMap', '[]');
  1156. const parsedArray = JSON.parse(albumMapStr) as [string, VideoItem[]][];
  1157. this.albumMap = new Map(parsedArray);
  1158. if(this.modeType==3){
  1159. this.updateListData(this.albumList)
  1160. }
  1161. }
  1162. }
  1163. startAutoHide() {
  1164. if(this.isHiCar()){
  1165. return
  1166. }
  1167. if(PreferencesUtil.getBooleanSync(SettingPage.IS_AUTO_HIDE_PROGRESS,false)){
  1168. console.info('onecold startAutoHide')
  1169. this.is_auto_hide_progress = false
  1170. setTimeout(() => {
  1171. this.is_auto_hide_progress = true
  1172. }, 6000)
  1173. }
  1174. }
  1175. applyThemeMode(mode: number) {
  1176. let colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET
  1177. if (mode === 1) {
  1178. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT
  1179. } else if (mode === 2) {
  1180. colorMode = ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1181. }
  1182. AppStorage.setOrCreate('currentColorMode', colorMode)
  1183. AppStorage.setOrCreate('isDarkMode', colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK)
  1184. PreferencesUtil.putSync(SettingPage.THEME_MODE, mode)
  1185. AppStorage.setOrCreate('themeMode', mode)
  1186. this.isDarkMode = colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK
  1187. // 只有强制浅色/深色时才主动设置
  1188. const context = getContext(this) as common.UIAbilityContext
  1189. context.getApplicationContext().setColorMode(colorMode)
  1190. }
  1191. initSetting() {
  1192. this.isShowPrecious = PreferencesUtil.getBooleanSync('isShowPrecious', false)
  1193. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1194. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  1195. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  1196. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, false)
  1197. this.isScrollHide = PreferencesUtil.getBooleanSync(SettingPage.IS_SCROLL_HIDE, false)
  1198. this.isSameTimePlay = PreferencesUtil.getBooleanSync(SettingPage.IS_SAMETIME_PLAY, false)
  1199. this.isSavePlayMode = PreferencesUtil.getBooleanSync(SettingPage.iS_SAVE_PLAY_MODE, true)
  1200. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  1201. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  1202. this.isStartAutoPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_START_AUTO_PLAY, false)
  1203. this.isMemoryLastPlay = PreferencesUtil.getBooleanSync(SettingPage.iS_MEMORY_LAST_PLAY, false)
  1204. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, false)
  1205. this.isShowAllBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_ALLBAR, true)
  1206. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 2)
  1207. this.isCoverTop = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP, true)
  1208. this.isCircleBtn = PreferencesUtil.getBooleanSync(SettingPage.IS_CIRCLE_BTN, true)
  1209. this.isShowPlayPageBack = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_PLAYPAGE_BACK, true)
  1210. this.isCoverTopBig = PreferencesUtil.getBooleanSync(SettingPage.IS_COVER_TOP_BIG, false)
  1211. this.isShowSingleLineLyric = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SLLYRIC, false)
  1212. this.longPressSpeed = PreferencesUtil.getNumberSync(SettingPage.LONG_PRESS_SPEED, 3)
  1213. this.isPlayListBgGrass = PreferencesUtil.getBooleanSync(SettingPage.IS_PLAYLIST_BG_GRASS, true)
  1214. this.isShowHeader = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HEADER, true)
  1215. this.volume = PreferencesUtil.getNumberSync('DefalutVolume', this.volume)
  1216. this.isSwipe = PreferencesUtil.getBooleanSync(SettingPage.IS_SWIPE, true)
  1217. this.openSkipSongAnimate = PreferencesUtil.getBooleanSync(SettingPage.OPEN_SKIPSONG_ANIMATE, true)
  1218. this.volumeSmall = PreferencesUtil.getBooleanSync('volumeSmall', false)
  1219. this.autoParseMusicName = PreferencesUtil.getBooleanSync('autoParseMusicName', true)
  1220. this.isShowFileName = PreferencesUtil.getBooleanSync('isShowFileName', false)
  1221. this.isLongNameRoLL = PreferencesUtil.getBooleanSync('isLongNameRoLL', true)
  1222. this.fastForwardSeconds = PreferencesUtil.getStringSync('fastForwardSeconds', '10')
  1223. this.isShowBackFast = PreferencesUtil.getBooleanSync('isShowBackFast', false)
  1224. this.isCopyFileToDownLoad = PreferencesUtil.getBooleanSync(SettingPage.IS_COPYFILE_TO_DOWNLOAD, false)
  1225. if(this.volumeSmall){
  1226. this.volume = 0.5
  1227. }else{
  1228. this.volume = 1
  1229. }
  1230. //如果是hicar连接状态,这些都是false
  1231. if(this.isHiCar()){
  1232. this.isShowTitleBar = false//不显示导航栏
  1233. this.columns=4
  1234. if(!(this.windowWidth>1800&&this.windowHeight>=1200))//小屏幕不可以Grid
  1235. {
  1236. this.isShowHeader = false//二级菜单不显示头部
  1237. this.isGridMusic= false//用list不用网格
  1238. this.isCoverTopBig = false
  1239. }
  1240. this.isShowPlayPageBack = true //播放页返回键要显示,方便驾驶员操作
  1241. }
  1242. if (this.isSavePlayMode) {
  1243. this.playType = PreferencesUtil.getNumberSync('musicPlayType', 0)
  1244. }
  1245. }
  1246. doChangeSetting() {
  1247. this.initSetting()
  1248. this.deleteCache(this.currentPath)
  1249. if (this.modeType === 0) {
  1250. this.getSortedFiles(this.currentPath)
  1251. }
  1252. }
  1253. doChangeBarHeight() {
  1254. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  1255. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  1256. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  1257. this.setBarHeightNormal()
  1258. }
  1259. }
  1260. onPageShow() {
  1261. this.knockController?.immersiveListening();
  1262. app.setImageCacheCount(100);
  1263. // 设置解码前图片数据内存缓存上限为100MB (100MB=100*1024*1024B=104857600B)
  1264. app.setImageRawDataCacheSize(104857600);
  1265. Logger.info('onecold onPageShow currentBreakpoint= ' + this.currentBreakpoint)
  1266. }
  1267. //开启线程查看各个数据库
  1268. makeWorker() {
  1269. setTimeout(() => {
  1270. if (PreferencesUtil.getBooleanSync('isFirstApp', true)) {
  1271. ToastUtil.showToast('请到文件扫描页面导入音乐!')
  1272. //发送worker通知扫描文件入库,用户反馈4000多首用这个方法扫描会闪退。
  1273. // workerInstance.postMessage({
  1274. // code: 1,
  1275. // data1: this.context,
  1276. // data2: this.rootPath,
  1277. // data3: this.lockPath,
  1278. // data4: PreferencesUtil.getStringSync('COVER_API', ''),
  1279. // data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  1280. // });
  1281. PreferencesUtil.putSync('isFirstApp', false)
  1282. } else {
  1283. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1284. workerInstance.postMessage({ code: 3, data: this.context });
  1285. workerInstance.postMessage({ code: 4, data: this.context });
  1286. this.getHistoryList(false)
  1287. }
  1288. }, 1000)
  1289. workerInstance.onmessage = (e: MessageEvents): void => {
  1290. switch (e.data.code) {
  1291. case 101: //第一次扫描文件夹入库
  1292. ToastUtil.showToast('刷新同步数据库成功!')
  1293. Logger.info('onecold 扫描数据库结束 this.mediaKuList length= ' + this.mediaKuList.length)
  1294. this.doAllUpdateData()
  1295. break;
  1296. case 102: //查询媒体库列表
  1297. this.isRefreshing = false
  1298. this.mediaKuList = e.data.data
  1299. Logger.info('onecold 查询媒体库列表 this.mediaKuList length= ' + this.mediaKuList.length)
  1300. Utility.doSortListAscending(this.mediaKuList)
  1301. AppStorage.setOrCreate('mediaKuList', this.mediaKuList);
  1302. if (this.modeType === 1) {
  1303. this.updateListData(this.mediaKuList)
  1304. }
  1305. PreferencesUtil.putSync('mediaKuCount', this.mediaKuList.length)
  1306. // 处理媒体库前100条记录,列表长度并存储到PreferencesUtil
  1307. if (ArrayUtil.isNotEmpty(this.mediaKuList)&&this.mediaKuList.length > 100) {
  1308. // 只保存前100条记录到缓存中
  1309. let truncatedList = this.mediaKuList.slice(0, 100);
  1310. PreferencesUtil.putSync('mediaKuList', JSON.stringify(truncatedList));
  1311. } else {
  1312. PreferencesUtil.putSync('mediaKuList', JSON.stringify(this.mediaKuList));
  1313. }
  1314. break;
  1315. case 103: //收到查询艺术家列表
  1316. this.isRefreshing = false
  1317. this.artistMap = e.data.data1;
  1318. this.artistList = e.data.data2;
  1319. PreferencesUtil.putSync('artistCount', this.artistList.length)
  1320. // 处理艺术家前100条记录,列表长度并存储到PreferencesUtil
  1321. if (ArrayUtil.isNotEmpty(this.artistList)&&this.artistList.length > 100) {
  1322. // 只保存前100条记录到缓存中
  1323. let truncatedList = this.artistList.slice(0, 100);
  1324. PreferencesUtil.putSync('artistList', JSON.stringify(truncatedList));
  1325. } else {
  1326. PreferencesUtil.putSync('artistList', JSON.stringify(this.artistList));
  1327. }
  1328. // 处理并缓存前60条艺术家数据
  1329. const sortedEntries = Array.from(this.artistMap.entries())
  1330. .sort((a, b) => b[1].length - a[1].length)
  1331. .slice(0, 60);
  1332. PreferencesUtil.putSync('artistMap', JSON.stringify(sortedEntries));
  1333. break;
  1334. case 104: //收到查询专辑列表
  1335. this.isRefreshing = false
  1336. this.albumMap = e.data.data1;
  1337. this.albumList = e.data.data2
  1338. //查询完毕在启动是否自动播放
  1339. if (this.isStartAutoPlay&&this.isCanAuto) {
  1340. this.isCanAuto = false
  1341. console.info('onecold startPlayOrResumePlay 757')
  1342. this.startPlayOrResumePlay()
  1343. }
  1344. PreferencesUtil.putSync('albumCount', this.albumList.length)
  1345. // 处理专辑前100条记录,列表长度并存储到PreferencesUtil
  1346. if (ArrayUtil.isNotEmpty(this.albumList)&&this.albumList.length > 100) {
  1347. // 只保存前100条记录到缓存中
  1348. let truncatedList = this.albumList.slice(0, 100);
  1349. PreferencesUtil.putSync('albumList', JSON.stringify(truncatedList));
  1350. } else {
  1351. PreferencesUtil.putSync('albumList', JSON.stringify(this.albumList));
  1352. }
  1353. const mapArrayAlbum = Array.from(this.albumMap.entries())
  1354. .sort((a, b) => b[1].length - a[1].length)
  1355. .slice(0, 60);
  1356. PreferencesUtil.putSync('albumMap', JSON.stringify(mapArrayAlbum));
  1357. break;
  1358. case 105: // 缓存完成后返回的元数据
  1359. this.handleWorkerMetadataPayload(e.data.data as WorkerMetadataPayload);
  1360. break;
  1361. case 106: // 编辑音乐元数据和封面完成
  1362. this.handleEditMusicResult(e.data);
  1363. break;
  1364. }
  1365. };
  1366. // 在调用terminate后,执行onexit
  1367. workerInstance.onexit = (code) => {
  1368. metadataExtractionInFlight.clear();
  1369. Logger.info(TAG, 'workerInstance 线程已退出,code: ' + code);
  1370. }
  1371. workerInstance.onerror = (err: ErrorEvent) => {
  1372. metadataExtractionInFlight.clear();
  1373. console.error('workerInstance 线程执行发生异常: ' + err.message)
  1374. }
  1375. }
  1376. private handleWorkerMetadataPayload(payload: WorkerMetadataPayload | undefined): void {
  1377. if (!payload || !payload.originFilePath) {
  1378. return;
  1379. }
  1380. metadataExtractionInFlight.delete(payload.originFilePath);
  1381. if (payload.error) {
  1382. Logger.warn(TAG, `缓存文件元数据解析失败: ${payload.error}`);
  1383. return;
  1384. }
  1385. this.applyMetadataToCollections(payload.originFilePath, payload);
  1386. }
  1387. private applyMetadataToCollections(filePath: string, payload: WorkerMetadataPayload): void {
  1388. const targets: Array<VideoItem> = [];
  1389. let mainListUpdated = false;
  1390. let playlistUpdated = false;
  1391. if (this.currentSong && this.currentSong.filePath === filePath) {
  1392. targets.push(this.currentSong);
  1393. }
  1394. const collectFromList = (list?: Array<VideoItem>, markUpdated?: () => void) => {
  1395. if (!list || list.length === 0) {
  1396. return;
  1397. }
  1398. const found = Utility.getItemByFilePath(list, filePath);
  1399. if (found) {
  1400. markUpdated?.();
  1401. targets.push(found);
  1402. }
  1403. };
  1404. collectFromList(this.videoLocalList, () => {
  1405. mainListUpdated = true;
  1406. });
  1407. collectFromList(this.songList, () => {
  1408. playlistUpdated = true;
  1409. });
  1410. collectFromList(this.historyList);
  1411. collectFromList(this.favList);
  1412. const remoteManager = RemoteDriveManager.getInstance();
  1413. collectFromList(remoteManager.webDavSongs);
  1414. const updated = new Set<VideoItem>();
  1415. const remoteMetadataUpdates: Map<string, WebDavMetadataUpdatePayload> = new Map();
  1416. for (let i = 0; i < targets.length; i++) {
  1417. const target = targets[i];
  1418. if (!target || updated.has(target)) {
  1419. continue;
  1420. }
  1421. updated.add(target);
  1422. this.mergeVideoItemWithPayload(target, payload);
  1423. if (isRemoteCloudType(target.type) && StrUtil.isNotEmpty(target.filePath)) {
  1424. remoteMetadataUpdates.set(target.filePath, {
  1425. filePath: target.filePath,
  1426. pixelMapPath: target.pixelMapPath,
  1427. name: target.name,
  1428. artist: target.artist
  1429. });
  1430. }
  1431. }
  1432. if (this.currentSong && this.currentSong.filePath === filePath) {
  1433. this.mergeVideoItemWithPayload(this.currentSong, payload);
  1434. if (payload.name) {
  1435. this.name = payload.name;
  1436. }
  1437. if (payload.artist) {
  1438. this.artist = payload.artist;
  1439. }
  1440. if (payload.pixelMapPath) {
  1441. this.cover = payload.pixelMapPath;
  1442. }
  1443. if (payload.lyricContent) {
  1444. this.applyInlineLyricContent(payload.lyricContent);
  1445. }
  1446. this.currentSong = cloneVideoItem(this.currentSong);
  1447. AppStorage.setOrCreate('currentSong', this.currentSong);
  1448. }
  1449. const primaryTarget = targets.length > 0 ? targets[0] : undefined;
  1450. if (primaryTarget) {
  1451. this.persistRemoteMetadataToDb(primaryTarget).catch((error: Error) => {
  1452. Logger.error(TAG, `缓存元数据持久化失败: ${error.message}`);
  1453. });
  1454. }
  1455. if (remoteMetadataUpdates.size > 0) {
  1456. const eventUpdate: emitter.InnerEvent = { eventId: EventConstants.EVENT_WEBDAV_METADATA_UPDATED };
  1457. emitter.emit(eventUpdate, { data: Array.from(remoteMetadataUpdates.values()) });
  1458. }
  1459. this.refreshLazyListViews(mainListUpdated, playlistUpdated);
  1460. }
  1461. private handleEditMusicResult(result: WorkerEditMusicResult): void {
  1462. // 关闭进度条
  1463. DialogHelper.closeLoading();
  1464. if (result.success) {
  1465. console.log("heanup 编辑信息成功,数据库已同步");
  1466. if (result.coverResult) {
  1467. ToastUtil.showToast('内嵌封面成功');
  1468. }
  1469. ToastUtil.showToast('内嵌音乐标签成功');
  1470. this.isShowMoreView = false;
  1471. this.name = this.titleStr;
  1472. // 同步当前播放的歌曲信息
  1473. if (this.editingItem && this.editingItem.filePath == this.currentSong?.filePath) {
  1474. this.currentSong.name = this.titleStr;
  1475. this.artist = this.artistStr;
  1476. this.currentSong.artist = this.artistStr;
  1477. this.currentSong.album = this.ablumStr;
  1478. this.currentSong.year = this.yearStr;
  1479. this.currentSong.genre = this.genreStr;
  1480. this.currentSong.track = this.trackStr;
  1481. this.currentSong.lyricContent = this.lyricConStr;
  1482. this.currentSong.ALBUMARTIST = this.albumArtistStr;
  1483. this.currentSong.COMPOSER = this.composerStr;
  1484. this.currentSong.LYRICIST = this.lyricistStr;
  1485. this.currentSong.COMMENT = this.commentStr;
  1486. }
  1487. // if (result.needRefreshList && this.modeType == 0) {
  1488. // this.deleteCache(this.currentPath);
  1489. // this.getSortedFiles(this.currentPath);
  1490. // }
  1491. // 同步编辑字段到本地列表
  1492. if (this.editingItem) {
  1493. this.syncEditedFields(this.editingItem);
  1494. this.syncListsAfterEdit(this.editingItem.filePath);
  1495. this.doUpateEditedFields(this.editingItem);
  1496. }
  1497. // 清理临时变量
  1498. this.longItemFilePath = '';
  1499. this.tempLyricContent = '';
  1500. this.isShowEdit = false;
  1501. this.imagePathStr = '';
  1502. } else {
  1503. console.error("heanup 编辑信息失败: " + result.error);
  1504. ToastUtil.showToast('编辑失败: ' + (result.error || '未知错误'));
  1505. // 清理临时变量
  1506. this.longItemFilePath = '';
  1507. this.tempLyricContent = '';
  1508. this.isShowEdit = false;
  1509. this.imagePathStr = '';
  1510. }
  1511. }
  1512. private assignStringMetadata(target: VideoItem, key: keyof VideoItem, value?: string | null, allowEmpty = false): void {
  1513. if (value === undefined || value === null) {
  1514. return;
  1515. }
  1516. const text = value.toString();
  1517. if (!allowEmpty && text.trim().length === 0) {
  1518. return;
  1519. }
  1520. Reflect.set(target, key as string, value);
  1521. }
  1522. private assignNumberMetadata(target: VideoItem, key: keyof VideoItem, value?: number | null): void {
  1523. if (value === undefined || value === null || Number.isNaN(value)) {
  1524. return;
  1525. }
  1526. Reflect.set(target, key as string, value);
  1527. }
  1528. private mergeVideoItemWithPayload(target: VideoItem, payload: WorkerMetadataPayload): void {
  1529. if (!target || !payload) {
  1530. return;
  1531. }
  1532. this.assignStringMetadata(target, 'name', payload.name);
  1533. this.assignStringMetadata(target, 'artist', payload.artist);
  1534. this.assignStringMetadata(target, 'album', payload.album);
  1535. this.assignStringMetadata(target, 'bit_rate', payload.bit_rate);
  1536. this.assignStringMetadata(target, 'duration', payload.duration);
  1537. this.assignStringMetadata(target, 'sampleRate', payload.sampleRate);
  1538. this.assignStringMetadata(target, 'mimeType', payload.mimeType);
  1539. this.assignStringMetadata(target, 'size', payload.size);
  1540. this.assignStringMetadata(target, 'pixelMapPath', payload.pixelMapPath);
  1541. this.assignStringMetadata(target, 'lyricContent', payload.lyricContent, true);
  1542. this.assignStringMetadata(target, 'genre', payload.genre);
  1543. this.assignStringMetadata(target, 'track', payload.track);
  1544. this.assignStringMetadata(target, 'bits_per_raw_sample', payload.bits_per_raw_sample);
  1545. this.assignStringMetadata(target, 'channels', payload.channels);
  1546. this.assignStringMetadata(target, 'channel_layout', payload.channel_layout);
  1547. this.assignStringMetadata(target, 'start_time', payload.start_time);
  1548. this.assignStringMetadata(target, 'year', payload.year);
  1549. this.assignStringMetadata(target, 'disc', payload.disc);
  1550. this.assignStringMetadata(target, 'ALBUMARTIST', payload.ALBUMARTIST);
  1551. this.assignStringMetadata(target, 'COMPOSER', payload.COMPOSER);
  1552. this.assignStringMetadata(target, 'LYRICIST', payload.LYRICIST);
  1553. this.assignStringMetadata(target, 'COMMENT', payload.COMMENT, true);
  1554. this.assignNumberMetadata(target, 'videoSize', payload.videoSize);
  1555. this.assignNumberMetadata(target, 'probe_score', payload.probe_score);
  1556. this.assignNumberMetadata(target, 'nb_streams', payload.nb_streams);
  1557. this.assignNumberMetadata(target, 'nb_programs', payload.nb_programs);
  1558. }
  1559. private mergeVideoItemFromSource(target: VideoItem, source: VideoItem): void {
  1560. if (!target || !source) {
  1561. return;
  1562. }
  1563. this.assignStringMetadata(target, 'name', source.name);
  1564. this.assignStringMetadata(target, 'artist', source.artist);
  1565. this.assignStringMetadata(target, 'album', source.album);
  1566. this.assignStringMetadata(target, 'bit_rate', source.bit_rate);
  1567. this.assignStringMetadata(target, 'duration', source.duration);
  1568. this.assignStringMetadata(target, 'sampleRate', source.sampleRate);
  1569. this.assignStringMetadata(target, 'trackCount', source.trackCount);
  1570. this.assignStringMetadata(target, 'mimeType', source.mimeType);
  1571. this.assignStringMetadata(target, 'size', source.size);
  1572. this.assignStringMetadata(target, 'pixelMapPath', source.pixelMapPath);
  1573. this.assignStringMetadata(target, 'lyricContent', source.lyricContent, true);
  1574. this.assignStringMetadata(target, 'genre', source.genre);
  1575. this.assignStringMetadata(target, 'track', source.track);
  1576. this.assignStringMetadata(target, 'bits_per_raw_sample', source.bits_per_raw_sample);
  1577. this.assignStringMetadata(target, 'channels', source.channels);
  1578. this.assignStringMetadata(target, 'channel_layout', source.channel_layout);
  1579. this.assignStringMetadata(target, 'start_time', source.start_time);
  1580. this.assignStringMetadata(target, 'year', source.year);
  1581. this.assignStringMetadata(target, 'disc', source.disc);
  1582. this.assignStringMetadata(target, 'ALBUMARTIST', source.ALBUMARTIST);
  1583. this.assignStringMetadata(target, 'COMPOSER', source.COMPOSER);
  1584. this.assignStringMetadata(target, 'LYRICIST', source.LYRICIST);
  1585. this.assignStringMetadata(target, 'COMMENT', source.COMMENT, true);
  1586. this.assignNumberMetadata(target, 'videoSize', source.videoSize);
  1587. this.assignNumberMetadata(target, 'probe_score', source.probe_score);
  1588. this.assignNumberMetadata(target, 'nb_streams', source.nb_streams);
  1589. this.assignNumberMetadata(target, 'nb_programs', source.nb_programs);
  1590. if (source.remote_rel_path && StrUtil.isEmpty(target.remote_rel_path)) {
  1591. target.remote_rel_path = source.remote_rel_path;
  1592. }
  1593. }
  1594. private async hydrateRemoteSongFromDb(item: VideoItem | undefined): Promise<void> {
  1595. if (!item || !isRemoteCloudType(item.type)) {
  1596. return;
  1597. }
  1598. const storagePath = item.remote_rel_path || WebDavUrlUtil.toStoragePath(item.filePath);
  1599. if (!storagePath) {
  1600. return;
  1601. }
  1602. try {
  1603. const cached = await this.table.queryVideoByFilePath(storagePath);
  1604. if (!cached) {
  1605. return;
  1606. }
  1607. this.mergeVideoItemFromSource(item, cached);
  1608. if (StrUtil.isEmpty(item.remote_rel_path)) {
  1609. item.remote_rel_path = storagePath;
  1610. }
  1611. if (item === this.currentSong) {
  1612. if (StrUtil.isNotEmpty(item.name)) {
  1613. this.name = item.name;
  1614. }
  1615. if (StrUtil.isNotEmpty(item.artist)) {
  1616. this.artist = item.artist!;
  1617. }
  1618. if (StrUtil.isNotEmpty(item.pixelMapPath)) {
  1619. this.cover = item.pixelMapPath!;
  1620. }
  1621. if (StrUtil.isNotEmpty(item.lyricContent) && StrUtil.isEmpty(this.lyricContent)) {
  1622. this.applyInlineLyricContent(item.lyricContent as string);
  1623. }
  1624. }
  1625. } catch (error) {
  1626. Logger.error(TAG, `hydrateRemoteSongFromDb 失败: ${(error as Error).message}`);
  1627. }
  1628. }
  1629. private applyInlineLyricContent(content: string): void {
  1630. if (StrUtil.isEmpty(content)) {
  1631. return;
  1632. }
  1633. this.lyricContent = content;
  1634. const lines = content.split('\n').map(line => line.trim());
  1635. const lyric = this.parser.parse(lines);
  1636. this.lyricController.setLyric(lyric);
  1637. this.lyricControllerXF.setLyric(lyric);
  1638. this.lyricControllerSingle.setLyric(lyric);
  1639. }
  1640. private extractParentPathFromStoragePath(path: string): string {
  1641. if (!path) {
  1642. return '';
  1643. }
  1644. const lastSlash = path.lastIndexOf('/');
  1645. if (lastSlash <= 0) {
  1646. return '';
  1647. }
  1648. return path.substring(0, lastSlash);
  1649. }
  1650. private resolveRemoteStoragePath(target: VideoItem): string | null {
  1651. if (!target || !isRemoteCloudType(target.type)) {
  1652. return null;
  1653. }
  1654. if (isWebDavType(target.type)) {
  1655. const storagePath = target.remote_rel_path || WebDavUrlUtil.toStoragePath(target.filePath);
  1656. if (storagePath) {
  1657. target.remote_rel_path = storagePath;
  1658. return storagePath;
  1659. }
  1660. return null;
  1661. }
  1662. if (target.remote_rel_path && target.remote_rel_path.length > 0) {
  1663. return target.remote_rel_path;
  1664. }
  1665. return null;
  1666. }
  1667. private async persistRemoteMetadataToDb(target: VideoItem): Promise<void> {
  1668. if (!this.context || !target || !isRemoteCloudType(target.type)) {
  1669. return;
  1670. }
  1671. const storagePath = this.resolveRemoteStoragePath(target);
  1672. if (!storagePath) {
  1673. return;
  1674. }
  1675. const table = new MediaTable(this.context);
  1676. await new Promise<void>((resolve) => {
  1677. table.getRdbStore(this.context as Context, () => resolve());
  1678. });
  1679. const cloneItem = cloneVideoItem(target);
  1680. cloneItem.filePath = storagePath;
  1681. cloneItem.remote_rel_path = storagePath;
  1682. cloneItem.parentPath = this.extractParentPathFromStoragePath(storagePath);
  1683. await table.saveOrUpdateWebDavItem(cloneItem);
  1684. }
  1685. onPageHide(): void {
  1686. this.knockController?.immersiveDisableListening();
  1687. }
  1688. @State isFirstStartPlay: boolean = false
  1689. private async startFileDeletionWatcher(): Promise<void> {
  1690. if (!this.rootPath) {
  1691. return;
  1692. }
  1693. if (!this.deletionWatcher) {
  1694. this.deletionWatcher = new FileDeletionWatcher(this.context, this.table);
  1695. }
  1696. try {
  1697. await this.deletionWatcher.watchDirectories([
  1698. this.rootPath,
  1699. this.lockPath,
  1700. this.favPath,
  1701. this.historyPath
  1702. ]);
  1703. } catch (error) {
  1704. Logger.error(TAG, `初始化文件删除监听失败: ${(error as Error).message}`);
  1705. }
  1706. }
  1707. //获取download_path
  1708. async mkDownLoadDir() {
  1709. const documentViewPicker = new picker.DocumentViewPicker()
  1710. let documentSaveResult = await documentViewPicker.save({ pickerMode: picker.DocumentPickerMode.DOWNLOAD })
  1711. this.rootPath = new fileUri.FileUri(documentSaveResult[0]).path
  1712. PreferencesUtil.putSync('download_path', this.rootPath+'/')
  1713. this.currentPath = this.rootPath
  1714. this.lockPath = this.rootPath + '/' + LocalMusic.STR_LOCK_VIDEO
  1715. this.favPath = this.rootPath + '/' + LocalMusic.STR_FAC_VIDEO
  1716. this.historyPath = this.rootPath + '/' + LocalMusic.STR_HISTORY_MUSIC
  1717. Logger.info('onecold rootPath = ' + this.rootPath)
  1718. Logger.info('onecold lockPath = ' + this.lockPath)
  1719. if (!FileUtil.accessSync(this.lockPath)) {
  1720. FileUtil.mkdirSync(this.lockPath)
  1721. }
  1722. if (!FileUtil.accessSync(this.favPath)) {
  1723. FileUtil.mkdirSync(this.favPath)
  1724. }
  1725. if (!FileUtil.accessSync(this.historyPath)) {
  1726. FileUtil.mkdirSync(this.historyPath)
  1727. }
  1728. // await this.startFileDeletionWatcher();
  1729. this.getSortedFiles(this.rootPath).then(async () => {
  1730. this.isFavMusic = false
  1731. //穿山甲
  1732. // this.loadBannerAd(CSJUtil.getBannerID())
  1733. this.songList = PreferencesUtil.getSync('LastMusicList', []) as Array<VideoItem>
  1734. this.currentSong = PreferencesUtil.getSync('LastMusicInfo', undefined) as VideoItem
  1735. if (ArrayUtil.isEmpty(this.songList)) {
  1736. this.songList = this.getCurFileList()
  1737. } else {
  1738. this.curIndex = Utility.getIndexFromList(this.songList, this.currentSong.filePath)
  1739. }
  1740. if (ArrayUtil.isNotEmpty(this.songList)) {
  1741. this.isFirstStartPlay = true
  1742. this.sonDataSource.pushArrayData(this.songList)
  1743. if (this.currentSong === undefined) {
  1744. this.isFirstStartPlay = false
  1745. this.currentSong = this.songList[0]
  1746. }
  1747. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  1748. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  1749. context: this.context,
  1750. autoParseMusicName: this.autoParseMusicName
  1751. });
  1752. Logger.info(TAG, `WebDAV URL同步构建完成: ${this.videoUrl}`);
  1753. this.name = this.currentSong.name
  1754. this.cover = this.currentSong.pixelMapPath
  1755. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  1756. } else {
  1757. this.name = '空空如也'
  1758. }
  1759. })
  1760. this.getFavList(false)
  1761. }
  1762. getFavList(isFavRefresh: boolean) {
  1763. this.table.queryByisFav(1, async (result: VideoItem[]) => {
  1764. this.favList = result
  1765. if (isFavRefresh || this.isFavMusic) { //如果是我的收藏,更新我的收藏数据
  1766. this.videoLocalList = this.favList
  1767. this.updateListData(this.videoLocalList)
  1768. }
  1769. })
  1770. }
  1771. getHistoryList(isRefresh: boolean) {
  1772. this.table.queryRecentPlayedRecords(50, async (result: VideoItem[]) => {
  1773. this.historyList = result
  1774. // for (let i = 0; i < this.historyList.length; i++) {
  1775. //
  1776. // console.info(`onecold gengxin 1: ${this.historyList[i].name}`);
  1777. // console.info(`onecold gengxin 1: ${this.historyList[i].lastPlayedStr}`);
  1778. // }
  1779. if (isRefresh) {
  1780. this.videoLocalList = this.historyList
  1781. this.updateListData(this.videoLocalList, true)
  1782. }
  1783. })
  1784. }
  1785. // 组件消失生命周期
  1786. aboutToDisappear() {
  1787. console.info('LifeCycleComponent aboutToDisappear');
  1788. this.deletionWatcher?.stop();
  1789. this.knockController?.immersiveDisableListening();
  1790. this.curIndex = 0
  1791. emitter.off(EventConstants.EVENT_AUDIO_OPEN);
  1792. emitter.off(EventConstants.EVENT_SCAN_UPDATE);
  1793. emitter.off(EventConstants.EVENT_SWIPE_BACK_UPDATE);
  1794. emitter.off(EventConstants.EVENT_SETTING_UPDATE);
  1795. this.mDestroyPage = true;
  1796. this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
  1797. if (this.CONTROL_PlayStatus != PlayStatus.INIT) {
  1798. this.stop();
  1799. }
  1800. this.mIjkMediaPlayer.off('audioInterrupt');
  1801. if (workerInstance) {
  1802. workerInstance.terminate();
  1803. }
  1804. this.stopPip();
  1805. this.destroyPipController()
  1806. }
  1807. async getSortedFiles(curPath: string, isWorkerPost?: boolean, destPath?: string, isOpen?: boolean,openItem?:VideoItem) {
  1808. this.isFavMusic = false
  1809. console.info('onecold getSortedFiles 1 curPath '+curPath)
  1810. if (isWorkerPost) {
  1811. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  1812. }
  1813. if (this.modeType !== 0) {
  1814. return
  1815. }
  1816. console.info('onecold getSortedFiles 2')
  1817. this.isCanBack = false
  1818. this.currentPath = curPath
  1819. console.info('onecold getSortedFiles this.currentPath ='+this.currentPath)
  1820. this.titleName = getFileDirName(this.currentPath,this.rootPath)
  1821. if (curPath === this.rootPath) {
  1822. this.rightTopImage = $r('sys.symbol.sort')
  1823. } else {
  1824. this.currentTitleName = getFileDirName(this.currentPath, this.rootPath)
  1825. if (this.rootPath === Utility.getParentDirectory(curPath)) {
  1826. this.rightTopImage = $r('sys.symbol.chevron_left')
  1827. }
  1828. }
  1829. // Get the current file list and calculate its hash
  1830. this.fileList = FileUtil.listFileSync(curPath);
  1831. const currentHash = simpleHash(this.fileList);
  1832. // Check cache
  1833. const cachedValue = this.findCache(curPath);
  1834. Logger.info('onecold cachedValue = ' + cachedValue)
  1835. const cachedHash = this.findStringCache(curPath + '_hash');
  1836. const cachedDirList = this.findCache(curPath + "_dirList");
  1837. if (cachedValue !== undefined&&!this.isRefreshing) {
  1838. // this.videoLocalList = cachedValue;
  1839. Logger.info('onecold 有缓存 cachedValue = ' + cachedValue)
  1840. if (this.currentPath != this.rootPath) { //第一个封面赋值给currentTitleCover
  1841. this.currentTitleCover = Utility.getFirstCoverFromList(cachedValue)
  1842. }
  1843. this.isRefreshing = false
  1844. this.updateListData(cachedValue)
  1845. }
  1846. if (cachedDirList !== undefined) {
  1847. this.dirList = cachedDirList
  1848. }
  1849. //通过当前hash值和缓存hash判断list有没有变化
  1850. if (cachedValue && cachedHash === currentHash) {
  1851. return;
  1852. }
  1853. this.fileList = FileUtil.listFileSync(curPath)
  1854. let directories: Array<VideoItem> = [];
  1855. let files: Array<VideoItem> = [];
  1856. for (let i = 0; i < this.fileList.length; i++) {
  1857. console.info(`The name of file: ${this.fileList[i]}`);
  1858. let path = curPath + '/' + this.fileList[i]
  1859. if (FileUtil.isDirectory(path)) {
  1860. let item: VideoItem =
  1861. new VideoItem(this.fileList[i].toString(), this.fileList[i].toString(), path, CommonConstants.TYPE_IS_DIR, 0,
  1862. '')
  1863. if (this.isShowDir(item.name)) {
  1864. directories.push(item);
  1865. }
  1866. // directories.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1867. // Utility.doSortListAscending(directories)
  1868. } else {
  1869. if (this.currentPath === this.lockPath&&Utility.isMeidaByExtension(path)) {
  1870. let item: VideoItem =
  1871. await Utility.uriGetMusicAssetsFromFile(this.context, path, CommonConstants.TYPE_LOCAL, false);
  1872. if (!path.endsWith('.lrc') && Utility.isMeidaByExtension(path) && !path.endsWith('.srt')) {
  1873. files.push(item);
  1874. // files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1875. // this.doSortListAscending(files)
  1876. }
  1877. }
  1878. }
  1879. }
  1880. this.table.queryByParentPath(curPath, async (result: VideoItem[]) => {
  1881. if (this.currentPath !== this.lockPath) {
  1882. files = result;
  1883. }
  1884. files.sort((a, b) => a.cTime.localeCompare(b.cTime));
  1885. Utility.doSortListAscending(files)
  1886. if (this.currentPath === this.rootPath) {
  1887. this.dirList = directories
  1888. this.addCache(curPath + "_dirList", this.dirList);
  1889. }
  1890. //插入广告先注释掉
  1891. // if (this.isShowAd && ArrayUtil.isNotEmpty(directories)) {
  1892. // let adItem: VideoItem = new VideoItem('', '', '', CommonConstants.TYPE_IS_CSJAD, 0, '')
  1893. // directories.push(adItem)
  1894. // }
  1895. // 合并文件夹和文件,文件夹在前,文件在后,广告在中间
  1896. this.videoLocalList = directories.concat(files);
  1897. this.updateListData(this.videoLocalList)
  1898. if (ArrayUtil.isNotEmpty(files)) {
  1899. if (this.currentPath != this.rootPath) {
  1900. if (files) {
  1901. this.currentTitleCover = Utility.getFirstCoverFromList(files)
  1902. }
  1903. }
  1904. // 缓存结果
  1905. this.addCache(curPath, this.videoLocalList);
  1906. await this.saveCacheToStorage(); // 保存缓存至本地存储
  1907. this.addStringCache(curPath + '_hash', currentHash);
  1908. }
  1909. console.info(`onecold gengxin 1: ${this.videoLocalList.length}`);
  1910. for (let i = 0; i < this.videoLocalList.length; i++) {
  1911. console.info(`onecold gengxin 1: ${this.videoLocalList[i].name}`);
  1912. }
  1913. // this.setButtonStatus()
  1914. this.openMusic(isOpen, destPath,openItem)
  1915. this.isRefreshing = false
  1916. });
  1917. }
  1918. //第三方app打开天天静听导入音乐后播放
  1919. openMusic(isOpen?: boolean, destPath?: string,openItem?:VideoItem){
  1920. if (isOpen&&destPath) {
  1921. if (destPath === undefined) {
  1922. // 处理 destPath 为 undefined 的情况
  1923. return
  1924. }
  1925. if (destPath.endsWith('.lrc')) {
  1926. ToastUtil.showToast('导入歌词成功!请注意歌词文件和歌曲要同个歌单路径。')
  1927. if (StrUtil.isNotEmpty(this.videoUrl)) {
  1928. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  1929. this.initLyric(lyricPath);
  1930. }
  1931. return
  1932. }
  1933. if(openItem){
  1934. this.doPlay(openItem,0,false,true)
  1935. // this.isShowPlay = true
  1936. this.setShowPlayTrue()
  1937. }
  1938. }
  1939. }
  1940. //扫描文件夹入库
  1941. async scanDirectory(curPath: string): Promise<VideoItem[]> {
  1942. const files = FileUtil.listFileSync(curPath);
  1943. let mediaItems: VideoItem[] = [];
  1944. Logger.info('onecold scanDirectory start ')
  1945. for (const file of files) {
  1946. const fPath = `${curPath}/${file}`;
  1947. if (fPath === this.lockPath) {
  1948. Logger.info(`Skipping locked path: ${fPath}`);
  1949. continue;
  1950. }
  1951. if (FileUtil.isDirectory(fPath)) {
  1952. // Recursively scan subdirectories
  1953. const subDirItems = await this.scanDirectory(fPath);
  1954. mediaItems = mediaItems.concat(subDirItems);
  1955. } else {
  1956. Logger.info('onecold scanDirectory filePath = ' + fPath)
  1957. // Process media files
  1958. if (!fPath.endsWith('.lrc') && Utility.isMeidaByExtension(fPath) && !fPath.endsWith('.srt')) {
  1959. let mediaItem: VideoItem =
  1960. await Utility.uriGetMusicAssetsFromFile(this.context, fPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  1961. mediaItems.push(mediaItem);
  1962. this.table.insert(mediaItem, (id: number) => {
  1963. });
  1964. }
  1965. }
  1966. }
  1967. return mediaItems;
  1968. }
  1969. updateListData(mList: Array<VideoItem>, noSort?: boolean) {
  1970. animateTo({ duration: 666 }, () => {
  1971. this.opacityItem = 0.5;
  1972. });
  1973. setTimeout(() => {
  1974. this.videoLocalList = mList;
  1975. if (!noSort) {
  1976. if (this.modeType === 0 || this.modeType === 1) {
  1977. this.sortType = PreferencesUtil.getNumberSync(SettingPage.SORT_TYPE, 4)
  1978. this.doSortType(this.sortType)
  1979. }
  1980. }
  1981. this.dataSource.pushArrayData(this.videoLocalList)
  1982. animateTo({ duration: 666 }, () => {
  1983. this.opacityItem = 1;
  1984. });
  1985. //添加到字母索引表
  1986. this.setAlphaBet()
  1987. this.setButtonStatus()
  1988. }, 200);
  1989. }
  1990. getCurFileList(): Array<VideoItem> {
  1991. if(this.isSearchMode){
  1992. return this.filteredList
  1993. }
  1994. let files: Array<VideoItem> = [];
  1995. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  1996. for (let i = 0; i < this.videoLocalList.length; i++) {
  1997. if (this.videoLocalList[i].type === CommonConstants.TYPE_LOCAL) {
  1998. files.push(this.videoLocalList[i]);
  1999. }
  2000. }
  2001. }
  2002. return files
  2003. }
  2004. setButtonStatus() {
  2005. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2006. this.isZero = false
  2007. } else {
  2008. this.isZero = true
  2009. }
  2010. if (this.currentPath !== this.rootPath &&
  2011. ArrayUtil.isNotEmpty(Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR))) {
  2012. this.isHasDir = true //不为空,说明有子文件夹
  2013. } else {
  2014. this.isHasDir = false
  2015. }
  2016. }
  2017. @Builder
  2018. SortMenuBuilder() {
  2019. Menu() {
  2020. MenuItem({
  2021. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  2022. content: "按艺术家升序"
  2023. })
  2024. .onClick(async () => {
  2025. this.doSortType(0)
  2026. PreferencesUtil.put(SettingPage.SORT_TYPE, 0)
  2027. this.updateListData(this.videoLocalList, true)
  2028. })
  2029. MenuItem({
  2030. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  2031. content: "按艺术家降序"
  2032. })
  2033. .onClick(async () => {
  2034. this.doSortType(1)
  2035. PreferencesUtil.put(SettingPage.SORT_TYPE, 1)
  2036. this.updateListData(this.videoLocalList, true)
  2037. })
  2038. MenuItem({
  2039. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.textformat_size_square')),
  2040. content: "按专辑升序"
  2041. })
  2042. .onClick(async () => {
  2043. this.doSortType(2)
  2044. PreferencesUtil.put(SettingPage.SORT_TYPE, 2)
  2045. this.updateListData(this.videoLocalList, true)
  2046. })
  2047. MenuItem({
  2048. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.character_arrow_clockwise')),
  2049. content: "按专辑降序"
  2050. })
  2051. .onClick(async () => {
  2052. this.doSortType(3)
  2053. PreferencesUtil.put(SettingPage.SORT_TYPE, 3)
  2054. this.updateListData(this.videoLocalList, true)
  2055. })
  2056. MenuItem({
  2057. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  2058. content: $r('app.string.sort_by_name')
  2059. })
  2060. .onClick(async () => {
  2061. this.doSortType(4)
  2062. PreferencesUtil.put(SettingPage.SORT_TYPE, 4)
  2063. this.updateListData(this.videoLocalList, true)
  2064. })
  2065. MenuItem({
  2066. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  2067. content: '按名称降序'
  2068. })
  2069. .onClick(async () => {
  2070. this.doSortType(5)
  2071. PreferencesUtil.put(SettingPage.SORT_TYPE, 5)
  2072. this.updateListData(this.videoLocalList, true)
  2073. })
  2074. MenuItem({
  2075. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2076. content: $r('app.string.sort_by_time')
  2077. })
  2078. .onClick(async () => {
  2079. this.doSortType(6)
  2080. PreferencesUtil.put(SettingPage.SORT_TYPE, 6)
  2081. this.updateListData(this.videoLocalList, true)
  2082. })
  2083. MenuItem({
  2084. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
  2085. content: '按添加时间降序'
  2086. })
  2087. .onClick(async () => {
  2088. this.doSortType(7)
  2089. PreferencesUtil.put(SettingPage.SORT_TYPE, 7)
  2090. this.updateListData(this.videoLocalList, true)
  2091. })
  2092. }.attributeModifier(new MenuModifier())
  2093. }
  2094. @Builder
  2095. SortMenuForArtistAblumBuilder() {
  2096. Menu() {
  2097. MenuItem({
  2098. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  2099. content: $r('app.string.sort_by_name')
  2100. })
  2101. .onClick(async () => {
  2102. this.doSortType(4)
  2103. // PreferencesUtil.put(SettingPage.SORT_TYPE, 2)
  2104. this.updateListData(this.videoLocalList, true)
  2105. })
  2106. MenuItem({
  2107. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  2108. content: '按名称降序'
  2109. })
  2110. .onClick(async () => {
  2111. this.doSortType(5)
  2112. this.updateListData(this.videoLocalList, true)
  2113. })
  2114. MenuItem({
  2115. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2116. content: '按数量升序'
  2117. })
  2118. .onClick(async () => {
  2119. this.doSortType(8)
  2120. this.updateListData(this.videoLocalList, true)
  2121. })
  2122. MenuItem({
  2123. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
  2124. content: '按数量降序'
  2125. })
  2126. .onClick(async () => {
  2127. this.doSortType(9)
  2128. this.updateListData(this.videoLocalList, true)
  2129. })
  2130. }.attributeModifier(new MenuModifier())
  2131. }
  2132. doSortType(index: number) {
  2133. switch (index) {
  2134. case 0:
  2135. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  2136. // 类型排序优先级
  2137. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2138. if (typeOrder !== 0) {
  2139. return typeOrder;
  2140. }
  2141. // 处理艺术家可能为undefined的字符串比较
  2142. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  2143. const artistB = b.artist?.trim() || '';
  2144. return artistA.localeCompare(artistB);
  2145. });
  2146. break;
  2147. case 1:
  2148. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  2149. // 类型排序优先级
  2150. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2151. if (typeOrder !== 0) {
  2152. return typeOrder;
  2153. }
  2154. // 处理艺术家可能为undefined的字符串比较
  2155. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  2156. const artistB = b.artist?.trim() || '';
  2157. return artistB.localeCompare(artistA);
  2158. });
  2159. break;
  2160. case 2:
  2161. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  2162. // 类型排序优先级
  2163. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2164. if (typeOrder !== 0) {
  2165. return typeOrder;
  2166. }
  2167. // 处理专辑可能为undefined的字符串比较
  2168. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  2169. const albumB = b.album?.trim() || '';
  2170. return albumA.localeCompare(albumB);
  2171. });
  2172. break;
  2173. case 3:
  2174. this.videoLocalList.sort((a: VideoItem, b: VideoItem) => {
  2175. // 类型排序优先级
  2176. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2177. if (typeOrder !== 0) {
  2178. return typeOrder;
  2179. }
  2180. // 处理专辑可能为undefined的字符串比较
  2181. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  2182. const albumB = b.album?.trim() || '';
  2183. return albumB.localeCompare(albumA);
  2184. });
  2185. break;
  2186. case 4:
  2187. Utility.doSortListAscending(this.videoLocalList,this.isShowFileName)
  2188. break;
  2189. case 5:
  2190. Utility.doSortListDescending(this.videoLocalList,this.isShowFileName)
  2191. break;
  2192. case 6:
  2193. this.videoLocalList.sort((a, b) => {
  2194. // First, sort by type
  2195. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2196. if (typeOrder !== 0) {
  2197. return typeOrder;
  2198. }
  2199. // If types are the same, sort by cTime in ascending order
  2200. return a.cTime.localeCompare(b.cTime);
  2201. });
  2202. break;
  2203. case 7:
  2204. this.videoLocalList.sort((a, b) => {
  2205. // First, sort by type
  2206. const typeOrder = getTypeOrder(a.type) - getTypeOrder(b.type);
  2207. if (typeOrder !== 0) {
  2208. return typeOrder;
  2209. }
  2210. // If types are the same, sort by cTime in descending order
  2211. return b.cTime.localeCompare(a.cTime);
  2212. });
  2213. break;
  2214. case 8:
  2215. this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
  2216. // 1. Sort by type first
  2217. const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
  2218. if (typeOrder !== 0) {
  2219. return typeOrder;
  2220. }
  2221. // 2. Then sort by artist count (numeric comparison)
  2222. let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
  2223. if(this.modeType === 2){
  2224. sortMap = this.artistMap
  2225. }else{
  2226. sortMap = this.albumMap
  2227. }
  2228. const aArtistCount: number = sortMap.get(a.name)?.length || 0;
  2229. const bArtistCount: number = sortMap.get(b.name)?.length || 0;
  2230. return aArtistCount - bArtistCount;
  2231. });
  2232. break;
  2233. case 9:
  2234. this.videoLocalList.sort((a: VideoItem, b: VideoItem): number => {
  2235. // 1. Sort by type first
  2236. const typeOrder: number = getTypeOrder(a.type) - getTypeOrder(b.type);
  2237. if (typeOrder !== 0) {
  2238. return typeOrder;
  2239. }
  2240. let sortMap:Map<string, VideoItem[]>= new Map<string, VideoItem[]>();
  2241. if(this.modeType === 2){
  2242. sortMap = this.artistMap
  2243. }else{
  2244. sortMap = this.albumMap
  2245. }
  2246. const aArtistCount: number = sortMap.get(a.name)?.length || 0;
  2247. const bArtistCount: number = sortMap.get(b.name)?.length || 0;
  2248. return bArtistCount - aArtistCount;
  2249. });
  2250. break;
  2251. }
  2252. }
  2253. showSheelDialog() {
  2254. // if(PreferencesUtil.getBooleanSync('isFirstMusic',true)) {
  2255. // this.showTips()
  2256. // return
  2257. // }
  2258. this.showAddDialog()
  2259. }
  2260. showAddDialog() {
  2261. if (this.modeType === 2 || this.modeType === 3) {
  2262. return
  2263. }
  2264. DialogHelper.showActionSheetDialog({
  2265. title: "请选择添加方式(建议歌词文件一起导入)",
  2266. sheets: [
  2267. { value: "新建文件夹", fontColor: $r('app.color.text_color') },
  2268. { value: "手动导入", fontColor: $r('app.color.text_color') },
  2269. { value: "自动导入", fontColor: $r('app.color.text_color') },
  2270. { value: "全选导入", fontColor: $r('app.color.text_color') },
  2271. ],
  2272. maskColor: Color.Transparent,
  2273. backgroundColor: $r('app.color.bg_card'),
  2274. transition: AnimationHelper.transitionInDown(555),
  2275. onAction: (index) => {
  2276. switch (index) {
  2277. case 0:
  2278. if (this.modeType === 0) {
  2279. this.showMkDialog()
  2280. } else {
  2281. ToastUtil.showToast('请切换到首页才能新建文件夹!')
  2282. }
  2283. break;
  2284. case 1:
  2285. this.callFilePickerSelectFile()
  2286. break;
  2287. case 2:
  2288. this.showTips()
  2289. break;
  2290. case 3:
  2291. this.goSelectMusic()
  2292. break;
  2293. }
  2294. }
  2295. })
  2296. }
  2297. //拉起音频
  2298. goSelectMusic() {
  2299. if (DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_TABLET ||
  2300. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_PC ||
  2301. DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1
  2302. ) {
  2303. ToastUtil.showToast('暂时不支持该设备')
  2304. return
  2305. }
  2306. try {
  2307. let documentSelectOptions = new picker.DocumentSelectOptions();
  2308. documentSelectOptions.authMode = true
  2309. documentSelectOptions.multiAuthMode = true
  2310. if( deviceInfo.sdkApiVersion>=21){//如果api大于21 ,可以支持1w首歌以上
  2311. documentSelectOptions.maxSelectNumber = 20000
  2312. }
  2313. documentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO;
  2314. let documentPicker = new picker.DocumentViewPicker(this.context);
  2315. documentPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
  2316. if (documentSelectResult !== null && documentSelectResult !== undefined) {
  2317. this.saveVideoDatas(documentSelectResult)
  2318. }
  2319. console.info('DocumentViewPicker.select successfully, documentSelectResult uri: ' +
  2320. JSON.stringify(documentSelectResult));
  2321. }).catch((err: BusinessError) => {
  2322. console.error(`DocumentViewPicker.select failed with err, code is: ${err.code}, message is: ${err.message}`);
  2323. });
  2324. } catch (error) {
  2325. let err: BusinessError = error as BusinessError;
  2326. console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2327. }
  2328. }
  2329. async showTips() {
  2330. try {
  2331. this.getUIContext().getPromptAction().showDialog({
  2332. title: '导入指南',
  2333. message:'用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  2334. + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  2335. '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  2336. '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后去文件扫描一下。\n',
  2337. buttons: [
  2338. {
  2339. text: '知道了',
  2340. color: '#000000'
  2341. },
  2342. ]
  2343. }, (err, data) => {
  2344. if (err) {
  2345. console.error('showDialog err: ' + err);
  2346. return;
  2347. }
  2348. console.info('showDialog success callback, click button: ' + data.index);
  2349. });
  2350. } catch (error) {
  2351. let message = (error as BusinessError).message;
  2352. let code = (error as BusinessError).code;
  2353. console.error(`showDialog args error code is ${code}, message is ${message}`);
  2354. };
  2355. // DialogHelper.showTipsDialog({
  2356. // title: '使用提示:自动导入教程',
  2357. //
  2358. // content: '用系统自带的文件管理器将:\n\n1、音频文件放入' + '\n\n我的设备/Download/'
  2359. // + this.appName + '\n\n2、无需繁琐的勾选和分类步骤。\n\n3、每个子文件夹将被组成一个分组。' +
  2360. // '\n\n4、歌词文件的文件名必须和目标歌曲文件名相同(不包含后缀名)。\n\n5、歌词文件和目标歌曲文件必须同个目录。' +
  2361. // '\n\n6、电脑上Download的目录是\nDownload/' + this.packName + '。\n\n7、放好文件后如果没显示点击刷新按钮。\n',
  2362. // onAction: (action) => {
  2363. // if (action == DialogAction.TWO) {
  2364. // PreferencesUtil.putSync('isFirstMusic', false)
  2365. // router.pushUrl({
  2366. // url: 'pages/ScanFilePage'
  2367. // });
  2368. // }
  2369. // }
  2370. // })
  2371. }
  2372. showMkDialog() {
  2373. DialogHelper.showTextInputDialog({
  2374. title: '新建歌单',
  2375. maskColor: Color.Transparent,
  2376. text: '',
  2377. transition: AnimationHelper.transitionInDown(666),
  2378. onChange: (text) => {
  2379. console.error("onChange: " + text);
  2380. },
  2381. onAction: (action, dialogId, content) => {
  2382. // ToastUtil.showToast('content = ' +content)
  2383. if (action == DialogAction.TWO) {
  2384. const newName = content
  2385. const newPath = this.currentPath + '/' + newName
  2386. FileUtil.mkdir(newPath, true).then(() => {
  2387. this.cache.delete(this.currentPath); // 删除目标路径缓存
  2388. this.getSortedFiles(this.currentPath)
  2389. }).catch((error: BusinessError) => {
  2390. console.error(error.message);
  2391. });
  2392. }
  2393. }
  2394. })
  2395. }
  2396. @State progress: number = 0;
  2397. async saveVideoDatas(uris:string[],isOpen?:boolean){
  2398. if (ArrayUtil.isEmpty(uris)) {
  2399. return;
  2400. }
  2401. console.info('onecold this.isCopyFileToDownLoad = ' + this.isCopyFileToDownLoad);
  2402. if(this.isCopyFileToDownLoad||this.currentPath==this.lockPath||isOpen){
  2403. this.saveVideoDatasToDownLoad(uris,isOpen)
  2404. return
  2405. }
  2406. // 初始化进度条
  2407. this.progress = 0;
  2408. DialogHelper.showLoadingProgress({
  2409. progress: this.progress,
  2410. backCancel: false,
  2411. autoCancel: false,
  2412. loadColor: $r('app.color.title_bar_bg'),
  2413. fontColor: $r('app.color.title_bar_bg')
  2414. });
  2415. // 计算处理总数用于进度计算
  2416. const totalItems = uris.length;
  2417. let processedItems = 0;
  2418. for (let i = 0; i < uris.length; i++) {
  2419. let filePath = uris[i];
  2420. try {
  2421. if (this.currentPath !== this.lockPath) { // 判断不是私密音乐,才入库
  2422. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2423. let mediaItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context,
  2424. filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2425. console.info('onecold saveVideoDatas filePath = ' + filePath)
  2426. if (!filePath.includes(this.rootPath)) {
  2427. console.info('onecold saveVideoDatas mediaItem.parentPath111 = ' + mediaItem.parentPath)
  2428. mediaItem.parentPath = this.currentPath;
  2429. }
  2430. console.info('onecold saveVideoDatas mediaItem.parentPath = ' + mediaItem.parentPath)
  2431. this.table.insert(mediaItem, (id: number) => {
  2432. // 插入完成回调
  2433. });
  2434. }
  2435. }
  2436. // 更新进度
  2437. processedItems++;
  2438. this.progress = Math.floor((processedItems / totalItems) * 100);
  2439. DialogHelper.updateLoading(' 正在处理', this.progress);
  2440. } catch (error) {
  2441. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2442. // 即使出错也更新进度
  2443. processedItems++;
  2444. this.progress = Math.floor((processedItems / totalItems) * 100);
  2445. DialogHelper.updateLoading(' 正在处理', this.progress);
  2446. }
  2447. }
  2448. // 关闭进度条
  2449. DialogHelper.closeLoading();
  2450. this.isZero = false
  2451. // 删除目标路径缓存
  2452. setTimeout(() => {
  2453. this.cache.delete(this.currentPath);
  2454. this.getSortedFiles(this.currentPath,false,uris[0],isOpen)
  2455. this.setButtonStatus()
  2456. }, 500);
  2457. }
  2458. async saveVideoDatasToDownLoad(uris: string[], isOpen?: boolean) {
  2459. if (ArrayUtil.isEmpty(uris)) {
  2460. return;
  2461. }
  2462. let newUris: string[] = [];
  2463. this.progress = 0
  2464. DialogHelper.showLoadingProgress({
  2465. progress: this.progress,
  2466. backCancel: false,
  2467. autoCancel: false,
  2468. loadColor: this.themeColor,
  2469. fontColor: this.themeColor
  2470. });
  2471. // 计算所有文件的总大小
  2472. let totalSize = 0;
  2473. for (let uri of uris) {
  2474. const sourceFile = await fileIo.open(uri, fileIo.OpenMode.READ_ONLY);
  2475. totalSize += (await fileIo.stat(sourceFile.fd)).size;
  2476. await fileIo.close(sourceFile.fd);
  2477. }
  2478. let totalRead = 0;
  2479. let destPath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[0]);
  2480. Logger.info(TAG, 'destPath uri: ' + destPath);
  2481. for (let i = 0; i < uris.length; i++) {
  2482. let filePath = this.currentPath + '/' + Utility.getMediaNameByUri(uris[i]);
  2483. Logger.info(TAG, 'filePath uri: ' + filePath);
  2484. newUris.push(filePath);
  2485. try {
  2486. const sourceFile = await fileIo.open(uris[i], fileIo.OpenMode.READ_ONLY);
  2487. const destFile = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  2488. const buffSize = 1024 * 1024; // 1MB 缓冲区大小
  2489. const buffer = new ArrayBuffer(buffSize);
  2490. let len = await fileIo.read(sourceFile.fd, buffer);
  2491. while (len > 0) {
  2492. await fileIo.write(destFile.fd, buffer.slice(0, len));
  2493. totalRead += len;
  2494. // 计算总进度
  2495. this.progress = Math.floor((totalRead / totalSize) * 100);
  2496. DialogHelper.updateLoading('正在导入', this.progress);
  2497. len = await fileIo.read(sourceFile.fd, buffer);
  2498. }
  2499. await fileIo.close(sourceFile.fd);
  2500. await fileIo.close(destFile.fd);
  2501. if (this.currentPath !== this.lockPath) { //判断不是私密音乐,才入库
  2502. if (!filePath.endsWith('.lrc') && Utility.isMeidaByExtension(filePath) && !filePath.endsWith('.srt')) {
  2503. let mediaItem: VideoItem =
  2504. await Utility.uriGetMusicAssetsFromFile(this.context, filePath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2505. this.table.insert(mediaItem, (id: number) => {
  2506. // 删除目标路径缓存
  2507. this.cache.delete(this.currentPath);
  2508. this.getSortedFiles(this.currentPath, true, destPath, isOpen,mediaItem)
  2509. });
  2510. }
  2511. }
  2512. } catch (error) {
  2513. Logger.error(TAG, 'saveVideoDatas failed with err: ' + JSON.stringify(error));
  2514. }
  2515. }
  2516. DialogHelper.closeLoading()
  2517. this.isZero = false
  2518. // setTimeout(() => {
  2519. // // 删除目标路径缓存
  2520. // this.cache.delete(this.currentPath);
  2521. // this.getSortedFiles(this.currentPath,true,destPath,isOpen)
  2522. // }, 500);
  2523. Logger.info(TAG, 'scan select video result:' + newUris)
  2524. }
  2525. //拉起音频
  2526. // goSelectMusic(){
  2527. //
  2528. // try {
  2529. // let audioSelectOptions = new picker.AudioSelectOptions();
  2530. // let audioPicker = new picker.AudioViewPicker(this.context);
  2531. // audioPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
  2532. // if (audioSelectResult !== null && audioSelectResult !== undefined) {
  2533. // this.saveVideoDatas(audioSelectResult)
  2534. // }
  2535. // console.info('AudioViewPicker.select successfully, audioSelectResult uri: ' + JSON.stringify(audioSelectResult));
  2536. // }).catch((err: BusinessError) => {
  2537. //
  2538. // console.error('AudioViewPicker.select failed with err: ' + JSON.stringify(err));
  2539. // });
  2540. // } catch (error) {
  2541. // let err: BusinessError = error as BusinessError;
  2542. // console.error('AudioViewPicker failed with err: ' + JSON.stringify(err));
  2543. // }
  2544. //
  2545. //
  2546. //
  2547. // }
  2548. async goSelectImage(item: VideoItem): Promise<string | undefined> {
  2549. if (!item) {
  2550. return undefined;
  2551. }
  2552. try {
  2553. let selectUris: Array<string> = [];
  2554. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  2555. let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  2556. photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  2557. photoSelectOptions.maxSelectNumber = 1;
  2558. const photoSelectResult = await photoPicker.select(photoSelectOptions);
  2559. selectUris = photoSelectResult.photoUris;
  2560. console.info('photoViewPicker.select to file succeed and uris are:' + selectUris);
  2561. let file = fs.openSync(selectUris[0], fs.OpenMode.READ_ONLY);
  2562. console.info('file fd: ' + file.fd);
  2563. let name = await MD5.digestSync(this.videoUrl)+'.jpg'
  2564. let imagePath = this.context.filesDir + FileUtil.separator + name
  2565. imagePath = fileUri.getUriFromPath(imagePath)
  2566. let file2 = fileIo.openSync(imagePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  2567. fileIo.copyFileSync(file.fd, file2.fd)
  2568. fileIo.closeSync(file);
  2569. fileIo.closeSync(file2);
  2570. if (item.filePath == this.currentSong?.filePath) {
  2571. this.cover = imagePath
  2572. }
  2573. if (item) {
  2574. item.pixelMapPath = imagePath
  2575. }
  2576. this.table.updatePixelMapPath(item.filePath, imagePath, (success: boolean, error?: string) => {
  2577. if (success) {
  2578. this.doUpdateData()
  2579. console.log("onecold 更新音乐封面成功,数据库已同步");
  2580. } else {
  2581. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  2582. }
  2583. });
  2584. LogUtil.debug("onecold this.cover =" + this.cover)
  2585. return FileUtil.getFilePath(imagePath); // Return the image path here
  2586. } catch (err) {
  2587. console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  2588. return undefined;
  2589. }
  2590. }
  2591. // 拉起picker选择文件管理器
  2592. async callFilePickerSelectFile(): Promise<void> {
  2593. try {
  2594. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  2595. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE) {
  2596. DocumentSelectOptions.fileSuffixFilters = CommonConstants.MEDIA_FORMAT
  2597. } else {
  2598. DocumentSelectOptions.mergeMode = picker.MergeTypeMode.AUDIO
  2599. }
  2600. let documentPicker = new picker.DocumentViewPicker();
  2601. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  2602. Logger.info(TAG,
  2603. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  2604. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  2605. this.saveVideoDatas(DocumentSelectResult)
  2606. }
  2607. }).catch((err: BusinessError) => {
  2608. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  2609. });
  2610. } catch (err) {
  2611. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  2612. }
  2613. }
  2614. //重命名的对话框
  2615. showReNameDialog(item: VideoItem, index: string, filePath: string) {
  2616. if(!item.filePath.includes(this.packName)){
  2617. ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限重命名')
  2618. return
  2619. }
  2620. DialogHelper.showTextInputDialog({
  2621. title: '重命名',
  2622. text: item.type === CommonConstants.TYPE_IS_DIR ? item.name : item.fileName,
  2623. maskColor: Color.Transparent,
  2624. backgroundColor: Color.Grey,
  2625. transition: AnimationHelper.transitionInDown(666),
  2626. onChange: (text) => {
  2627. console.error("onChange: " + text);
  2628. },
  2629. onAction: (action, dialogId, content) => {
  2630. // ToastUtil.showToast('content = ' +content)
  2631. if (action == DialogAction.TWO) {
  2632. const newName = content
  2633. const newPath = this.currentPath + '/' + newName
  2634. console.log("onecold item = " + item.type);
  2635. this.doReName(index, newName, filePath, newPath, item)
  2636. }
  2637. }
  2638. })
  2639. }
  2640. //剪切 移动到另个文件夹的对话框
  2641. showCutDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  2642. Logger.info('onecold showCutDialog')
  2643. let mList: Array<string> = []
  2644. let rPath = this.rootPath
  2645. if (isCurrent) {
  2646. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2647. rPath = this.currentPath
  2648. } else {
  2649. mList = Utility.getNameList(this.dirList);
  2650. rPath = this.rootPath
  2651. }
  2652. let dataBean = new BubbleBean()
  2653. dataBean.data = mList
  2654. dataBean.color = this.themeColor
  2655. dataBean.onItemClick = (i) => {
  2656. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  2657. Logger.info('newPath = ' + newPath)
  2658. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  2659. ToastUtil.showToast('移动成功')
  2660. this.table.deleteData(item, () => {
  2661. });
  2662. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2663. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2664. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2665. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2666. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2667. this.table.insert(newItem, (id: number) => {
  2668. //加入数据库
  2669. });
  2670. }
  2671. this.cache.delete(this.currentPath); // 删除原路径缓存
  2672. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  2673. this.getSortedFiles(this.currentPath, true)
  2674. }).catch((error: BusinessError) => {
  2675. console.error(error.message);
  2676. });
  2677. XPopup.dismissTop()
  2678. }
  2679. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  2680. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  2681. popupPosition = PopupPosition.TOP
  2682. }
  2683. if (index <= 3) {
  2684. popupPosition = PopupPosition.BOTTOM
  2685. }
  2686. let pup: XPopup
  2687. if (this.isDarkMode) {
  2688. pup = XPopup.Builder()
  2689. .setPopupPosition(popupPosition)
  2690. .atView(id)// .setHeight(this.isCoverOpacity()?100:420)
  2691. .setBackgroundColor(Color.Black)
  2692. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2693. .show()
  2694. } else {
  2695. pup = XPopup.Builder()
  2696. .setPopupPosition(popupPosition)
  2697. .atView(id)// .setHeight(this.isCoverOpacity()?280:420)
  2698. .setBackgroundColor(Color.White)
  2699. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2700. .show()
  2701. }
  2702. }
  2703. //复制 到另个文件夹的对话框
  2704. showCopyDialog(isCurrent: boolean, item: VideoItem, index: number, id: string) {
  2705. Logger.info('onecoldv showCopyDialog')
  2706. let mList: Array<string> = []
  2707. let rPath = this.rootPath
  2708. if (isCurrent) {
  2709. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  2710. rPath = this.currentPath
  2711. } else {
  2712. mList = Utility.getNameList(this.dirList);
  2713. rPath = this.rootPath
  2714. }
  2715. let dataBean = new BubbleBean()
  2716. dataBean.data = mList
  2717. dataBean.isCopy = true
  2718. dataBean.color = this.themeColor
  2719. dataBean.onItemClick = (i) => {
  2720. const newPath = rPath + '/' + mList[i] + '/' + item.fileName
  2721. Logger.info('newPath = ' + newPath)
  2722. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  2723. ToastUtil.showToast('复制成功')
  2724. this.cache.delete(rPath + '/' + mList[i]); // 删除目标路径缓存
  2725. this.getSortedFiles(this.currentPath)
  2726. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  2727. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  2728. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  2729. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2730. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  2731. this.table.insert(newItem, (id: number) => {
  2732. //加入数据库
  2733. });
  2734. }
  2735. }).catch((error: BusinessError) => {
  2736. console.error(error.message);
  2737. });
  2738. XPopup.dismissTop()
  2739. }
  2740. let popupPosition: PopupPosition = PopupPosition.BOTTOM
  2741. if (ArrayUtil.isNotEmpty(this.videoLocalList) && this.videoLocalList.length > 7) {
  2742. popupPosition = PopupPosition.TOP
  2743. }
  2744. if (index <= 3) {
  2745. popupPosition = PopupPosition.BOTTOM
  2746. }
  2747. let pup: XPopup
  2748. if (this.isDarkMode) {
  2749. pup = XPopup.Builder()
  2750. .setPopupPosition(popupPosition)
  2751. .atView(id)
  2752. .setMaxHeight('60%')
  2753. .setBackgroundColor(Color.Black)
  2754. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2755. .show();
  2756. } else {
  2757. pup = XPopup.Builder()
  2758. .setPopupPosition(popupPosition)
  2759. .atView(id)
  2760. .setMaxHeight('60%')
  2761. .setBackgroundColor(Color.White)
  2762. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  2763. .show();
  2764. }
  2765. }
  2766. //重命名索引index的视频
  2767. doReName(index: string, newName: string, oldPath: string, newPath: string, info: VideoItem) {
  2768. FileUtil.rename(oldPath, newPath).then(async () => {
  2769. if (ArrayUtil.isNotEmpty(this.videoLocalList)) {
  2770. if (info.type === CommonConstants.TYPE_IS_DIR) {
  2771. //如果是文件夹先删除源数据,再添加新数据
  2772. this.table.deleteDataForParentPath(oldPath, (success: boolean, error?: string) => {
  2773. if (success) {
  2774. console.log(" onecold deleteDataForParentPath 文件夹重命名成功,数据库已同步");
  2775. } else {
  2776. console.error(" onecold deleteDataForParentPath 文件夹重命名数据库失败原因: " + error);
  2777. }
  2778. });
  2779. this.scanDirectory(newPath)
  2780. } else if (info.type === CommonConstants.TYPE_LOCAL) {
  2781. this.table.updateRename(newName, oldPath, newPath, (success: boolean, error?: string) => {
  2782. if (success) {
  2783. console.log(" onecold 重命名成功,数据库已同步");
  2784. } else {
  2785. console.error(" onecold 重命名数据库失败原因: " + error);
  2786. }
  2787. });
  2788. }
  2789. let mediaItem: VideoItem =
  2790. await Utility.uriGetMusicAssetsFromFile(this.context, newPath, CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  2791. this.videoLocalList[index] = mediaItem;
  2792. }
  2793. this.cache.delete(this.currentPath)
  2794. this.getSortedFiles(this.currentPath, true)
  2795. }).catch((error: BusinessError) => {
  2796. console.error(error.message);
  2797. });
  2798. }
  2799. build() {
  2800. Stack() {
  2801. this.ContentBuild()
  2802. Stack() {
  2803. this.PlayController()
  2804. }
  2805. .hitTestBehavior(HitTestMode.Transparent)
  2806. .opacity(this.barBottomOpacity)
  2807. .width('90%')
  2808. .borderRadius(20)
  2809. .margin({ bottom:DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_2IN1
  2810. ? 30 :this.bottomSafeHeight })
  2811. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  2812. .backgroundImage( this.cover)
  2813. .visibility(this.isMultiSelect ? Visibility.None : Visibility.Visible)
  2814. .backgroundImageSize( { width: '100%' })
  2815. .opacity(0.9)
  2816. .clickEffect({ level: ClickEffectLevel.HEAVY })
  2817. }
  2818. .alignContent(Alignment.Bottom)
  2819. .width('100%')
  2820. .height('100%')
  2821. }
  2822. @Builder
  2823. ContentBuild() {
  2824. Scroll() {
  2825. Column() {
  2826. Stack() {
  2827. //libraryname加上去后onKeyEvent监听不了,因为目前的解决方案是上面的XComponent,去掉libraryname
  2828. XComponent({ id: 'for_onKeyEvent',type: XComponentType.SURFACE,
  2829. controller: this.xcomponentController })
  2830. .onLoad(async (event?: object) => {
  2831. })
  2832. .focusable(true)
  2833. .height(0)
  2834. .focusOnTouch(true)
  2835. .defaultFocus(true) // 自动获取键盘焦点
  2836. .onKeyEvent((event?: KeyEvent) => {
  2837. console.info('onecold点击 onKeyEvent')
  2838. // If the button type is pressed, the subsequent code will not be executed; the specific button logic will be executed upon release.
  2839. if (!event || event.type !== KeyType.Down) {
  2840. return;
  2841. }
  2842. console.info('onecold点击 onKeyEvent event.keyCode: ' + event.keyCode)
  2843. //空格键 Space key controls pause/play
  2844. if (event.keyCode === KeyCode.KEYCODE_SPACE|| event.keyCode === KeyCode.KEYCODE_MEDIA_PLAY_PAUSE) {
  2845. this.playOrPause()
  2846. }
  2847. if (event.keyCode === KeyCode.KEYCODE_DPAD_UP) {
  2848. this.playPrevious()
  2849. }
  2850. if (event.keyCode === KeyCode.KEYCODE_DPAD_DOWN) {
  2851. this.playNext()
  2852. }
  2853. // Right-click to fast forward
  2854. if (event.keyCode === KeyCode.KEYCODE_DPAD_RIGHT) {
  2855. this.fastForward()
  2856. }
  2857. // Left-click to rewind
  2858. if (event.keyCode === KeyCode.KEYCODE_DPAD_LEFT) {
  2859. this.backForward()
  2860. }
  2861. })
  2862. Column() {
  2863. XComponent({
  2864. id: 'xcomponentId',
  2865. type: 'surface',
  2866. libraryname: 'ijkplayer_napi',
  2867. controller: this.xcomponentController
  2868. })
  2869. .onLoad((event?: object) => {
  2870. if (!!event) {
  2871. this.initDelayPlay(event);
  2872. }
  2873. })
  2874. .onDestroy(() => {
  2875. })
  2876. .width('100%')// .width(this.videoWidth)
  2877. .aspectRatio(this.videoAspectRatio)
  2878. }
  2879. .aspectRatio(this.videoAspectRatio)
  2880. .justifyContent(FlexAlign.Center)
  2881. .backgroundColor(Color.Transparent)
  2882. .visibility(Visibility.Hidden)
  2883. .height(CommonConstants.FULL_PERCENT)
  2884. .width(CommonConstants.FULL_PERCENT)
  2885. .bindSheet($$this.isABSheet, this.ABLoopSheet(), {
  2886. height:this.isLandscape?'80%': '43%',
  2887. dragBar: true,
  2888. showClose: true,
  2889. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  2890. blurStyle:BlurStyle.Thin,
  2891. backgroundColor:Color.Transparent,
  2892. title: { title: 'AB循环' }
  2893. })
  2894. Stack() {
  2895. Column() {
  2896. if(this.twoFingerType==4){
  2897. this.getWaterView()
  2898. }else{
  2899. if(this.isGridMusic){
  2900. this.getGridView()
  2901. }else {
  2902. this.getList()
  2903. }
  2904. }
  2905. if (this.modeType ==0||this.modeType==4) {
  2906. Column() {
  2907. emptyView(this.themeColor)
  2908. }
  2909. .position({ top: 200 })
  2910. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 })
  2911. .animation({ duration: 500 }),
  2912. TransitionEffect.scale({ x: 0, y: 0 })))
  2913. .justifyContent(FlexAlign.Center)
  2914. .opacity(this.isZero ? 1 : 0)
  2915. .visibility(this.isZero && !this.isFavMusic && !this.isHistory
  2916. ? Visibility.Visible : Visibility.None)
  2917. .animation({
  2918. duration: 500,
  2919. curve: 'ease-in-out' // 可选动画曲线
  2920. })
  2921. .width('100%')
  2922. }
  2923. }
  2924. .layoutWeight(1)
  2925. .height('100%')
  2926. // 右侧居中的字母表索引
  2927. this.indexBuilder()
  2928. this.topTitleBar()
  2929. }
  2930. .alignContent(Alignment.Top)
  2931. .layoutWeight(1)
  2932. .height('100%')
  2933. Row() {
  2934. Button(this.isAllSelected ? '反选' : '全选', { type: ButtonType.Circle, stateEffect: true })
  2935. .width(45)
  2936. .height(45)
  2937. .fontSize(10)
  2938. .margin({ top: 10, bottom: 10, right: 6 })
  2939. .backgroundColor(this.themeColor)
  2940. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2941. .onClick(() => {
  2942. if (this.isAllSelected) {
  2943. // 全不选
  2944. this.selectedFiles = [];
  2945. } else {
  2946. // 全选
  2947. this.selectedFiles = [...this.getCurFileList()];
  2948. }
  2949. this.isAllSelected = !this.isAllSelected;
  2950. })
  2951. Button('内嵌标签', { type: ButtonType.Capsule, stateEffect: true })
  2952. .width(72)
  2953. .height(45)
  2954. .fontSize(10)
  2955. .margin({ top: 10, bottom: 10, right: 6 })
  2956. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2957. .backgroundColor(this.themeColor)
  2958. .bindContentCover($$this.isOneKeyTags, this.TagsContentCoverBuilder(), {
  2959. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2960. })
  2961. .onClick(() => {
  2962. // if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  2963. this.isOneKeyTags = !this.isOneKeyTags
  2964. // }else{
  2965. // ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限批量内嵌')
  2966. // }
  2967. })
  2968. Button('合并', { type: ButtonType.Circle, stateEffect: true })
  2969. .width(45)
  2970. .height(45)
  2971. .fontSize(10)
  2972. .margin({ top: 10, bottom: 10, right: 6 })
  2973. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2974. .backgroundColor(this.themeColor)
  2975. .bindContentCover($$this.isMergeAudio, this.MergeAudioBuilder(), {
  2976. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  2977. })
  2978. .onClick(() => {
  2979. if(ArrayUtil.isNotEmpty(this.selectedFiles)&&Utility.isMerge(this.selectedFiles,this.packName)){
  2980. this.isMergeAudio = !this.isMergeAudio
  2981. }else{
  2982. ToastUtil.showToast('选中的文件包含了不是本应用的DownLoad文件下,其他路径音频无权限合并')
  2983. }
  2984. })
  2985. Button('+歌单', { type: ButtonType.Circle, stateEffect: true })
  2986. .width(45)
  2987. .height(45)
  2988. .fontSize(10)
  2989. .margin({ top: 10, bottom: 10, right: 6 })
  2990. .backgroundColor(this.themeColor)
  2991. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  2992. .onClick(async () => {
  2993. this.longItemFilePath = ''
  2994. await this.openAddToPlaylistDialog(this.selectedFiles)
  2995. })
  2996. // Button('乱码', { type: ButtonType.Circle, stateEffect: true })
  2997. // .width(45)
  2998. // .height(45)
  2999. // .fontSize(10)
  3000. // .margin({ top: 10, bottom: 10, right: 6 })
  3001. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3002. // .backgroundColor(this.themeColor)
  3003. // .bindContentCover($$this.isFixMessy, this.FixMessyViewBuilder(), {
  3004. // transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  3005. // })
  3006. // .onClick(() => {
  3007. // this.isFixMessy = !this.isFixMessy
  3008. // })
  3009. // Button('剪切', { type: ButtonType.Circle, stateEffect: true })
  3010. // .width('35%')
  3011. // .height(60)
  3012. // .id('music_cut')
  3013. // .margin({ top: 10, bottom: 10, right: 6 })
  3014. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3015. // .backgroundColor(this.themeColor)
  3016. // .onClick(() => {
  3017. // this.showCutDialogForMultipleFiles(false, 'music_cut')
  3018. // })
  3019. //
  3020. // Button('移动', { type: ButtonType.Circle, stateEffect: true })
  3021. // .width('35%')
  3022. // .height(60)
  3023. // .id('music_cut_current')
  3024. // .visibility(this.isHasDir ? Visibility.Visible : Visibility.None)
  3025. // .margin({ top: 10, bottom: 10, right: 6 })
  3026. // .backgroundColor(this.themeColor)
  3027. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3028. // .onClick(() => {
  3029. //
  3030. // this.showCutDialogForMultipleFiles(true, 'music_cut_current')
  3031. // })
  3032. // Button('复制', { type: ButtonType.Circle, stateEffect: true })
  3033. // .width('35%')
  3034. // .height(60)
  3035. // .id('music_copy_current')// .visibility(this.isHasDir?Visibility.None:Visibility.None)
  3036. // .margin({ top: 10, bottom: 10, right: 6 })
  3037. // .backgroundColor(this.themeColor)
  3038. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3039. // .onClick(() => {
  3040. // this.showCopyDialogForMultipleFiles(false, 'music_copy_current')
  3041. // })
  3042. Button('删除', { type: ButtonType.Circle, stateEffect: true })
  3043. .width(45)
  3044. .height(45)
  3045. .fontSize(10)
  3046. .margin({ top: 10, bottom: 10, right: 6 })
  3047. .visibility(this.isFavMusic ? Visibility.None : Visibility.Visible)
  3048. .backgroundColor(this.themeColor)
  3049. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3050. .onClick(() => {
  3051. this.showWarnIsDelete()
  3052. })
  3053. Button('取消', { type: ButtonType.Circle, stateEffect: true })
  3054. .width(45)
  3055. .height(45)
  3056. .fontSize(10)
  3057. .margin({ top: 10, bottom: 10, right: 6 })
  3058. .backgroundColor(this.themeColor)
  3059. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  3060. .onClick(() => {
  3061. this.selectedFiles = [];
  3062. this.isAllSelected = false
  3063. this.isMultiSelect = false
  3064. })
  3065. }
  3066. .width('100%')
  3067. .justifyContent(FlexAlign.Center)
  3068. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  3069. .opacity(this.isMultiSelect ? 1 : 0)
  3070. .animation({
  3071. duration: 666,
  3072. curve: 'ease-in-out' // 可选动画曲线
  3073. })
  3074. .position({ bottom: 20 }) // 将 Row 固定在底部
  3075. }
  3076. .width('100%')
  3077. .height('100%')
  3078. .alignContent(Alignment.Top)
  3079. }
  3080. .width('100%')
  3081. .height('100%')
  3082. .backgroundImage(this.isCustomizeBg ? this.customizeBgPath : $r('app.color.bottom_control_background'))
  3083. .backgroundImageSize(this.isCoverOpacity() ? { width: '100%' } : { height: '100%' })
  3084. .backgroundImagePosition(Alignment.Center)
  3085. .backdropBlur(this.blurValue)
  3086. .backgroundBrightness({ rate: this.isCustomizeBg ? 0.1 : 0, lightUpDegree: this.bgBrightness })
  3087. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  3088. }
  3089. }
  3090. //字母表索引
  3091. @Builder
  3092. indexBuilder(){
  3093. if(this.enableShowAlphabet){
  3094. Column({space: 5}){
  3095. if(this.isShowAlphaBet){
  3096. AlphabetIndexer({arrayValue: this.alphaBet,selected: this.selectAlphaBetIndex})
  3097. .attributeModifier(this.alphaBetStyle)
  3098. .usingPopup(this.isTouchingAlphaBet)
  3099. .onAreaChange((old_value,new_value)=>{
  3100. this.alphabetHeight = new_value.height as number
  3101. })
  3102. .popupPosition({
  3103. x: 40,
  3104. y: this.alphabetHeight / 2
  3105. })
  3106. .onSelect((index: number) => {
  3107. this.onSelectIndexItem(this.alphaBet[index])
  3108. })
  3109. .onTouch((event: TouchEvent) =>{
  3110. this.isShowAlphaBet = true
  3111. if(event.type === TouchType.Up || event.type === TouchType.Cancel){
  3112. this.isTouchingAlphaBet = false
  3113. }else{
  3114. this.isTouchingAlphaBet = true
  3115. }
  3116. })
  3117. .transition(
  3118. TransitionEffect.translate({x: 10})
  3119. .combine(TransitionEffect.opacity(0.1))
  3120. .animation({
  3121. duration: 150,
  3122. curve: Curve.EaseInOut,
  3123. })
  3124. )
  3125. }else{
  3126. Blank()
  3127. .layoutWeight(1)
  3128. }
  3129. // ListLocateButton()
  3130. // .onClick(() =>{
  3131. // this.locateSong()
  3132. // })
  3133. // .clickEffect({level:ClickEffectLevel.LIGHT,scale: 0.5})
  3134. // .margin({
  3135. // bottom: 10
  3136. // })
  3137. }
  3138. .padding({
  3139. bottom: 0
  3140. })
  3141. .position({x:'92%'})
  3142. .height('100%')
  3143. .justifyContent(FlexAlign.Center)
  3144. }
  3145. }
  3146. onSelectIndexItem(letter: string) {
  3147. let songs = this.videoLocalList
  3148. let targetIndex = -1;
  3149. for (let i = 0; i < songs.length; i++) {
  3150. let song = songs[i]
  3151. let text = this.isShowFileName?song.fileName:song.name
  3152. if(this.sortType === 0||this.sortType==1){
  3153. text = song.artist
  3154. }else if(this.sortType === 2||this.sortType==3){
  3155. text = song.album
  3156. }
  3157. if(text){
  3158. let firstPinyin = getFirstLetter(text)
  3159. if (firstPinyin&&firstPinyin === letter) {
  3160. targetIndex = i;
  3161. break;
  3162. }
  3163. }
  3164. }
  3165. if (targetIndex !== -1) {
  3166. this.listScroller.scrollToIndex(targetIndex);
  3167. }
  3168. }
  3169. // 找到对应字母表的索引
  3170. findAlphaBetIndex(song: VideoItem):number{
  3171. let text = this.isShowFileName?song.fileName:song.name
  3172. if(this.sortType === 0||this.sortType==1){
  3173. text = song.artist
  3174. }else if(this.sortType === 2||this.sortType==3){
  3175. text = song.album
  3176. }
  3177. if(text){
  3178. let firstLetter = getFirstLetter(text)
  3179. for(let i=0;i<this.alphaBet.length;i++){
  3180. if(this.alphaBet[i] === firstLetter){
  3181. return i
  3182. }
  3183. }
  3184. }
  3185. return 0
  3186. }
  3187. async setAlphaBet(){
  3188. return new Promise<void>((resolve,reject) => {
  3189. try {
  3190. let songs = this.videoLocalList
  3191. if(songs.length > 40000){
  3192. this.alphaBet = []
  3193. resolve()
  3194. return
  3195. }
  3196. let alphabetSet = new Set<string>();
  3197. for (let song of songs) {
  3198. let text = this.isShowFileName?song.fileName:song.name
  3199. if(this.sortType === 0||this.sortType==1){
  3200. text = song.artist
  3201. }else if(this.sortType === 2||this.sortType==3){
  3202. text = song.album
  3203. }
  3204. if(text){
  3205. let firstPinyin = getFirstLetter(text)
  3206. if(!alphabetSet.has(firstPinyin)){
  3207. alphabetSet.add(firstPinyin)
  3208. }
  3209. }
  3210. // const pyStr = song.pyStr
  3211. // if(pyStr){
  3212. // if(!alphabetSet.has(pyStr)){
  3213. // alphabetSet.add(pyStr)
  3214. // }
  3215. // }
  3216. }
  3217. this.alphaBet = Array.from(alphabetSet).sort((a,b)=>{
  3218. if(this.sortType ===4||this.sortType==0||this.sortType==2||this.sortType==6){
  3219. return a.localeCompare(b)
  3220. }else{
  3221. return b.localeCompare(a)
  3222. }
  3223. })
  3224. if(this.videoLocalList.length > 0){
  3225. this.listScroller.scrollToIndex(0)
  3226. this.selectAlphaBetIndex = 0
  3227. }
  3228. resolve()
  3229. }catch (e) {
  3230. console.error('testTag','排序字母表出错',JSON.stringify(e))
  3231. resolve()
  3232. }
  3233. })
  3234. }
  3235. @Builder
  3236. topTitleBar(){
  3237. Column() {
  3238. Row({ space: 15 }) {
  3239. if (!this.isSearchMode ) {
  3240. //左侧滑动按钮
  3241. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3242. SymbolGlyph(this.rightTopImage)
  3243. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3244. }
  3245. .attributeModifier(new ButtonFancyModifier(40, 40))
  3246. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3247. .animation({ duration: 300, curve: Curve.Ease })
  3248. .onClick(() => {
  3249. this.doSwipBack()
  3250. })
  3251. .attributeModifier(new ShadowModifier())
  3252. .zIndex(0)
  3253. }else{
  3254. //左侧搜索返回按钮
  3255. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3256. SymbolGlyph($r('sys.symbol.chevron_left'))
  3257. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3258. }
  3259. .attributeModifier(new ButtonFancyModifier(40, 40))
  3260. .margin({bottom:5})
  3261. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3262. .animation({ duration: 300, curve: Curve.Ease })
  3263. .onClick(() => {
  3264. this.isSearchMode = false
  3265. if (this.modeType==0) {//如果是首页 直接getSortedFiles,如果不是就走this.onSearchInput('')
  3266. this.searchText = ''
  3267. this.getSortedFiles(this.currentPath)
  3268. return
  3269. }
  3270. this.onSearchInput('')
  3271. })
  3272. .attributeModifier(new ShadowModifier())
  3273. .zIndex(0)
  3274. }
  3275. if (!this.isSearchMode) {
  3276. Text(this.titleName)
  3277. .margin({left:3,right:10})
  3278. .fontColor($r('app.color.text_color'))
  3279. .fontSize(this.twoFingerType==3?19:this.twoFingerType==2?17:15)
  3280. .maxLines(1)
  3281. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  3282. .layoutWeight(1)
  3283. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3284. }
  3285. //搜索框
  3286. Search({ controller: this.searchController,value: this.searchText, placeholder: '搜索标题、艺术家...' })
  3287. .searchButton('搜索',{fontColor:this.themeColor})
  3288. .searchIcon({
  3289. src: $r('sys.media.ohos_ic_public_search_filled')
  3290. })
  3291. .cancelButton({
  3292. style: CancelButtonStyle.CONSTANT,
  3293. icon: {
  3294. src: $r('sys.media.ohos_ic_public_cancel_filled')
  3295. }
  3296. })
  3297. .layoutWeight(1)
  3298. .height(40)
  3299. .maxLength(20)
  3300. .backgroundColor(this.isDarkMode?Color.Black:'#F5F5F5')
  3301. .placeholderColor(Color.Grey)
  3302. .placeholderFont({ size: 14, weight: 400 })
  3303. .textFont({ size: 14, weight: 400 })
  3304. .onSubmit((value: string) => {
  3305. console.log('onecold onSubmit ='+value)
  3306. this.searchController.stopEditing()
  3307. this.onSearchInput(this.searchText);
  3308. })
  3309. .onChange((value: string) => {
  3310. console.log('onecold onChange ='+value)
  3311. this.onSearchInput(value);
  3312. })
  3313. .visibility(this.isSearchMode?Visibility.Visible:Visibility.None)
  3314. .animation({ duration: 300, curve: Curve.Ease })
  3315. //搜索按钮
  3316. if (!this.isSearchMode) {
  3317. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3318. SymbolGlyph($r('sys.symbol.magnifyingglass'))
  3319. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3320. }
  3321. .attributeModifier(new ButtonFancyModifier(40, 40))
  3322. .animation({ duration: 300, curve: Curve.Ease })
  3323. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3324. .attributeModifier(new ShadowModifier())
  3325. .zIndex(0)
  3326. .onClick(()=>{
  3327. this.isSearchMode = true
  3328. })
  3329. //排序按钮
  3330. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3331. SymbolGlyph($r('sys.symbol.list_number'))
  3332. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3333. }
  3334. .attributeModifier(new ButtonFancyModifier(40, 40))
  3335. .animation({ duration: 300, curve: Curve.Ease })
  3336. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3337. .bindMenu((this.modeType==2&&!this.isCanBack)||(this.modeType==3&&!this.isCanBack)
  3338. ?this.SortMenuForArtistAblumBuilder:this.SortMenuBuilder)
  3339. .attributeModifier(new ShadowModifier())
  3340. .zIndex(0)
  3341. //添加按钮
  3342. Button({ type: ButtonType.Circle, stateEffect: true }) {
  3343. SymbolGlyph($r('sys.symbol.plus'))
  3344. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  3345. }
  3346. .attributeModifier(new ButtonFancyModifier(40, 40))
  3347. .animation({ duration: 300, curve: Curve.Ease })
  3348. .visibility(this.modeType==0||this.modeType==1?Visibility.Visible:Visibility.None)
  3349. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3350. .bindSheet($$this.showAddSheet, this.addSheet(), {
  3351. height: SheetSize.FIT_CONTENT,
  3352. dragBar: true,
  3353. showClose: true,
  3354. preferType: SheetType.CENTER ,
  3355. title: {
  3356. title: '导入音乐'
  3357. }
  3358. })
  3359. .onClick(() => {
  3360. this.showAddSheet = !this.showAddSheet;
  3361. })
  3362. .attributeModifier(new ShadowModifier())
  3363. .zIndex(0)
  3364. }
  3365. }
  3366. }
  3367. .padding({ top: this.topSafeHeight+10, left: 10, right: 10 })
  3368. .width('100%')
  3369. }
  3370. @Builder
  3371. addSheet() {
  3372. Scroll() {
  3373. Column() {
  3374. Column() {
  3375. Row() {
  3376. Text('导入音乐复制到DownLoad目录')
  3377. .margin({ left: 18 })
  3378. .fontSize(14)
  3379. .fontColor($r('app.color.text_color'))
  3380. .fontWeight(480)
  3381. .layoutWeight(1)
  3382. Toggle({ type: ToggleType.Switch, isOn: this.isCopyFileToDownLoad })
  3383. .selectedColor(this.themeColor)
  3384. .switchPointColor(Color.White)
  3385. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  3386. .margin({ right: 18 })
  3387. .onChange((checked: boolean) => {
  3388. this.isCopyFileToDownLoad = checked;
  3389. PreferencesUtil.put(SettingPage.IS_COPYFILE_TO_DOWNLOAD, this.isCopyFileToDownLoad)
  3390. })
  3391. .width(50)
  3392. .height(30);
  3393. }
  3394. .height(88)
  3395. }
  3396. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  3397. .backgroundColor($r('app.color.start_window_background'))
  3398. .borderRadius(15)
  3399. .margin({
  3400. left: 30,
  3401. right: 30,
  3402. top: 10,
  3403. bottom: 10
  3404. })
  3405. .padding(0)
  3406. .border({
  3407. color: Color.White,
  3408. width: 1.8
  3409. })
  3410. Menu() {
  3411. MenuItem({
  3412. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder_badge_plus')),
  3413. content: "新建文件夹"
  3414. })
  3415. .backgroundColor($r('app.color.silvery'))
  3416. .border({
  3417. width: { bottom: 1 },
  3418. color: '#12ec5c87'
  3419. })
  3420. .margin(10)
  3421. .padding({left:15,right:15})
  3422. .onClick(async () => {
  3423. this.showMkDialog()
  3424. this.showAddSheet = !this.showAddSheet
  3425. })
  3426. MenuItem({
  3427. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.folder')),
  3428. content: $r('app.string.import_from_files')
  3429. })
  3430. .padding({left:15,right:15})
  3431. .backgroundColor($r('app.color.silvery'))
  3432. .border({
  3433. width: { bottom: 1 },
  3434. color: '#12ec5c87'
  3435. })
  3436. .margin(10)
  3437. .onClick(async () => {
  3438. this.callFilePickerSelectFile()
  3439. this.showAddSheet = !this.showAddSheet
  3440. })
  3441. MenuItem({
  3442. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square')),
  3443. content: '全选导入'
  3444. // content: '从下载文件夹导入(路径:Download/' +
  3445. // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
  3446. })
  3447. .padding({left:15,right:15})
  3448. .backgroundColor($r('app.color.silvery'))
  3449. .border({
  3450. width: { bottom: 1 },
  3451. color: '#12ec5c87'
  3452. })
  3453. .margin(10)
  3454. .onClick(async () => {
  3455. this.goSelectMusic()
  3456. this.showAddSheet = !this.showAddSheet
  3457. })
  3458. MenuItem({
  3459. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.save')),
  3460. content: '自动导入教程'
  3461. // content: '从下载文件夹导入(路径:Download/' +
  3462. // PathUtils.appContext!.resourceManager.getStringSync($r('app.string.EntryAbility_label').id) + ')'
  3463. })
  3464. .padding({left:15,right:15})
  3465. .backgroundColor($r('app.color.silvery'))
  3466. .border({
  3467. width: { bottom: 1 },
  3468. color: '#12ec5c87'
  3469. })
  3470. .margin(10)
  3471. .onClick(async () => {
  3472. this.showTips()
  3473. this.showAddSheet = !this.showAddSheet
  3474. })
  3475. }.attributeModifier(new MenuModifier())
  3476. .margin({bottom:30})
  3477. }
  3478. .layoutWeight(1)
  3479. }
  3480. }
  3481. @Builder
  3482. TagsContentCoverBuilder() {
  3483. Scroll() {
  3484. Column() {
  3485. TagsContentCover(
  3486. {
  3487. selectedFiles:this.selectedFiles,
  3488. isOneKeyTags:this.isOneKeyTags,
  3489. table:this.table,
  3490. onTagsResult:(result: boolean,deleteCache_path?:string)=>{
  3491. this.isMultiSelect = false
  3492. if(result){//如果嵌入成功,更新数据
  3493. this.listRefreshKey++
  3494. setTimeout(()=>{
  3495. this.doUpdateData()
  3496. },500)
  3497. }
  3498. console.info('onecold onTagsResult deleteCache_path =' +deleteCache_path)
  3499. if(deleteCache_path){
  3500. this.deleteCache(deleteCache_path)
  3501. }
  3502. }
  3503. }
  3504. )
  3505. }
  3506. }
  3507. .width('100%')
  3508. .height('100%')
  3509. }
  3510. @Builder
  3511. FixMessyViewBuilder() {
  3512. Scroll() {
  3513. Column() {
  3514. FixMessyView(
  3515. {
  3516. selectedFiles:this.selectedFiles,
  3517. isFixMessy:this.isFixMessy,
  3518. onFixResult:(result: boolean)=>{
  3519. this.isMultiSelect = false
  3520. if(result){//如果嵌入成功,更新数据
  3521. this.deleteCache(this.currentPath)
  3522. this.doUpdateData()
  3523. }
  3524. }
  3525. }
  3526. )
  3527. }
  3528. }
  3529. .width('100%')
  3530. .height('100%')
  3531. }
  3532. //剪辑音频
  3533. @Builder
  3534. EditAudioBuilder(item:VideoItem) {
  3535. Scroll() {
  3536. Column() {
  3537. EditAudio(
  3538. {
  3539. mVideoItem:item,
  3540. currentPath:this.currentPath,
  3541. videoUrl:this.videoUrl,
  3542. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3543. currentTime:this.currentTime,
  3544. progressValue:this.progressValue,
  3545. onBack:()=>{
  3546. this.isEditAudio = !this.isEditAudio
  3547. },
  3548. onSeeOutputPath:(outPutPath:string)=>{
  3549. this.isEditAudio = !this.isEditAudio
  3550. this.longItemFilePath = ''
  3551. this.modeType = 0
  3552. this.isShowFileName = true
  3553. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3554. },
  3555. onPlayOrPause:()=>{
  3556. if(this.videoUrl==item.filePath){
  3557. this.playOrPause()
  3558. }else{//如果不是当前播放的,则播放该文件
  3559. this.videoUrl==item.filePath
  3560. this.doPlay(item,0,false,true)
  3561. }
  3562. },
  3563. onSliderChange:(value:number)=>{
  3564. if(this.videoUrl!=item.filePath){
  3565. this.videoUrl==item.filePath
  3566. return
  3567. }
  3568. this.isSeekTo = true;
  3569. this.mDestroyPage = false;
  3570. this.showLoadIng();
  3571. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  3572. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3573. this.seekTo(seekValue + "");
  3574. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  3575. this.isSeekTo = false;
  3576. },
  3577. onResult:(result: boolean,outPath:string)=>{
  3578. if(result){//如果剪辑成功,更新数据
  3579. this.doUpdateData()
  3580. }else{
  3581. ToastUtil.showToast('剪辑失败')
  3582. }
  3583. }
  3584. }
  3585. )
  3586. }
  3587. }
  3588. .width('100%')
  3589. .height('100%')
  3590. }
  3591. //提取伴奏
  3592. @Builder
  3593. ConverterBuilder(item:VideoItem) {
  3594. Scroll() {
  3595. Column() {
  3596. AudioFormatConverter(
  3597. {
  3598. mVideoItem:item,
  3599. videoUrl:this.videoUrl,
  3600. currentPath:this.currentPath,
  3601. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3602. currentTime:this.currentTime,
  3603. progressValue:this.progressValue,
  3604. onBack:()=>{
  3605. this.isConverter = !this.isConverter
  3606. this.longItemFilePath = ''
  3607. },
  3608. onPlayOrPause:()=>{
  3609. if(this.videoUrl==item.filePath){
  3610. this.playOrPause()
  3611. }else{//如果不是当前播放的,则播放该文件
  3612. this.videoUrl==item.filePath
  3613. this.doPlay(item,0,false,true)
  3614. }
  3615. },
  3616. onSeeOutputPath:(outPutPath:string)=>{
  3617. this.isConverter = !this.isConverter
  3618. this.longItemFilePath = ''
  3619. this.modeType = 0
  3620. this.isShowFileName = true
  3621. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3622. },
  3623. onSliderChange:(value:number)=>{
  3624. if(this.videoUrl!=item.filePath){
  3625. this.videoUrl==item.filePath
  3626. return
  3627. }
  3628. this.isSeekTo = true;
  3629. this.mDestroyPage = false;
  3630. this.showLoadIng();
  3631. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3632. this.seekTo(seekValue + "");
  3633. this.isSeekTo = false;
  3634. },
  3635. onResult:(result: boolean,outPath:string)=>{
  3636. if(result){//如果成功,更新数据
  3637. this.doUpdateData()
  3638. }else{
  3639. ToastUtil.showToast('格式转化失败')
  3640. }
  3641. }
  3642. }
  3643. )
  3644. }
  3645. }
  3646. .width('100%')
  3647. .height('100%')
  3648. }
  3649. //提取伴奏
  3650. @Builder
  3651. ExtractAccBuilder(item:VideoItem) {
  3652. Scroll() {
  3653. Column() {
  3654. ExtractAccompaniment(
  3655. {
  3656. mVideoItem:item,
  3657. currentPath:this.currentPath,
  3658. videoUrl:this.videoUrl,
  3659. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3660. currentTime:this.currentTime,
  3661. progressValue:this.progressValue,
  3662. onBack:()=>{
  3663. this.isExtractAcc = !this.isExtractAcc
  3664. this.longItemFilePath = ''
  3665. },
  3666. onPlayOrPause:()=>{
  3667. if(this.videoUrl==item.filePath){
  3668. this.playOrPause()
  3669. }else{//如果不是当前播放的,则播放该文件
  3670. this.videoUrl==item.filePath
  3671. this.doPlay(item,0,false,true)
  3672. }
  3673. },
  3674. onSeeOutputPath:(outPutPath:string)=>{
  3675. this.isExtractAcc = !this.isExtractAcc
  3676. this.longItemFilePath = ''
  3677. this.modeType = 0
  3678. this.isShowFileName = true
  3679. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3680. },
  3681. onSliderChange:(value:number)=>{
  3682. if(this.videoUrl!=item.filePath){
  3683. this.videoUrl==item.filePath
  3684. return
  3685. }
  3686. this.isSeekTo = true;
  3687. this.mDestroyPage = false;
  3688. this.showLoadIng();
  3689. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3690. this.seekTo(seekValue + "");
  3691. this.isSeekTo = false;
  3692. },
  3693. onResult:(result: boolean,outPath:string)=>{
  3694. if(result){//如果成功,更新数据
  3695. this.doUpdateData()
  3696. }else{
  3697. ToastUtil.showToast('提取伴奏失败')
  3698. }
  3699. }
  3700. }
  3701. )
  3702. }
  3703. }
  3704. .width('100%')
  3705. .height('100%')
  3706. }
  3707. //AI人声分离
  3708. @Builder
  3709. AiBuilder(item:VideoItem) {
  3710. Scroll() {
  3711. Column() {
  3712. AIVoiceSeparation(
  3713. {
  3714. mVideoItem:item,
  3715. videoUrl:this.videoUrl,
  3716. currentPath:this.currentPath,
  3717. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3718. currentTime:this.currentTime,
  3719. progressValue:this.progressValue,
  3720. onBack:()=>{
  3721. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  3722. this.longItemFilePath = ''
  3723. },
  3724. onPlayOrPause:()=>{
  3725. if(this.videoUrl==item.filePath||this.isPlaying){
  3726. this.playOrPause()
  3727. }else{//如果不是当前播放的,则播放该文件
  3728. this.videoUrl==item.filePath
  3729. this.doPlay(item,0,false,true)
  3730. }
  3731. },
  3732. onPlayPath:(path:string)=>{
  3733. this.videoUrl==path
  3734. const itemP = Utility.getItemByFilePath(this.videoLocalList,path)
  3735. if(itemP)
  3736. this.doPlay(itemP,0,false,true)
  3737. },
  3738. onSeeOutputPath:(outPutPath:string)=>{
  3739. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  3740. this.longItemFilePath = ''
  3741. this.modeType = 0
  3742. this.isShowFileName = true
  3743. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3744. },
  3745. onSliderChange:(value:number)=>{
  3746. if(this.videoUrl!=item.filePath){
  3747. this.videoUrl==item.filePath
  3748. return
  3749. }
  3750. this.isSeekTo = true;
  3751. this.mDestroyPage = false;
  3752. this.showLoadIng();
  3753. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3754. this.seekTo(seekValue + "");
  3755. this.isSeekTo = false;
  3756. },
  3757. onResult:(result: boolean,outPath:string)=>{
  3758. if(result){//如果成功,更新数据
  3759. this.doUpdateData()
  3760. }else{
  3761. ToastUtil.showToast('Ai人声分离失败')
  3762. }
  3763. }
  3764. }
  3765. )
  3766. }
  3767. }
  3768. .width('100%')
  3769. .height('100%')
  3770. }
  3771. //变速变调
  3772. @Builder
  3773. ChangeToneBuilder(item:VideoItem) {
  3774. Scroll() {
  3775. Column() {
  3776. ChangeTone(
  3777. {
  3778. mVideoItem:item,
  3779. currentPath:this.currentPath,
  3780. videoUrl:this.videoUrl,
  3781. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3782. currentTime:this.currentTime,
  3783. progressValue:this.progressValue,
  3784. onBack:()=>{
  3785. this.isChangeTone = !this.isChangeTone
  3786. this.longItemFilePath = ''
  3787. },
  3788. onPlayOrPause:()=>{
  3789. if(this.videoUrl==item.filePath){
  3790. this.playOrPause()
  3791. }else{//如果不是当前播放的,则播放该文件
  3792. this.videoUrl==item.filePath
  3793. this.doPlay(item,0,false,true)
  3794. }
  3795. },
  3796. onSeeOutputPath:(outPutPath:string)=>{
  3797. this.isChangeTone = !this.isChangeTone
  3798. this.longItemFilePath = ''
  3799. this.modeType = 0
  3800. this.isShowFileName = true
  3801. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3802. },
  3803. onSliderChange:(value:number)=>{
  3804. if(this.videoUrl!=item.filePath){
  3805. this.videoUrl==item.filePath
  3806. return
  3807. }
  3808. this.isSeekTo = true;
  3809. this.mDestroyPage = false;
  3810. this.showLoadIng();
  3811. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3812. this.seekTo(seekValue + "");
  3813. this.isSeekTo = false;
  3814. },
  3815. onResult:(result: boolean,outPath:string)=>{
  3816. if(result){//如果成功,更新数据
  3817. this.doUpdateData()
  3818. }else{
  3819. ToastUtil.showToast('变速变调失败')
  3820. }
  3821. }
  3822. }
  3823. )
  3824. }
  3825. }
  3826. .width('100%')
  3827. .height('100%')
  3828. }
  3829. //提取视频中的音频
  3830. @Builder
  3831. extractAudioFromVideoBuilder(item:VideoItem) {
  3832. Scroll() {
  3833. Column() {
  3834. ExtractAudioFromVideo(
  3835. {
  3836. mVideoItem:item,
  3837. currentPath:this.currentPath,
  3838. videoUrl:this.videoUrl,
  3839. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3840. currentTime:this.currentTime,
  3841. progressValue:this.progressValue,
  3842. onBack:()=>{
  3843. this.isExtractAudio = !this.isExtractAudio
  3844. this.longItemFilePath = ''
  3845. },
  3846. onPlayOrPause:()=>{
  3847. if(this.videoUrl==item.filePath){
  3848. this.playOrPause()
  3849. }else{//如果不是当前播放的,则播放该文件
  3850. this.videoUrl==item.filePath
  3851. this.doPlay(item,0,false,true)
  3852. }
  3853. },
  3854. onSeeOutputPath:(outPutPath:string)=>{
  3855. this.isExtractAudio = !this.isExtractAudio
  3856. this.longItemFilePath = ''
  3857. this.modeType = 0
  3858. this.isShowFileName = true
  3859. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3860. },
  3861. onSliderChange:(value:number)=>{
  3862. if(this.videoUrl!=item.filePath){
  3863. this.videoUrl==item.filePath
  3864. return
  3865. }
  3866. this.isSeekTo = true;
  3867. this.mDestroyPage = false;
  3868. this.showLoadIng();
  3869. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  3870. this.seekTo(seekValue + "");
  3871. this.isSeekTo = false;
  3872. },
  3873. onResult:(result: boolean,outPath:string)=>{
  3874. if(result){//如果成功,更新数据
  3875. this.doUpdateData()
  3876. }else{
  3877. ToastUtil.showToast('提取音频失败')
  3878. }
  3879. }
  3880. }
  3881. )
  3882. }
  3883. }
  3884. .width('100%')
  3885. .height('100%')
  3886. }
  3887. //合并音频
  3888. @Builder
  3889. MergeAudioBuilder() {
  3890. Scroll() {
  3891. Column() {
  3892. MergeAudio(
  3893. {
  3894. videoUrl:this.videoUrl,
  3895. CONTROL_PlayStatus:this.CONTROL_PlayStatus,
  3896. currentPath:this.currentPath,
  3897. selectedFiles:this.selectedFiles,
  3898. currentTime:this.currentTime,
  3899. progressValue:this.progressValue,
  3900. onBack:()=>{
  3901. this.isMergeAudio = !this.isMergeAudio
  3902. this.longItemFilePath = ''
  3903. },
  3904. // onPlayPath:(path:string)=>{
  3905. // if(this.videoUrl==item.filePath){
  3906. // this.playOrPause()
  3907. // }else{//如果不是当前播放的,则播放该文件
  3908. // this.videoUrl==item.filePath
  3909. // this.doPlay(item,0,false,true)
  3910. // }
  3911. //
  3912. // },
  3913. onSeeOutputPath:(outPutPath:string)=>{
  3914. this.isMergeAudio = !this.isMergeAudio
  3915. this.longItemFilePath = ''
  3916. this.modeType = 0
  3917. this.isShowFileName = true
  3918. this.getSortedFiles(FileUtil.getParentPath(outPutPath))
  3919. },
  3920. onResult:(result: boolean,outPath:string)=>{
  3921. if(result){//如果成功,更新数据
  3922. this.doUpdateData()
  3923. }else{
  3924. if(this.selectedFiles.length>=3){
  3925. ToastUtil.showToast('合并数量太多导致失败')
  3926. }else{
  3927. ToastUtil.showToast('合并失败')
  3928. }
  3929. }
  3930. }
  3931. }
  3932. )
  3933. }
  3934. }
  3935. .width('100%')
  3936. .height('100%')
  3937. }
  3938. asyncCurrentPathData() {
  3939. if (this.modeType == 0) {
  3940. workerInstance.postMessage({
  3941. code: 1,
  3942. data1: this.context,
  3943. data2: this.currentPath,
  3944. data3: this.lockPath,
  3945. data4: PreferencesUtil.getStringSync('COVER_API', ''),
  3946. data5: PreferencesUtil.getBooleanSync('autoParseMusicName', true),
  3947. });
  3948. }
  3949. }
  3950. // 处理文件选择的函数
  3951. handleFileSelection(item: VideoItem, checked: boolean) {
  3952. if (checked) {
  3953. if (!this.selectedFiles.some(x => x.filePath == item.filePath)) {
  3954. this.selectedFiles.push(item);
  3955. }
  3956. } else {
  3957. const index = this.selectedFiles.findIndex(x => x.filePath == item.filePath);
  3958. if (index > -1) {
  3959. this.selectedFiles.splice(index, 1);
  3960. }
  3961. }
  3962. }
  3963. private deleteComponentId: number = 0
  3964. //多选删除文件
  3965. showWarnIsDelete(){
  3966. this.getUIContext().getPromptAction().openCustomDialog({
  3967. builder: () => {
  3968. this.deleteComptentBuilder()
  3969. },
  3970. isModal:true,
  3971. showInSubWindow:false,
  3972. maskColor: Color.Transparent,
  3973. dialogTransition: // 设置弹窗内容显示的过渡效果
  3974. TransitionEffect.translate({ x: 0, y: 290, z: 0 })
  3975. .animation({ duration: 600, curve: Curve.Smooth }),
  3976. maskTransition: // 设置蒙层显示的过渡效果
  3977. TransitionEffect.opacity(0)
  3978. .animation({ duration: 600, curve: Curve.Smooth })
  3979. }).then((dialogId: number) => {
  3980. this.deleteComponentId = dialogId
  3981. })
  3982. .catch((error: BusinessError) => {
  3983. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  3984. })
  3985. }
  3986. @Builder
  3987. deleteComptentBuilder(){
  3988. DeleteComptent({
  3989. selectedFiles:this.selectedFiles,
  3990. onCancel:()=>{
  3991. this.isMultiSelect = false
  3992. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  3993. },
  3994. onDeleteResult:(result: boolean)=>{
  3995. this.isMultiSelect = false
  3996. this.getUIContext().getPromptAction().closeCustomDialog(this.deleteComponentId)
  3997. if(result){//如果删除成功,更新数据
  3998. this.selectedFiles = [];
  3999. this.isAllSelected = false
  4000. this.cache.delete(this.currentPath);
  4001. this.getSortedFiles(this.currentPath, true);
  4002. }
  4003. }
  4004. })
  4005. }
  4006. //多选移动文件
  4007. showCutDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  4008. Logger.info('onecold showCutDialogForMultipleFiles')
  4009. let mList: Array<string> = []
  4010. let rPath = this.rootPath
  4011. if (isCurrent) {
  4012. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  4013. rPath = this.currentPath
  4014. } else {
  4015. mList = Utility.getNameList(this.dirList);
  4016. rPath = this.rootPath
  4017. }
  4018. let dataBean = new BubbleBean();
  4019. dataBean.data = mList;
  4020. dataBean.color = this.themeColor
  4021. dataBean.onItemClick = (i) => {
  4022. const newDirPath = rPath + '/' + mList[i];
  4023. // Logger.info('newDirPath = ' + newDirPath)
  4024. this.selectedFiles.forEach((item) => {
  4025. const newPath = newDirPath + '/' + item.fileName;
  4026. FileUtil.moveFile(item.filePath, newPath, 1).then(async () => {
  4027. ToastUtil.showToast('移动成功');
  4028. this.table.deleteData(item, () => {
  4029. this.cache.delete(this.currentPath); // 删除原路径缓存
  4030. this.cache.delete(newDirPath); // 删除目标路径缓存
  4031. this.getSortedFiles(this.currentPath, true);
  4032. });
  4033. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  4034. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  4035. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  4036. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  4037. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  4038. this.table.insert(newItem, (id: number) => {
  4039. //加入数据库
  4040. });
  4041. }
  4042. }).catch((error: Error) => {
  4043. console.error(error.message);
  4044. });
  4045. });
  4046. this.isMultiSelect = false
  4047. this.selectedFiles = [];
  4048. this.isAllSelected = false
  4049. XPopup.dismissTop();
  4050. };
  4051. let pup: XPopup
  4052. if (this.isDarkMode) {
  4053. pup = XPopup.Builder()
  4054. .setPopupPosition(PopupPosition.TOP)
  4055. .atView(viewId)
  4056. .setBackgroundColor(Color.Black)
  4057. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4058. .show();
  4059. } else {
  4060. pup = XPopup.Builder()
  4061. .setPopupPosition(PopupPosition.TOP)
  4062. .atView(viewId)
  4063. .setBackgroundColor(Color.White)
  4064. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4065. .show();
  4066. }
  4067. }
  4068. /**
  4069. * 加载所有歌单
  4070. */
  4071. async loadAllPlaylists() {
  4072. try {
  4073. this.allPlaylists = await this.playlistTable?.queryAllPlaylists()!
  4074. LogUtil.info('heanup Loaded playlists: ' + this.allPlaylists.length)
  4075. } catch (error) {
  4076. LogUtil.error('heaunp Failed to load playlists: ' + error.message)
  4077. }
  4078. }
  4079. /**
  4080. * 显示添加到歌单对话框
  4081. */
  4082. async openAddToPlaylistDialog(items: VideoItem | VideoItem[]) {
  4083. const songs = Array.isArray(items) ? items : [items]
  4084. const musicItems = songs.filter(song => song.type !== CommonConstants.TYPE_IS_DIR)
  4085. if (musicItems.length === 0) {
  4086. ToastUtil.showToast('请选择要添加的歌曲')
  4087. return
  4088. }
  4089. // 加载最新的歌单列表
  4090. await this.loadAllPlaylists()
  4091. showAddToPlaylistDialog(
  4092. musicItems,
  4093. this.allPlaylists,
  4094. async (playlistId: string) => {
  4095. // 添加歌曲到歌单
  4096. const success = await this.playlistTable?.addSongsToPlaylist(playlistId,
  4097. musicItems.map(song => song.filePath))
  4098. if (success) {
  4099. const count = musicItems.length
  4100. ToastUtil.showToast(count > 1 ? `已添加 ${count} 首歌曲` : '已添加到歌单')
  4101. // 重新加载歌单列表
  4102. await this.loadAllPlaylists()
  4103. } else {
  4104. ToastUtil.showToast(musicItems.length > 1 ? '选中的歌曲已在该歌单中' : '歌曲已在该歌单中')
  4105. }
  4106. this.longItemFilePath = ''
  4107. if (this.isMultiSelect) {
  4108. this.isMultiSelect = false
  4109. this.isAllSelected = false
  4110. this.selectedFiles = []
  4111. }
  4112. },
  4113. () => {
  4114. LogUtil.info('取消添加到歌单')
  4115. },
  4116. () => {
  4117. // 创建新歌单
  4118. showCreatePlaylistDialog(
  4119. async (name: string, description: string, coverPath?: string) => {
  4120. const success = await this.playlistTable?.createPlaylist(name, description, coverPath)
  4121. if (success) {
  4122. ToastUtil.showToast('歌单创建成功')
  4123. // 重新加载歌单列表并打开添加对话框
  4124. await this.loadAllPlaylists()
  4125. await this.openAddToPlaylistDialog(musicItems)
  4126. } else {
  4127. ToastUtil.showToast('歌单创建失败')
  4128. }
  4129. },
  4130. () => {
  4131. // 取消创建歌单
  4132. }
  4133. )
  4134. }
  4135. )
  4136. }
  4137. doFav(item: VideoItem) {
  4138. LogUtil.info('onecold doFav isFav=' + item.isFav)
  4139. let isFav = 0
  4140. if (Utility.getIsFav(this.favList, item)) {
  4141. isFav = 0
  4142. } else {
  4143. isFav = 1
  4144. }
  4145. this.table.updateIsFavByFilePath(item.filePath, isFav, async (result: boolean) => {
  4146. if (result) {
  4147. if (isFav === 1) {
  4148. ToastUtil.showToast('收藏成功');
  4149. } else {
  4150. ToastUtil.showToast('取消收藏成功');
  4151. }
  4152. this.deleteCache(this.currentPath)
  4153. this.getFavList(false)
  4154. if (this.modeType === 0 && !this.isFavMusic) {
  4155. LogUtil.info('onecold doFav currentPath =' + this.currentPath)
  4156. this.getSortedFiles(this.currentPath)
  4157. }
  4158. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  4159. workerInstance.postMessage({ code: 3, data: this.context });
  4160. workerInstance.postMessage({ code: 4, data: this.context });
  4161. }
  4162. })
  4163. }
  4164. //多选复制文件
  4165. showCopyDialogForMultipleFiles(isCurrent: boolean, viewId: string) {
  4166. console.log('onecold showCopyDialogForMultipleFiles');
  4167. let mList: Array<string> = []
  4168. let rPath = this.rootPath
  4169. if (isCurrent) {
  4170. mList = Utility.getGlobalNameList(this.videoLocalList, CommonConstants.TYPE_IS_DIR);
  4171. rPath = this.currentPath
  4172. } else {
  4173. mList = Utility.getNameList(this.dirList);
  4174. rPath = this.rootPath
  4175. }
  4176. let dataBean = new BubbleBean();
  4177. dataBean.data = mList;
  4178. dataBean.isCopy = true
  4179. dataBean.color = this.themeColor
  4180. dataBean.onItemClick = (i) => {
  4181. const newDirPath = rPath + '/' + mList[i];
  4182. // Logger.info('newDirPath = ' + newDirPath)
  4183. this.selectedFiles.forEach((item) => {
  4184. const newPath = newDirPath + '/' + item.fileName;
  4185. FileUtil.copyFile(item.filePath, newPath, 0).then(async () => {
  4186. ToastUtil.showToast('复制成功');
  4187. this.cache.delete(newDirPath); // 删除目标路径缓存
  4188. this.getSortedFiles(this.currentPath);
  4189. // let newItem = new VideoItem(item.name,newPath,newPath,item.type,item.videoSize,item.cTime,item.pixelMap,
  4190. // item.size,item.pixelMapToString,item.artist,item.album,item.fileName)
  4191. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newPath,
  4192. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  4193. if (!newPath.includes(this.lockPath)) { //如果移动到私密,就不插入数据库
  4194. this.table.insert(newItem, (id: number) => {
  4195. //加入数据库
  4196. });
  4197. }
  4198. }).catch((error: Error) => {
  4199. console.error(error.message);
  4200. });
  4201. });
  4202. this.isMultiSelect = false
  4203. this.selectedFiles = [];
  4204. this.isAllSelected = false
  4205. XPopup.dismissTop();
  4206. };
  4207. let pup: XPopup
  4208. if (this.isDarkMode) {
  4209. pup = XPopup.Builder()
  4210. .setPopupPosition(PopupPosition.TOP)
  4211. .atView(viewId)
  4212. .setBackgroundColor(Color.Black)
  4213. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4214. .show();
  4215. } else {
  4216. pup = XPopup.Builder()
  4217. .setPopupPosition(PopupPosition.TOP)
  4218. .atView(viewId)
  4219. .setBackgroundColor(Color.White)
  4220. .asBubble(wrapBuilder(cutPopupBuilder), dataBean)
  4221. .show();
  4222. }
  4223. }
  4224. @Builder
  4225. private DirItem(item: VideoItem, index?: number) {
  4226. Button({ type: ButtonType.Normal, stateEffect: true }) {
  4227. Row() {
  4228. Image(this.modeType !== 0 && StrUtil.isNotEmpty(item.pixelMapPath) ? item.pixelMapPath :
  4229. $r('app.media.music_group'))
  4230. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4231. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4232. .fillColor(this.themeColor)// .fontSize(33)
  4233. .alt($r('app.media.music_group'))
  4234. .borderRadius('100%')
  4235. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4236. // .autoResize(true) // 重采样,可减少内存占用
  4237. .clip(true)
  4238. .sourceSize({width:38, height:38})
  4239. .margin({ left: 20, top: 8, bottom: 8 })
  4240. Column() {
  4241. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  4242. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4243. .maxLines(1)// .width('88%')
  4244. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4245. .animation({
  4246. duration: 555,
  4247. curve: 'ease-in-out',
  4248. })
  4249. .transition({
  4250. type: TransitionType.Insert,
  4251. opacity: 0,
  4252. translate: { x: 160 }
  4253. })
  4254. .margin({ left: 10, right: 20 })
  4255. .fontColor($r('app.color.text_color'))
  4256. Row() {
  4257. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  4258. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4259. .padding({ top: 8 })
  4260. .visibility(this.modeType === 2 ? Visibility.Visible : Visibility.None)
  4261. .fontColor($r('app.color.text_color'))
  4262. .margin({ left: 10 })
  4263. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  4264. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4265. .padding({ top: 8 })
  4266. .visibility(this.modeType === 3 ? Visibility.Visible : Visibility.None)
  4267. .fontColor($r('app.color.text_color'))
  4268. .margin({ left: 10 })
  4269. Blank()
  4270. }
  4271. }
  4272. .height('100%')
  4273. .layoutWeight(1)
  4274. .justifyContent(FlexAlign.Center)
  4275. .alignItems(HorizontalAlign.Start)
  4276. Blank()
  4277. Image($r('app.media.arrow_right'))
  4278. .height(25)
  4279. .alignSelf(ItemAlign.Center)
  4280. .id(item.filePath)
  4281. .visibility(this.isShowAlphaBet?Visibility.None:Visibility.Visible)
  4282. .animation({ duration: 300, curve: Curve.Ease })
  4283. }
  4284. }
  4285. .backgroundColor(Color.Transparent)
  4286. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  4287. .width('98%')
  4288. .reuseId('dir_item')
  4289. .visibility(this.isShowDir(item.name) ? Visibility.Visible : Visibility.None)
  4290. .opacity(this.opacityItem) // 绑定透明度
  4291. }
  4292. isShowDir(dirName: string) {
  4293. this.isShowSimi = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, false)
  4294. this.isShowFAV = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_FAV, true)
  4295. this.isShowHistory = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_HISTORY, true)
  4296. if (dirName === undefined) {
  4297. return true
  4298. }
  4299. if (dirName === LocalMusic.STR_LOCK_VIDEO) {
  4300. return this.isShowSimi
  4301. }
  4302. if (dirName === LocalMusic.STR_FAC_VIDEO) {
  4303. return this.isShowFAV
  4304. }
  4305. if (dirName === LocalMusic.STR_HISTORY_MUSIC) {
  4306. return this.isShowHistory
  4307. }
  4308. return true
  4309. }
  4310. @State opacityItem: number = 1; // 控制透明度的状态变量
  4311. @Builder
  4312. private MusicItem(item: VideoItem, index?: number) {
  4313. Button({ type: ButtonType.Normal, stateEffect: true }) {
  4314. Row() {
  4315. Stack() {
  4316. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  4317. .fillColor(this.themeColor)
  4318. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4319. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  4320. .alt($r('app.media.music_red'))
  4321. .borderRadius(this.isCoverRectangle?13:'100%')
  4322. .clip(true)
  4323. .draggable(false)
  4324. .sourceSize({width:38, height:38})
  4325. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4326. // .autoResize(true) // 重采样,可减少内存占用
  4327. .opacity(this.opacityItem)// 绑定透明度
  4328. .margin({ left: 20 })
  4329. .gesture(LongPressGesture()
  4330. .onAction(async () => {
  4331. //如果是专辑和艺术家的首页,不能长按
  4332. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4333. return
  4334. //如果是我的收藏 最近播放等也不能长按
  4335. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4336. item.name === LocalMusic.STR_HISTORY_MUSIC
  4337. )
  4338. return
  4339. this.longItemFilePath = item.filePath
  4340. this.tempLyricContent = await this.getLyricContent(item)
  4341. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  4342. })
  4343. .onActionEnd((event: GestureEvent) => {
  4344. }))
  4345. .onClick(()=>{
  4346. if (this.isMultiSelect) {
  4347. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  4348. this.handleFileSelection(item, !isChecked);
  4349. } else {
  4350. this.doPlay(item,index)
  4351. this.setShowPlayTrue()
  4352. }
  4353. })
  4354. }
  4355. Column() {
  4356. Column() {
  4357. Text(this.isShowFileName?item.fileName :item.name)
  4358. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  4359. .maxLines(1)
  4360. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4361. .animation({
  4362. duration: 555,
  4363. curve: 'Linear',
  4364. })
  4365. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4366. $r('app.color.text_color'))
  4367. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4368. .padding({right:25})
  4369. .bindPopup(this.longItemFilePath === item.filePath, {
  4370. builder: this.MenuBuilder(item,index,item.filePath),
  4371. placement: Placement.Top,
  4372. // autoCancel: true,
  4373. mask: {color:'#33000000'},
  4374. // popupColor: Color.Yellow,
  4375. enableArrow: false,//是否显示箭头
  4376. showInSubWindow: false,
  4377. onStateChange: (e) => {
  4378. if (!e.isVisible) {
  4379. this.longItemFilePath = ''
  4380. this.tempLyricContent = ''
  4381. }
  4382. }
  4383. })
  4384. .gesture(LongPressGesture()
  4385. .onAction(async () => {
  4386. //如果是专辑和艺术家的首页,不能长按
  4387. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4388. return
  4389. //如果是我的收藏 最近播放等也不能长按
  4390. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4391. item.name === LocalMusic.STR_HISTORY_MUSIC
  4392. )
  4393. return
  4394. this.longItemFilePath = item.filePath
  4395. this.tempLyricContent = await this.getLyricContent(item)
  4396. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  4397. })
  4398. .onActionEnd((event: GestureEvent) => {
  4399. })
  4400. )
  4401. Row() {
  4402. Column(){
  4403. Text(item.md5Str?.includes('Lossless')?
  4404. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  4405. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  4406. .padding({ top: 3,right:6,left:6,bottom:3 })
  4407. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4408. $r('app.color.text_color'))
  4409. .fontWeight(500)
  4410. .borderRadius(12)
  4411. .visibility(StrUtil.isEmpty(item.md5Str)?Visibility.None:Visibility.Visible)
  4412. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4413. .backgroundColor('#FFC107')
  4414. }
  4415. .padding({ top: 8 })
  4416. Text(StrUtil.isEmpty(item.artist) ? item.duration
  4417. :this.twoFingerType==2? item.artist +' ' + item.duration
  4418. : item.artist + ' ' + item?.duration)
  4419. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4420. .padding({ top: 8 ,right:25})
  4421. .visibility(this.isShowFileName?Visibility.None:Visibility.Visible)
  4422. .maxLines(1)
  4423. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4424. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4425. Color.Gray)
  4426. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4427. Blank()
  4428. Text(this.isShowFileName?item.duration:item.size)
  4429. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  4430. .padding({ top: 8 })
  4431. .maxLines(1)
  4432. .visibility(this.isShowFileName?Visibility.Visible:StrUtil.isEmpty(item.artist)
  4433. ? Visibility.Visible : Visibility.None)
  4434. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4435. Color.Gray)
  4436. .margin({ left: StrUtil.isEmpty(item.artist) ?0:10 })
  4437. }
  4438. .gesture(LongPressGesture()
  4439. .onAction(async () => {
  4440. //如果是专辑和艺术家的首页,不能长按
  4441. if((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  4442. return
  4443. //如果是我的收藏 最近播放等也不能长按
  4444. if(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  4445. item.name === LocalMusic.STR_HISTORY_MUSIC
  4446. )
  4447. return
  4448. this.longItemFilePath = item.filePath
  4449. this.tempLyricContent = await this.getLyricContent(item)
  4450. LogUtil.info('长按this.tempLyricContent = '+this.tempLyricContent)
  4451. })
  4452. .onActionEnd((event: GestureEvent) => {
  4453. })
  4454. )
  4455. }
  4456. .height('100%')
  4457. .width('100%')
  4458. .margin({ right: 10 })
  4459. .justifyContent(FlexAlign.Center)
  4460. .alignItems(HorizontalAlign.Start)
  4461. }
  4462. .height('100%')
  4463. .margin({ left: 5 })
  4464. .layoutWeight(1)
  4465. Column() {
  4466. Checkbox({ name: 'checkbox' + index })
  4467. .select(this.selectedFiles.some(x => x.filePath === item.filePath))
  4468. .selectedColor(this.themeColor)
  4469. .shape(CheckBoxShape.CIRCLE)
  4470. .opacity(this.isMultiSelect ? 1 : 0)
  4471. .animation({
  4472. duration: 666,
  4473. curve: 'Smooth' // 可选动画曲线
  4474. })
  4475. .visibility(this.isMultiSelect ? Visibility.Visible : Visibility.None)
  4476. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  4477. .margin({ left: 20, top: 8, bottom: 8,right:18 })
  4478. .width(22)
  4479. .height(22)
  4480. ImageAnimator()
  4481. .images(this.imagesF)// 动画数组
  4482. .duration(1000)// 持续
  4483. .state(this.animationState)// 动画状态
  4484. .fillMode(FillMode.Forwards)
  4485. .width(18)
  4486. .margin({ right: 20, top: 8, bottom: 8 })
  4487. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  4488. Visibility.None)
  4489. .height(18)
  4490. .iterations(-1) // 播放次数
  4491. }
  4492. }
  4493. }
  4494. .backgroundColor(Color.Transparent)
  4495. .width('100%')
  4496. .reuseId('file_item')
  4497. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  4498. }
  4499. private readonly tabs: string[] = ['文件夹', '媒体库', '艺术家', '专辑']
  4500. @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
  4501. buttons: [{ text: '文件夹' }, { text: '媒体库' },{ text: '艺术家' }, { text: '专辑' }],
  4502. direction: Direction.Ltr,
  4503. buttonPadding:{top:12,bottom:12},
  4504. backgroundColor: Color.Transparent,
  4505. fontSize:14,
  4506. selectedFontSize:15,
  4507. selectedFontColor:Color.White,
  4508. selectedBackgroundColor: this.themeColor,
  4509. localizedTextPadding: {
  4510. end: LengthMetrics.vp(20),
  4511. start: LengthMetrics.vp(20)
  4512. }
  4513. })
  4514. @State @Watch('capsuleSelectedIndexesChanged')tabSelectedIndexes: number[] = [0]
  4515. //当胶囊按钮的选择发生变化时调用此函数
  4516. capsuleSelectedIndexesChanged() {
  4517. this.modeType = this.tabSelectedIndexes[0]
  4518. }
  4519. @Builder
  4520. tabTitle() {
  4521. Column({ space: 2 }) {
  4522. SegmentButton({ options: this.tabOptions, selectedIndexes: $tabSelectedIndexes })
  4523. Line()
  4524. .width('100%')
  4525. .height(1)
  4526. .backgroundColor($r('app.color.index_background'))
  4527. .opacity(this.barOpacity)
  4528. .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  4529. }
  4530. .width('100%')
  4531. .height(this.topBarHeight)
  4532. .visibility(this.isShowTitleBar ? Visibility.Visible : Visibility.None)
  4533. }
  4534. // @Builder
  4535. // tabTitle() {
  4536. // Column() {
  4537. // // 使用 Stack 布局来实现绝对定位效果
  4538. // Stack() {
  4539. // // 背景动画容器
  4540. // Row() {
  4541. // ForEach(this.tabs, (i: string, index) => {
  4542. // Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  4543. // Flex()
  4544. // .backgroundColor(this.isDarkMode ? $r('app.color.tab_item_bg') : this.themeColor)
  4545. // .borderRadius(20)
  4546. // .padding(10)
  4547. // .margin(6)
  4548. // .width('100%')
  4549. // .height('100%')
  4550. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  4551. // .visibility(this.modeType === index ? Visibility.Visible : Visibility.None)
  4552. // .opacity(this.modeType === index ? 1 : 0)
  4553. // .animation({
  4554. // duration: 666,
  4555. // playMode: PlayMode.Normal,
  4556. // curve: 'ease-in-out'
  4557. // });
  4558. // }
  4559. // .layoutWeight(1)
  4560. // .margin({
  4561. // left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5,
  4562. // right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 20 : 5, bottom: 1
  4563. // });
  4564. // });
  4565. // }
  4566. // .width('100%')
  4567. // .height(50);
  4568. //
  4569. // // 导航栏容器
  4570. // Row() {
  4571. // ForEach(this.tabs, (item: string, index) => {
  4572. // Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
  4573. // Text(item)
  4574. // .fontSize(16)
  4575. // .fontColor(this.modeType === index ? Color.White : $r('app.color.text_color'))
  4576. // .padding(15)
  4577. // .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  4578. // .onClick(() => {
  4579. // this.modeType = index;
  4580. // // this.onModeChange();
  4581. // });
  4582. // }
  4583. // .layoutWeight(1)
  4584. // .stateStyles({
  4585. // pressed: { opacity: 0.6 } // 按压反馈
  4586. // });
  4587. // });
  4588. // }
  4589. // .width('100%')
  4590. // .height(this.topBarHeight)
  4591. // .opacity(this.barOpacity)
  4592. // .backgroundColor(Color.Transparent);
  4593. //
  4594. // }
  4595. // .width('100%')
  4596. // .height(this.topBarHeight)
  4597. // .opacity(this.barOpacity)
  4598. //
  4599. // Line()
  4600. // .width('100%')
  4601. // .height(1)
  4602. // .backgroundColor($r('app.color.index_background'))
  4603. // .opacity(this.barOpacity)
  4604. // .visibility(this.isCustomizeBg ? Visibility.Hidden : Visibility.Visible)
  4605. // }
  4606. // .visibility(this.isShowTitleBar ? Visibility.Visible : Visibility.None)
  4607. // }
  4608. @State currentTitleName: string = '' //点击歌单,艺术家,专辑进去后的标题
  4609. @State currentTitleCover: string | ResourceStr = '' //点击歌单,艺术家,专辑进去后的封面
  4610. isShowCoverHeader() {
  4611. if (!this.isShowHeader) {
  4612. return false
  4613. }
  4614. if (this.modeType == 0) {
  4615. if (this.isHistory || this.isFavMusic) {
  4616. return true
  4617. }
  4618. if (this.currentPath != this.rootPath) {
  4619. return true
  4620. }
  4621. }
  4622. return (this.modeType == 2 || this.modeType == 3) && this.isCanBack
  4623. }
  4624. getCoverTitleBg(): ResourceStr | image.PixelMap {
  4625. if (this.isCustomizeBg) {
  4626. return ('rgba(255,255,255,0.2)')
  4627. }
  4628. if (this.isDarkMode) {
  4629. return $r('app.color.user_center_card_background')
  4630. }
  4631. return this.currentTitleCover
  4632. }
  4633. // 第二步:popup构造器定义弹框内容
  4634. @Builder popupBuilder() {
  4635. Column({ space: 2 }) {
  4636. Text('友情提示:双指缩放可以放大缩小列表')
  4637. .fontSize(12)
  4638. .fontWeight(FontWeight.Regular)
  4639. .fontColor($r('app.color.text_color'))
  4640. }
  4641. .justifyContent(FlexAlign.SpaceAround)
  4642. .width(220)
  4643. .height(55)
  4644. .padding(15)
  4645. }
  4646. //搜索功能的实现
  4647. @State searchText: string = ''; // 用户输入内容
  4648. @State filteredList: Array<VideoItem> = []; // 过滤后的结果
  4649. @State isSearchMode: boolean = false
  4650. // 实时搜索逻辑(带防抖)
  4651. private onSearchInput(value: string) {
  4652. this.searchText = value.trim();
  4653. let mSearchList: Array<VideoItem> = []
  4654. switch (this.modeType) {
  4655. case 0:
  4656. case 1:
  4657. mSearchList = this.mediaKuList
  4658. break;
  4659. case 2:
  4660. mSearchList = this.artistList
  4661. break;
  4662. case 3:
  4663. mSearchList = this.albumList
  4664. break;
  4665. default :
  4666. mSearchList = this.videoLocalList
  4667. break;
  4668. }
  4669. // 新增条件判断:空输入时显示所有数据
  4670. if (this.searchText === '') {
  4671. this.filteredList = [...mSearchList]; // 创建新数组以触发状态更新
  4672. } else {
  4673. this.filteredList = mSearchList.filter((item: VideoItem) => {
  4674. //支持模糊匹配和艺术家 专辑匹配
  4675. const regex = new RegExp(this.searchText.toLowerCase().replace(/\s+/g, '.*'), 'i');
  4676. return regex.test(item.name.toLowerCase())||
  4677. regex.test(item.fileName?.toLowerCase() ?? "") ||
  4678. regex.test(item.artist?.toLowerCase() ?? "") ||
  4679. regex.test(item.album?.toLowerCase() ?? "")
  4680. });
  4681. }
  4682. this.updateListData(this.filteredList);
  4683. // this.isSearchMode = false; // 根据业务需求决定是否启用
  4684. }
  4685. @State dragItem: number = -1
  4686. @State scaleItem: number = -1
  4687. @State neighborItem: number = -1
  4688. @State neighborScale: number = -1
  4689. @State offsetY: number = 0
  4690. private dragRefOffset: number = 0
  4691. private ITEM_INTV: number = 78
  4692. scaleSelect(item: number): number {
  4693. if (this.scaleItem === item) {
  4694. return 1.05
  4695. } else if (this.neighborItem === item) {
  4696. return this.neighborScale
  4697. } else {
  4698. return 1
  4699. }
  4700. }
  4701. itemMove(index: number, newIndex: number): void {
  4702. if (newIndex < 0 || newIndex >= this.videoLocalList.length) {
  4703. return;
  4704. }
  4705. let tmp = this.videoLocalList.splice(index, 1);
  4706. this.videoLocalList.splice(newIndex, 0, tmp[0]);
  4707. this.dataSource.pushArrayData(this.videoLocalList)
  4708. if(this.modeType==4&&this.playlistTable){
  4709. updateAllSongsSortOrder(this.playlistTable, this.videoLocalList,this.currentSongListID)
  4710. }
  4711. }
  4712. //瀑布流布局 支持双指缩放
  4713. @State columns: number = 2;
  4714. @State waterFlowScale: number = 1;
  4715. @State imageScale: number = 1;
  4716. @State waterFlowOpacity: number = 1;
  4717. @State waterFlowSnapshot: image.PixelMap | undefined = undefined;
  4718. private columnChanged: boolean = false;
  4719. private oldColumn: number = this.columns;
  4720. private pinchTime: number = 0;
  4721. // 根据缩放阈值改变列数,触发WaterFlow重新布局
  4722. changeColumns(scale: number) {
  4723. if (scale > (this.columns / (this.columns - 0.5)) && this.columns > 1) {
  4724. this.columns--;
  4725. this.columnChanged = true;
  4726. } else if (scale < 1 && this.columns < 4) {
  4727. this.columns++;
  4728. this.columnChanged = true;
  4729. }
  4730. }
  4731. @Builder
  4732. getWaterView(){
  4733. Scroll(this.scroller) {
  4734. Column() {
  4735. Blank().height(this.topSafeHeight + 55)
  4736. WaterFlow({
  4737. scroller:this.waterScroller,
  4738. layoutMode: WaterFlowLayoutMode.SLIDING_WINDOW
  4739. }) {
  4740. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  4741. FlowItem() {
  4742. this.MusicWaterCardItem(item,index)
  4743. }
  4744. .width('100%')
  4745. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  4746. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  4747. {
  4748. preview: MenuPreviewMode.IMAGE,
  4749. previewAnimationOptions: { scale: [0.8, 1.0] },
  4750. })
  4751. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  4752. {
  4753. preview: MenuPreviewMode.IMAGE,
  4754. previewAnimationOptions: { scale: [0.8, 1.0] },
  4755. })
  4756. .transition(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }))
  4757. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  4758. TransitionEffect.scale({ x: 0, y: 0 })))
  4759. .gesture(
  4760. GestureGroup(GestureMode.Exclusive,
  4761. SwipeGesture({ direction: SwipeDirection.Horizontal })
  4762. .onAction((event: GestureEvent) => {
  4763. if (event) {
  4764. // this.sideBarController.openSideBar()
  4765. }
  4766. }),
  4767. TapGesture({ count: 1, fingers: 1 })
  4768. .onAction(async () => {
  4769. })
  4770. )
  4771. )
  4772. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  4773. }
  4774. // .columnsTemplate('repeat(auto-fit, 160)')
  4775. .id('waterflow') // 设置id用于截图
  4776. .columnsTemplate('1fr '.repeat(this.columns)) // 动态生成列模板,如:'1fr 1fr 1fr'表示3列等宽
  4777. .columnsGap(12) // 列间距
  4778. .rowsGap(16) // 行间距
  4779. .cachedCount(6)
  4780. .padding({bottom:this.bottomBarHeight+10})
  4781. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  4782. .animation({ duration: 500, curve: Curve.Ease }))
  4783. .scrollBar(BarState.Off)
  4784. // .fadingEdge(true, { fadingEdgeLength: LengthMetrics.vp(38) })
  4785. // 效果:只有向上或者向下滑动到顶部时才会有弹簧回弹效果
  4786. .edgeEffect(EdgeEffect.Spring, { alwaysEnabled: true })
  4787. .width('90%')
  4788. .height('100%')
  4789. .opacity(this.waterFlowOpacity)
  4790. .scale({
  4791. x: this.waterFlowScale,
  4792. y: this.waterFlowScale,
  4793. centerX: 0,
  4794. centerY: 0
  4795. })
  4796. .onAppear(() => {
  4797. this.scroller.scrollEdge(Edge.Top)
  4798. })
  4799. .nestedScroll({
  4800. scrollForward: NestedScrollMode.PARENT_FIRST,
  4801. scrollBackward: NestedScrollMode.SELF_FIRST
  4802. })
  4803. .priorityGesture(
  4804. PinchGesture()
  4805. .onActionStart((event: GestureEvent) => {
  4806. // 双指捏合手势识别成功时截图
  4807. this.pinchTime = event.timestamp;
  4808. this.columnChanged = false;
  4809. this.oldColumn = this.columns;
  4810. this.getUIContext().getComponentSnapshot().get('waterflow', (error: Error, pixmap: image.PixelMap) => {
  4811. if (error) {
  4812. console.info('error:' + JSON.stringify(error));
  4813. return;
  4814. }
  4815. this.waterFlowSnapshot = pixmap;
  4816. if ((this.oldColumn === 1 ) && event.scale > 1|| (this.oldColumn === 4 && event.scale < 1)) {
  4817. console.info("onecold onActionStart oldColumn:" + this.oldColumn)
  4818. if (this.oldColumn ===4) {
  4819. this.twoFingerType =3
  4820. this.isGridMusic = true
  4821. }else if (this.oldColumn ===1) {
  4822. this.twoFingerType =1
  4823. this.isGridMusic = false
  4824. }
  4825. return;
  4826. }
  4827. })
  4828. })
  4829. .onActionUpdate((event: GestureEvent) => {
  4830. // 手势更新:处理缩放逻辑和视觉效果
  4831. // 边界限制:防止超出列数范围时继续缩放
  4832. if ((this.oldColumn === 1 && event.scale > 1) || (this.oldColumn === 4 && event.scale < 1)) {
  4833. return;
  4834. }
  4835. // 节流处理:避免过于频繁的更新,提升性能
  4836. if (event.timestamp - this.pinchTime < 10000000) {
  4837. return;
  4838. }
  4839. this.pinchTime = event.timestamp;
  4840. this.waterFlowScale = event.scale;
  4841. this.imageScale = event.scale;
  4842. // 根据缩放比例设置WaterFlow透明度
  4843. this.waterFlowOpacity = (this.waterFlowScale > 1) ? (this.waterFlowScale - 1) : (1 - this.waterFlowScale);
  4844. this.waterFlowOpacity *= 3;
  4845. if (!this.columnChanged) {
  4846. this.changeColumns(event.scale);
  4847. }
  4848. // 列数改变后的缩放比例调整:避免出现空白区域
  4849. if (this.columnChanged) {
  4850. this.waterFlowScale = this.imageScale * this.columns / this.oldColumn;
  4851. // 限制缩放范围,确保视觉效果自然
  4852. if (event.scale < 1) {
  4853. this.waterFlowScale = this.waterFlowScale > 1 ? this.waterFlowScale : 1;
  4854. } else {
  4855. this.waterFlowScale = this.waterFlowScale < 1 ? this.waterFlowScale : 1;
  4856. }
  4857. }
  4858. })
  4859. .onActionEnd((event: GestureEvent) => {
  4860. // 手势结束:执行归位动画并保存状态
  4861. // 执行归位动画:平滑过渡到正常状态
  4862. this.getUIContext()?.animateTo({ duration: 300 }, () => {
  4863. this.waterFlowScale = 1;
  4864. this.waterFlowOpacity = 1;
  4865. })
  4866. // 持久化保存当前列数:下次启动时恢复
  4867. PreferencesUtil.putSync('lastColumns', this.columns);
  4868. })
  4869. )
  4870. //允许拖拽音乐和视频到List或Grid上自动导入视频
  4871. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  4872. .onDrop((event?: DragEvent) => {
  4873. try {
  4874. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  4875. if (dragData !== undefined) {
  4876. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  4877. if (records.length > 0) {
  4878. for (let i = 0; i < records.length; i++) {
  4879. let types = records[i].getTypes();
  4880. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  4881. const fileUriUds =
  4882. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  4883. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  4884. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  4885. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  4886. this.targetFile = fileUriUds.oriUri;
  4887. this.saveVideoDatas([this.targetFile])
  4888. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  4889. }
  4890. }
  4891. }
  4892. } else {
  4893. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  4894. }
  4895. } else {
  4896. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  4897. }
  4898. } catch (error) {
  4899. const err = error as BusinessError;
  4900. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  4901. }
  4902. })
  4903. }
  4904. }
  4905. .scrollBar(BarState.Off)
  4906. }
  4907. //瀑布流卡片布局
  4908. @Builder
  4909. private MusicWaterCardItem(item: VideoItem, index: number) {
  4910. Button({ type: ButtonType.Normal, stateEffect: false }) {
  4911. Stack() {
  4912. Column() {
  4913. Image(item.pixelMapPath)
  4914. .backgroundImageSize(ImageSize.Auto)
  4915. .borderRadius({
  4916. topLeft: 12,
  4917. topRight : 12,
  4918. bottomLeft: 0,
  4919. bottomRight: 0
  4920. })
  4921. .draggable(false)// 禁止长按手势拖动
  4922. .autoResize(true) // 重采样,可减少内存占用
  4923. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  4924. .width('100%')
  4925. .height('auto')
  4926. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  4927. .objectFit(ImageFit.Auto)
  4928. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  4929. height: '99%' ,
  4930. dragBar: true,
  4931. onDisappear: () => {
  4932. this.longItemFilePath = '';
  4933. this.tempLyricContent = ''
  4934. },
  4935. showClose: true,
  4936. preferType: SheetType.CENTER ,
  4937. title: { title: '编辑标签' }
  4938. })
  4939. .draggable(false)
  4940. .opacity(this.opacityItem)// 绑定透明度
  4941. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  4942. // .animation({ duration: 500, curve: Curve.Ease }))
  4943. .animation({
  4944. duration: 666,
  4945. curve: 'ease-in-out' // 可选动画曲线
  4946. })
  4947. .margin({
  4948. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  4949. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  4950. })
  4951. Column() {
  4952. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  4953. .fontSize(this.columns == 4 ||this.columns==3? 12 : this.columns == 2 ? 15 : 18)
  4954. .maxLines(1)
  4955. .fontWeight(FontWeight.Bold)
  4956. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  4957. .animation({
  4958. duration: 555,
  4959. curve: 'Linear',
  4960. })
  4961. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  4962. height: '95%',
  4963. dragBar: true,
  4964. showClose: true,
  4965. onDisappear: () => {
  4966. this.longItemFilePathDetail = '';
  4967. },
  4968. blurStyle:BlurStyle.Thin,
  4969. backgroundColor:Color.Transparent,
  4970. preferType: SheetType.CENTER ,
  4971. title: { title: '详情' }
  4972. })
  4973. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4974. $r('app.color.text_color'))
  4975. Column() {
  4976. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  4977. .fontSize(11)
  4978. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  4979. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4980. .fontColor($r('app.color.text_color'))
  4981. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  4982. .fontSize(11)
  4983. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 14)
  4984. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  4985. .fontColor($r('app.color.text_color'))
  4986. Row(){
  4987. Column(){
  4988. Text(item.md5Str?.includes('Lossless')?
  4989. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  4990. .fontSize(this.columns == 4 ||this.columns==3? 8 : this.columns == 2 ? 9 : 11)
  4991. .padding({ top: 3,right:6,left:6,bottom:3 })
  4992. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  4993. $r('app.color.text_color'))
  4994. .fontWeight(500)
  4995. .borderRadius(12)
  4996. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  4997. .backgroundColor('#FFC107')
  4998. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  4999. }
  5000. .margin({ top: 2 ,right:6})
  5001. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  5002. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  5003. Text(StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  5004. .fontSize(this.columns == 4 ||this.columns==3? 10 : this.columns == 2 ? 12 : 13)
  5005. .maxLines(1)
  5006. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5007. .margin({ top: 2})
  5008. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  5009. || item.type == CommonConstants.TYPE_IS_ALBUM
  5010. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5011. .fontWeight(FontWeight.Medium)
  5012. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5013. $r('app.color.text_color'))
  5014. }
  5015. }
  5016. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  5017. }
  5018. .height(this.columns == 4 ||this.columns==3? item.type==CommonConstants.TYPE_IS_DIR?30:40
  5019. : this.columns == 2 ? (item.type==CommonConstants.TYPE_IS_DIR?38:48) :
  5020. (item.type==CommonConstants.TYPE_IS_DIR?48:58))
  5021. .width('100%')
  5022. .justifyContent(FlexAlign.Center)
  5023. .margin({
  5024. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5025. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5026. })
  5027. }
  5028. .width('100%')
  5029. .borderRadius(12)
  5030. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.alt') : item.pixelMapPath)
  5031. .backgroundImageSize({ height: '100%', width: '100%' })
  5032. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  5033. .animation({ curve: Curve.Sharp, duration: 300 })
  5034. Checkbox({ name: 'checkbox' + index })
  5035. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  5036. .selectedColor(this.themeColor)
  5037. .shape(CheckBoxShape.CIRCLE)
  5038. .opacity(this.isMultiSelect ? 1 : 0)
  5039. .animation({
  5040. duration: 666,
  5041. curve: 'Smooth' // 可选动画曲线
  5042. })
  5043. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  5044. Visibility.None)
  5045. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5046. .margin({ left: 20, top: 8, bottom: 8 })
  5047. .width(38)
  5048. .height(38)
  5049. }
  5050. }
  5051. .backgroundColor(Color.Transparent)
  5052. .width('100%')
  5053. .height('auto')
  5054. .padding({top:2})
  5055. .shadow({
  5056. radius: 10,
  5057. type: ShadowType.BLUR,
  5058. color: 'on_primary'
  5059. })
  5060. .reuseId('card_item')
  5061. .onClick(() => {
  5062. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5063. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5064. this.handleFileSelection(item, !isChecked);
  5065. } else {
  5066. this.doPlay(item, index)
  5067. }
  5068. })
  5069. }
  5070. // Grid布局的开始
  5071. private dragRefOffSetX: number = 0;
  5072. private dragRefOffSetY: number = 0;
  5073. private FIX_VP_X: number = 180;
  5074. private FIX_VP_Y: number = 84;
  5075. isDraggable(index: number): boolean {
  5076. return index >= 0;
  5077. }
  5078. getRowEnd(item: number) {
  5079. if (item.toString() === '0') {
  5080. return 1;
  5081. } else {
  5082. return 0;
  5083. }
  5084. }
  5085. isInLeft(index: number) {
  5086. return index % 2 == 0;
  5087. }
  5088. down(index: number): void {
  5089. if ([this.videoLocalList.length - 1, this.videoLocalList.length - 2].includes(index)) {
  5090. return;
  5091. }
  5092. this.offsetY -= this.FIX_VP_Y;
  5093. this.dragRefOffSetY += this.FIX_VP_Y;
  5094. this.itemMove(index, index + 1);
  5095. }
  5096. up(index: number): void {
  5097. if (!this.isDraggable(index - 2)) {
  5098. return;
  5099. }
  5100. this.offsetY += this.FIX_VP_Y;
  5101. this.dragRefOffSetY -= this.FIX_VP_Y;
  5102. this.itemMove(index, index - 1);
  5103. }
  5104. left(index: number): void {
  5105. if (this.isInLeft(index)) {
  5106. return;
  5107. }
  5108. if (!this.isDraggable(index - 1)) {
  5109. return;
  5110. }
  5111. this.offsetX += this.FIX_VP_X;
  5112. this.dragRefOffSetX -= this.FIX_VP_X;
  5113. this.itemMove(index, index - 1)
  5114. }
  5115. right(index: number): void {
  5116. if (!this.isInLeft(index)) {
  5117. return;
  5118. }
  5119. if (!this.isDraggable(index + 1)) {
  5120. return;
  5121. }
  5122. this.offsetX -= this.FIX_VP_X;
  5123. this.dragRefOffSetX += this.FIX_VP_X;
  5124. this.itemMove(index, index + 1)
  5125. }
  5126. private scroller: Scroller = new Scroller();
  5127. private waterScroller: Scroller = new Scroller();
  5128. @State startIndex: number = 0
  5129. @State endIndex: number = 0
  5130. @State scaleValue: number = 1
  5131. @State pinchValue: number = 1
  5132. layoutOptionsForHeader: GridLayoutOptions = {
  5133. regularSize: [1, 1], // 只支持[1, 1]
  5134. irregularIndexes: [0], // 索引为0的GridItem占用一行
  5135. };
  5136. @Builder
  5137. getGridView() {
  5138. Grid(this.scroller, this.layoutOptionsForHeader) {
  5139. GridItem() {
  5140. Column(){
  5141. Blank().height(this.topSafeHeight + 45)
  5142. }
  5143. }
  5144. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5145. GridItem() {
  5146. Stack({ alignContent: Alignment.Center }) {
  5147. this.MusicItemGrid(item, index)
  5148. }
  5149. }
  5150. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.LongPress,
  5151. {
  5152. preview: MenuPreviewMode.IMAGE,
  5153. previewAnimationOptions: { scale: [0.8, 1.0] },
  5154. })
  5155. .bindContextMenu(this.MenuBuilder(item, index, item.filePath), ResponseType.RightClick,
  5156. {
  5157. preview: MenuPreviewMode.IMAGE,
  5158. previewAnimationOptions: { scale: [0.8, 1.0] },
  5159. })
  5160. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.8, y: 0.8 }).animation({ duration: 500 }),
  5161. TransitionEffect.scale({ x: 0, y: 0 })))
  5162. .clickEffect({ level: ClickEffectLevel.LIGHT })
  5163. .scale({ x: this.scaleItem === index ? 1.02 : 1, y: this.scaleItem === index ? 1.02 : 1 })
  5164. .zIndex(this.dragItem === index ? 1 : 0)
  5165. .translate(this.dragItem === index ? { x: this.offsetX, y: this.offsetY } : { x: 0, y: 0 })
  5166. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5167. }
  5168. .width('94%')
  5169. .height('100%')
  5170. .editMode(true)
  5171. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  5172. .animation({ duration: 500, curve: Curve.Ease }))
  5173. .padding({bottom:this.bottomBarHeight+this.bottomSafeHeight+10})
  5174. .reuseId('grid_item')
  5175. .layoutWeight(1)
  5176. .scrollBar(BarState.Off)
  5177. .supportAnimation(true)
  5178. .cachedCount(this.twoFingerType==1?5:this.twoFingerType==2?4:3)
  5179. .columnsTemplate(
  5180. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  5181. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  5182. )
  5183. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  5184. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  5185. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  5186. .gesture(PinchGesture({ fingers: 2 })
  5187. .onActionEnd((event: GestureEvent) => {
  5188. this.setGridTwoFingers()
  5189. })
  5190. .onActionUpdate(e => {
  5191. this.scaleValue = this.pinchValue * e.scale
  5192. })
  5193. .onActionStart(e => {
  5194. }))
  5195. .enableScrollInteraction(true)
  5196. .onScrollIndex((start: number, end: number) => {
  5197. this.startIndex = start
  5198. this.endIndex = end
  5199. })
  5200. .onScrollFrameBegin((offset: number) => {
  5201. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  5202. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  5203. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  5204. if (this.isScrollHide) {
  5205. this.setBarHeightHide2(offset)
  5206. } else {
  5207. this.setBarHeightNormal()
  5208. }
  5209. } else {
  5210. this.setBarHeightHide(offset)
  5211. }
  5212. return { offsetRemain: offset };
  5213. })
  5214. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  5215. .onDrop((event?: DragEvent) => {
  5216. try {
  5217. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  5218. if (dragData !== undefined) {
  5219. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  5220. if (records.length > 0) {
  5221. for (let i = 0; i < records.length; i++) {
  5222. let types = records[i].getTypes();
  5223. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  5224. const fileUriUds =
  5225. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  5226. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  5227. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  5228. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  5229. this.targetFile = fileUriUds.oriUri;
  5230. this.saveVideoDatas([this.targetFile])
  5231. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  5232. }
  5233. }
  5234. }
  5235. } else {
  5236. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  5237. }
  5238. } else {
  5239. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  5240. }
  5241. } catch (error) {
  5242. const err = error as BusinessError;
  5243. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  5244. }
  5245. })
  5246. }
  5247. @State targetFile: string = '';
  5248. setGridTwoFingers() {
  5249. this.pinchValue = this.scaleValue;
  5250. Logger.info('this.pinchValue = ' + this.pinchValue);
  5251. if (this.pinchValue >= 1) {
  5252. this.twoFingerType++
  5253. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  5254. if(this.twoFingerType >= 4){
  5255. this.twoFingerType = 4//切换成瀑布流
  5256. this.columns = 4
  5257. }
  5258. } else {
  5259. this.twoFingerType--
  5260. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  5261. if (this.twoFingerType < 1) {
  5262. this.twoFingerType = 3
  5263. this.isGridMusic = false
  5264. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5265. }
  5266. }
  5267. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  5268. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5269. this.pinchValue = 1;
  5270. this.scaleValue = 1;
  5271. }
  5272. @State longItemFilePath: string = ''
  5273. @State tempLyricContent: string = ''
  5274. @State editingItem: VideoItem | null = null
  5275. @Builder
  5276. private MusicItemGrid(item: VideoItem, index: number) {
  5277. Button({ type: ButtonType.Normal, stateEffect: false }) {
  5278. Stack() {
  5279. Column() {
  5280. Image(item.pixelMapPath)
  5281. .height(this.getGridHeight())
  5282. .width(this.getGridWight())
  5283. .draggable(false)
  5284. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  5285. .autoResize(true) // 重采样,可减少内存占用
  5286. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  5287. .clip(true)
  5288. .borderRadius({
  5289. topLeft: 12,
  5290. topRight: 12,
  5291. bottomLeft: 0,
  5292. bottomRight: 0
  5293. })
  5294. .bindSheet(this.longItemFilePath== item.filePath, this.editSheet(item), {
  5295. height: '99%' ,
  5296. dragBar: true,
  5297. onDisappear: () => {
  5298. this.longItemFilePath = '';
  5299. this.tempLyricContent = ''
  5300. },
  5301. showClose: true,
  5302. preferType: SheetType.CENTER ,
  5303. title: { title: '编辑标签' }
  5304. })
  5305. .draggable(false)
  5306. .opacity(this.opacityItem)// 绑定透明度
  5307. .animation({
  5308. duration: 666,
  5309. curve: 'ease-in-out' // 可选动画曲线
  5310. })
  5311. .margin({
  5312. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5313. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5314. })
  5315. Column() {
  5316. Text(this.isShowFileName&&item.type!=CommonConstants.TYPE_IS_DIR?item.fileName :item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  5317. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  5318. .maxLines(1)
  5319. .fontWeight(FontWeight.Bold)
  5320. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5321. .animation({
  5322. duration: 555,
  5323. curve: 'Linear',
  5324. })
  5325. .bindSheet(this.longItemFilePathDetail== item.filePath, this.detailSheet(item), {
  5326. height: '95%',
  5327. dragBar: true,
  5328. showClose: true,
  5329. onDisappear: () => {
  5330. this.longItemFilePathDetail = '';
  5331. },
  5332. blurStyle:BlurStyle.Thin,
  5333. backgroundColor:Color.Transparent,
  5334. preferType: SheetType.CENTER ,
  5335. title: { title: '详情' }
  5336. })
  5337. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5338. $r('app.color.text_color'))
  5339. Column() {
  5340. Text(`${this.artistMap.get(item.name)?.length ?? 0}首`)
  5341. .fontSize(11)
  5342. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  5343. .visibility(this.modeType === 2 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5344. .fontColor($r('app.color.text_color'))
  5345. Text(`${this.albumMap.get(item.name)?.length ?? 0}首`)
  5346. .fontSize(11)
  5347. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  5348. .visibility(this.modeType === 3 && !this.isCanBack ? Visibility.Visible : Visibility.None)
  5349. .fontColor($r('app.color.text_color'))
  5350. Row(){
  5351. Column(){
  5352. Text(item.md5Str?.includes('Lossless')?
  5353. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  5354. .fontSize(this.twoFingerType == 1 ? 8 : this.twoFingerType == 2 ? 9 : 11)
  5355. .padding({ top: 3,right:6,left:6,bottom:3 })
  5356. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5357. $r('app.color.text_color'))
  5358. .fontWeight(500)
  5359. .borderRadius(12)
  5360. .margin({ left: this.twoFingerType == 3 ? 6 : 8 })
  5361. .backgroundColor('#FFC107')
  5362. .visibility(StrUtil.isEmpty(item.md5Str)||this.twoFingerType==1?Visibility.None:Visibility.Visible)
  5363. }
  5364. .margin({ top: 2 ,right:6})
  5365. .visibility((this.modeType == 3 && !this.isCanBack)||(this.modeType == 2 && !this.isCanBack)
  5366. ||(this.modeType == 0&&item.type==CommonConstants.TYPE_IS_DIR)? Visibility.None : Visibility.Visible)
  5367. Text(this.isShowFileName?item.duration:StrUtil.isEmpty(item.artist) ? item.duration: item.artist)
  5368. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  5369. .maxLines(1)
  5370. .textOverflow({ overflow: this.isLongNameRoLL?TextOverflow.MARQUEE:TextOverflow.Ellipsis })//超长滚动
  5371. .margin({ top: 2})
  5372. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  5373. || item.type == CommonConstants.TYPE_IS_ALBUM
  5374. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5375. .fontWeight(FontWeight.Medium)
  5376. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  5377. $r('app.color.text_color'))
  5378. }
  5379. }
  5380. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  5381. }
  5382. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  5383. .width(this.getGridWight())
  5384. .justifyContent(FlexAlign.Center)
  5385. .margin({
  5386. left: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20,
  5387. right: this.currentBreakpoint !== BreakpointTypeEnum.SM ? 40 : 20
  5388. })
  5389. }
  5390. .width(this.getGridWight())
  5391. .borderRadius(12)
  5392. .backgroundImage(StrUtil.isEmpty(item.pixelMapPath)?undefined:item.pixelMapPath)
  5393. .backgroundImageSize({ height: '100%', width: '100%' })
  5394. .backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK)
  5395. .animation({ curve: Curve.Sharp, duration: 300 })
  5396. Checkbox({ name: 'checkbox' + index })
  5397. .select(this.selectedFiles.some(x => x.filePath == item.filePath))
  5398. .selectedColor(this.themeColor)
  5399. .shape(CheckBoxShape.CIRCLE)
  5400. .opacity(this.isMultiSelect ? 1 : 0)
  5401. .animation({
  5402. duration: 666,
  5403. curve: 'Smooth' // 可选动画曲线
  5404. })
  5405. .visibility(this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR ? Visibility.Visible :
  5406. Visibility.None)
  5407. .onChange((checked: boolean) => this.handleFileSelection(item, checked))
  5408. .margin({ left: 20, top: 8, bottom: 8 })
  5409. .width(38)
  5410. .height(38)
  5411. }
  5412. }
  5413. .backgroundColor(Color.Transparent)
  5414. .width('100%')
  5415. .padding({ top: 15 })
  5416. .height(this.getGridAllHeight())
  5417. .onClick(() => {
  5418. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5419. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5420. this.handleFileSelection(item, !isChecked);
  5421. } else {
  5422. this.doPlay(item, index)
  5423. }
  5424. })
  5425. }
  5426. getGridAllHeight() {
  5427. let heightG = 222
  5428. switch (this.twoFingerType) {
  5429. case 1:
  5430. heightG = 143
  5431. break;
  5432. case 2:
  5433. heightG = 178
  5434. break;
  5435. case 3:
  5436. heightG = 222
  5437. break;
  5438. }
  5439. return heightG
  5440. }
  5441. getGridHeight() {
  5442. let heightG = 150
  5443. switch (this.twoFingerType) {
  5444. case 1:
  5445. heightG = 80
  5446. break;
  5447. case 2:
  5448. heightG = 110
  5449. break;
  5450. case 3:
  5451. heightG = 150
  5452. break;
  5453. }
  5454. return heightG
  5455. }
  5456. getGridWight() {
  5457. let wightG = 158
  5458. switch (this.twoFingerType) {
  5459. case 1:
  5460. wightG = 80
  5461. break;
  5462. case 2:
  5463. wightG = 110
  5464. break;
  5465. case 3:
  5466. wightG = 158
  5467. break;
  5468. }
  5469. return wightG
  5470. }
  5471. @State isShowDetail:boolean = false
  5472. @State longItemFilePathDetail:string =''
  5473. @Builder
  5474. MenuBuilder(item: VideoItem, index: number, filePath: string) {
  5475. if(
  5476. ((this.modeType===2||this.modeType==3)&&!this.isCanBack)
  5477. ||(item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5478. item.name === LocalMusic.STR_HISTORY_MUSIC)
  5479. ){
  5480. //如果是专辑和艺术家的首页,不能长按
  5481. //如果是我的收藏 最近播放等也不能长按
  5482. }else{
  5483. Scroll() {
  5484. Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
  5485. Menu() {
  5486. MenuItem({
  5487. symbolStartIcon: new SymbolGlyphModifier(Utility.getIsFav(this.favList, item) ?
  5488. $r('sys.symbol.heart_fill') : $r('sys.symbol.heart')),
  5489. content: Utility.getIsFav(this.favList, item) ? '取消收藏' : '收藏'
  5490. })
  5491. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5492. .onClick(() => {
  5493. if (item) {
  5494. this.doFav(item)
  5495. }
  5496. this.longItemFilePath = ''
  5497. })
  5498. MenuItem({
  5499. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.forward_end_fill')),
  5500. content: '下一首播放'
  5501. })
  5502. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5503. .onClick(() => {
  5504. this.addToNextPlay(item);
  5505. this.longItemFilePath = ''
  5506. })
  5507. MenuItem({
  5508. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music_note_list')),
  5509. content: '添加到歌单'
  5510. })
  5511. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5512. .onClick(async () => {
  5513. this.longItemFilePath = ''
  5514. await this.openAddToPlaylistDialog(item)
  5515. })
  5516. MenuItem({
  5517. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.square_and_pencil')),
  5518. content: '编辑标签'
  5519. })
  5520. .bindSheet($$this.isShowEdit, this.editSheet(item), {
  5521. height: '99%',
  5522. dragBar: true,
  5523. showClose: true,
  5524. preferType: SheetType.CENTER ,
  5525. title: { title: '编辑标签' }
  5526. })
  5527. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5528. .onClick(async() => {
  5529. this.initEditFields(item)
  5530. this.tempLyricContent = await this.getLyricContent(item);
  5531. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  5532. this.lyricConStr = this.tempLyricContent
  5533. }
  5534. if(this.isGridMusic||this.twoFingerType==4){
  5535. this.longItemFilePath = item.filePath
  5536. }else{
  5537. this.isShowEdit = !this.isShowEdit;
  5538. }
  5539. })
  5540. MenuItem({
  5541. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.checkmark_square_on_square')),
  5542. content: $r('app.string.select_all')
  5543. })
  5544. .onClick(() => {
  5545. this.isMultiSelect = !this.isMultiSelect
  5546. this.longItemFilePath = ''
  5547. this.selectedFiles.push(item)
  5548. })
  5549. MenuItem({
  5550. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.cut')),
  5551. content: $r('app.string.edit_audio')
  5552. })
  5553. .bindContentCover($$this.isEditAudio, this.EditAudioBuilder(item), {
  5554. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5555. })
  5556. .onClick(() => {
  5557. this.isEditAudio = !this.isEditAudio
  5558. })
  5559. MenuItem({
  5560. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.music')),
  5561. content: $r('app.string.extract_accompaniment')
  5562. })
  5563. .bindContentCover($$this.isExtractAcc, this.ExtractAccBuilder(item), {
  5564. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5565. })
  5566. .onClick(() => {
  5567. if (!Utility.isNoble()) {
  5568. this.showVipDialog()
  5569. return
  5570. }
  5571. this.isExtractAcc = !this.isExtractAcc
  5572. })
  5573. MenuItem({
  5574. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.repeat')),
  5575. content: $r('app.string.converter_audio')
  5576. })
  5577. .bindContentCover($$this.isConverter, this.ConverterBuilder(item), {
  5578. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5579. })
  5580. .onClick(() => {
  5581. if (!Utility.isNoble()) {
  5582. this.showVipDialog()
  5583. return
  5584. }
  5585. this.isConverter = !this.isConverter
  5586. })
  5587. MenuItem({
  5588. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.ai_edit')),
  5589. content: $r('app.string.vocal_separation')
  5590. })
  5591. .bindContentCover($$this.isAIVoiceSeparation, this.AiBuilder(item), {
  5592. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5593. })
  5594. .onClick(() => {
  5595. this.isAIVoiceSeparation = !this.isAIVoiceSeparation
  5596. })
  5597. MenuItem({
  5598. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.arrow_counterclockwise_clock')),
  5599. content: $r('app.string.change_tone')
  5600. })
  5601. .bindContentCover($$this.isChangeTone, this.ChangeToneBuilder(item), {
  5602. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5603. })
  5604. .onClick(() => {
  5605. this.isChangeTone = !this.isChangeTone
  5606. })
  5607. if(Utility.isVideoByExtension(item.filePath)){
  5608. MenuItem({
  5609. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.identify_song')),
  5610. content: $r('app.string.extract_audio')
  5611. })
  5612. .bindContentCover($$this.isExtractAudio, this.extractAudioFromVideoBuilder(item), {
  5613. transition: TransitionEffect.translate({ x: 500 }).animation({ curve: curves.springMotion(0.6, 0.8) })
  5614. })
  5615. .onClick(() => {
  5616. this.isExtractAudio = !this.isExtractAudio
  5617. })
  5618. }
  5619. MenuItem({
  5620. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.phone')),
  5621. content: $r('app.string.set_ring')
  5622. })
  5623. .onClick(async () => {
  5624. await PermissionUtil.activatePermission(item.filePath)
  5625. // if(item.filePath.includes(this.packName)){
  5626. setRingTone(this.context, item.filePath,item.name)
  5627. // }else{
  5628. // ToastUtil.showToast('请把该音频导入到本应用的DownLoad文件下,其他路径音频无权限设置铃声')
  5629. // }
  5630. this.longItemFilePath = ''
  5631. })
  5632. MenuItem({
  5633. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.rename')),
  5634. content: $r('app.string.rename')
  5635. })
  5636. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  5637. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5638. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  5639. .onClick(() => {
  5640. this.showReNameDialog(item, index + '', filePath)
  5641. this.longItemFilePath = ''
  5642. })
  5643. MenuItem({
  5644. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.trash')),
  5645. content: $r('app.string.delete')
  5646. })
  5647. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  5648. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  5649. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  5650. .onClick(() => {
  5651. this.selectedFiles.push(item)
  5652. this.showWarnIsDelete()
  5653. this.longItemFilePath = ''
  5654. })
  5655. MenuItem({
  5656. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.info_circle')),
  5657. content: $r('app.string.detail')
  5658. })
  5659. .bindSheet($$this.isShowDetail, this.detailSheet(item), {
  5660. height:'95%',
  5661. dragBar: true,
  5662. showClose: true,
  5663. blurStyle:BlurStyle.Thin,
  5664. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  5665. backgroundColor:Color.Transparent,
  5666. title: { title: '详情信息' }
  5667. })
  5668. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5669. .onClick(() => {
  5670. if(this.isGridMusic||this.twoFingerType==4){
  5671. this.longItemFilePathDetail = item.filePath
  5672. }else{
  5673. this.isShowDetail = !this.isShowDetail
  5674. }
  5675. })
  5676. MenuItem({
  5677. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.share')),
  5678. content: $r('app.string.share')
  5679. })
  5680. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  5681. .onClick(() => {
  5682. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  5683. this.longItemFilePath = ''
  5684. })
  5685. }
  5686. .font({ size: 14, weight: FontWeight.Normal })
  5687. }
  5688. .width(180)
  5689. }
  5690. .height('auto')
  5691. }
  5692. }
  5693. private listMaxScrollOffsetY: number = 0
  5694. @State selectedIndex: number = -1
  5695. setlistTwoFingers() {
  5696. this.pinchValue = this.scaleValue;
  5697. Logger.info('this.pinchValue = ' + this.pinchValue);
  5698. if (this.pinchValue >= 1) {
  5699. this.twoFingerType++
  5700. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  5701. if (this.twoFingerType > 3) {
  5702. this.twoFingerType = 1
  5703. this.isGridMusic = true
  5704. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5705. }
  5706. } else {
  5707. this.twoFingerType--
  5708. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  5709. if (this.twoFingerType < 1) {
  5710. this.twoFingerType = 4
  5711. this.columns = 1
  5712. }
  5713. }
  5714. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  5715. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  5716. this.pinchValue = 1;
  5717. this.scaleValue = 1;
  5718. }
  5719. @Builder
  5720. getList(){
  5721. Stack() {
  5722. Refresh({ refreshing: $$this.isRefreshing, refreshingContent: this.contentNode }) {
  5723. this.getListView()
  5724. }
  5725. .pullDownRatio(this.ratioL)
  5726. .pullToRefresh(true)
  5727. .refreshOffset(0)
  5728. .onOffsetChange((offset: number) => {
  5729. // 越接近最大距离,下拉跟手系数越小。
  5730. this.ratioL = 1 - Math.pow((offset / this.maxRefreshingHeight), 3);
  5731. })
  5732. .onStateChange((refreshStatus: RefreshStatus) => {
  5733. console.info('onecold Refresh onStatueChange state is ' + refreshStatus);
  5734. })
  5735. .onRefreshing(async () => {
  5736. if(this.modeType==0){
  5737. this.getHistoryList(false)
  5738. this.asyncCurrentPathOnlyFile()
  5739. }else if(this.modeType == 1){
  5740. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  5741. }else if(this.modeType == 2){
  5742. workerInstance.postMessage({ code: 3, data: this.context });
  5743. }else if(this.modeType == 3){
  5744. workerInstance.postMessage({ code: 4, data: this.context });
  5745. }else if(this.modeType == 4){
  5746. this.doSongListTask()
  5747. }
  5748. console.log('onRefreshing test');
  5749. })
  5750. }
  5751. }
  5752. // 扫描当前目录下的文件,不扫描子目录
  5753. asyncCurrentPathOnlyFile(){
  5754. if(this.modeType==0){
  5755. const task = new taskpool.Task(scanCurrentDirectoryTask, getContext(this), this.currentPath,
  5756. this.lockPath,PreferencesUtil.getStringSync('COVER_API',''));
  5757. taskpool.execute(task, taskpool.Priority.HIGH).then(()=>{
  5758. if(this.modeType==0){
  5759. setTimeout(()=>{
  5760. this.isRefreshing =false
  5761. this.deleteCache(this.currentPath)
  5762. this.getSortedFiles(this.currentPath)
  5763. },500)
  5764. }
  5765. }).catch((e:object)=>{
  5766. this.isRefreshing =false
  5767. console.info("onecold task1 catch e: " + e);
  5768. })
  5769. }
  5770. }
  5771. @Builder
  5772. getListView() {
  5773. List({ scroller: this.listScroller }) {
  5774. // ListItemGroup({ header: this.coverHeader() }) {
  5775. LazyForEach(this.dataSource, (item: VideoItem, index: number) => {
  5776. ListItem() {
  5777. Column() {
  5778. if (item.type === CommonConstants.TYPE_IS_DIR
  5779. || item.type === CommonConstants.TYPE_IS_ARTIST || item.type === CommonConstants.TYPE_IS_ALBUM) {
  5780. this.DirItem(item, index)
  5781. } else if (item.type === CommonConstants.TYPE_IS_CSJAD) { //如果是穿山甲广告
  5782. } else {
  5783. this.MusicItem(item, index)
  5784. }
  5785. }
  5786. .shadow(this.scaleItem === index ? {
  5787. radius: 70,
  5788. color: '#15000000',
  5789. offsetX: 0,
  5790. offsetY: 0
  5791. } :
  5792. {
  5793. radius: 0,
  5794. color: '#15000000',
  5795. offsetX: 0,
  5796. offsetY: 0
  5797. })
  5798. .animation({ curve: Curve.Sharp, duration: 300 })
  5799. }
  5800. // .transition(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }))
  5801. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0.9, y: 0.9 })
  5802. .animation({ duration: 500 }),
  5803. TransitionEffect.scale({ x: 0, y: 0 })))
  5804. .clickEffect({ level: ClickEffectLevel.LIGHT })
  5805. .swipeAction((
  5806. (this.isSwipe&&this.modeType == 0 || this.modeType == 1 || ((this.modeType == 3 || this.modeType == 2) && this.isCanBack))
  5807. && item.type !== CommonConstants.TYPE_IS_CSJAD &&
  5808. !this.isHistory) ? { end: this.DeleteButton(item, index, item.filePath),
  5809. start:null,edgeEffect: SwipeEdgeEffect.None } : {}) //左滑
  5810. .onClick(() => {
  5811. if (this.isMultiSelect && item.type !== CommonConstants.TYPE_IS_DIR) {
  5812. const isChecked = this.selectedFiles.some(x => x.filePath == item.filePath);
  5813. this.handleFileSelection(item, !isChecked);
  5814. } else {
  5815. this.doPlay(item, index)
  5816. }
  5817. })
  5818. //拖动List关键代码开始
  5819. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  5820. .zIndex(this.dragItem === index ? 1 : 0)
  5821. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  5822. .gesture(
  5823. GestureGroup(GestureMode.Sequence,
  5824. LongPressGesture({ repeat: true })
  5825. .onAction((event?: GestureEvent) => {
  5826. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5827. this.scaleItem = index
  5828. })
  5829. })
  5830. .onActionEnd(() => {
  5831. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  5832. this.scaleItem = -1
  5833. })
  5834. }),
  5835. PanGesture({ fingers: 1, direction: null, distance: 0 })
  5836. .onActionStart(() => {
  5837. this.dragItem = index // 记录当前拖动项索引
  5838. this.dragRefOffset = 0 // 重置偏移基准
  5839. })
  5840. .onActionUpdate((event: GestureEvent) => {
  5841. this.offsetY = event.offsetY - this.dragRefOffset;
  5842. this.neighborItem = -1;
  5843. let indexA = this.videoLocalList.indexOf(item);
  5844. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  5845. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  5846. let value: number = 0;
  5847. if (this.offsetY < 0) {
  5848. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  5849. this.neighborItem = indexA - 1;
  5850. this.neighborScale = 1 - value / 20;
  5851. } else if (this.offsetY > 0) {
  5852. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  5853. this.neighborItem = indexA + 1;
  5854. this.neighborScale = 1 - value / 20;
  5855. }
  5856. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.videoLocalList.length) {
  5857. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5858. this.offsetY -= this.ITEM_INTV;
  5859. this.dragRefOffset += this.ITEM_INTV;
  5860. this.itemMove(indexA, indexA + 1);
  5861. });
  5862. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  5863. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5864. this.offsetY += this.ITEM_INTV;
  5865. this.dragRefOffset -= this.ITEM_INTV;
  5866. this.itemMove(indexA, indexA - 1);
  5867. });
  5868. }
  5869. let curListOffset = this.listScroller.currentOffset()
  5870. // 获取手指信息
  5871. let fingerInfo = event.fingerList[0]
  5872. let clickPercentY =
  5873. (fingerInfo.globalY - Number(this.listArea.globalPosition.y)) / Number(this.listArea.height)
  5874. if (clickPercentY > 0.8 && !this.listScroller.isAtEnd()) {
  5875. let scrollVelocity = clickPercentY > 0.9 ? 4 : 2
  5876. if (this.listMaxScrollOffsetY - curListOffset.yOffset > scrollVelocity + 5) {
  5877. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset += scrollVelocity })
  5878. }
  5879. } else if (clickPercentY < 0.2 && curListOffset.yOffset >= 0) {
  5880. let scrollVelocity = clickPercentY < 0.1 ? 4 : 2
  5881. if (curListOffset.yOffset > scrollVelocity + 5) {
  5882. this.listScroller.scrollTo({ xOffset: 0, yOffset: curListOffset.yOffset -= scrollVelocity })
  5883. }
  5884. }
  5885. })
  5886. .onActionEnd((event: GestureEvent) => {
  5887. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5888. this.dragItem = -1
  5889. this.neighborItem = -1
  5890. })
  5891. animateTo({
  5892. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  5893. }, () => {
  5894. this.scaleItem = -1
  5895. })
  5896. })
  5897. )
  5898. .onCancel(() => {
  5899. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  5900. this.dragItem = -1
  5901. this.neighborItem = -1
  5902. })
  5903. animateTo({
  5904. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  5905. }, () => {
  5906. this.scaleItem = -1
  5907. })
  5908. })
  5909. ) //拖动List关键代码结束
  5910. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  5911. // }
  5912. }
  5913. .onScrollStart(() => {
  5914. this.isScrolling = true
  5915. this.isShowAlphaBet = true
  5916. })
  5917. .onScrollIndex((start: number,center:number,end:number) => {
  5918. this.selectedIndex = start
  5919. if(start >= 0 && start < this.videoLocalList.length){
  5920. this.selectAlphaBetIndex = this.findAlphaBetIndex(this.videoLocalList[start])
  5921. }
  5922. })
  5923. .onScrollStop(() => {
  5924. if(this.isScrolling){
  5925. this.isScrolling = false
  5926. }
  5927. this.isShowAlphaBet = false
  5928. })
  5929. .scrollBar(BarState.Off)
  5930. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  5931. .gesture(PinchGesture({ fingers: 2 })
  5932. .onActionEnd((event: GestureEvent) => {
  5933. this.setlistTwoFingers()
  5934. })
  5935. .onActionUpdate(e => {
  5936. this.scaleValue = this.pinchValue * e.scale
  5937. })
  5938. .onActionStart(e => {
  5939. }))
  5940. .contentStartOffset(this.topSafeHeight + 55)
  5941. .scrollBar(BarState.Off)
  5942. .contentEndOffset(this.bottomBarHeight+this.bottomSafeHeight)
  5943. .cachedCount(10)
  5944. // .reuseId('list_item')
  5945. .borderRadius(20)
  5946. .layoutWeight(1)
  5947. .visibility(this.isGridMusic ? Visibility.None : Visibility.Visible)
  5948. .lanes(
  5949. new BreakpointType<number>({
  5950. sm: 1,
  5951. md: 2,
  5952. lg: 2,
  5953. xl: 3,
  5954. xxl: 4
  5955. }).getValue(this.currentBreakpoint),
  5956. new BreakpointType<number>({
  5957. sm: 0,
  5958. md: 12,
  5959. lg: 12,
  5960. xl: 16,
  5961. xxl: 20
  5962. }).getValue(this.currentBreakpoint)
  5963. )
  5964. .onAreaChange((oldValue: Area, newValue: Area) => {
  5965. this.listArea = newValue
  5966. if (this.twoFingerType == 3) {
  5967. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_BIG) - 10
  5968. } else if (this.twoFingerType == 2) {
  5969. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT) - 10
  5970. } else if (this.twoFingerType == 1) {
  5971. this.listMaxScrollOffsetY = this.videoLocalList.length * (ITEM_HEIGHT_SMALL) - 10
  5972. }
  5973. })
  5974. .onScrollFrameBegin((offset: number) => {
  5975. //滚动小屏幕 比如puraX外屏和手机横屏可以隐藏bottomBarHeight topBarHeight
  5976. // if (this.isPhoneLan()) {
  5977. // this.setBarHeightHide(offset)
  5978. // } else
  5979. if (this.currentWidthBreakpoint !== WidthBreakpoint.WIDTH_SM ||
  5980. (this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_MD &&
  5981. this.currentHeightBreakpoint !== HeightBreakpoint.HEIGHT_SM)) {
  5982. if (this.isScrollHide) {
  5983. this.setBarHeightHide2(offset)
  5984. } else {
  5985. this.setBarHeightNormal()
  5986. }
  5987. } else {
  5988. this.setBarHeightHide(offset)
  5989. }
  5990. return { offsetRemain: offset };
  5991. })
  5992. //拖拽pc或者pad的用鼠标拖拽音乐和视频到List或Grid上自动导入视频
  5993. .allowDrop([uniformTypeDescriptor.UniformDataType.AUDIO,uniformTypeDescriptor.UniformDataType.VIDEO])
  5994. .onDrop((event?: DragEvent) => {
  5995. try {
  5996. let dragData: UnifiedData = (event as DragEvent).getData() as UnifiedData;
  5997. if (dragData !== undefined) {
  5998. let records: unifiedDataChannel.UnifiedRecord[] = dragData.getRecords();
  5999. if (records.length > 0) {
  6000. for (let i = 0; i < records.length; i++) {
  6001. let types = records[i].getTypes();
  6002. if (types.includes(uniformTypeDescriptor.UniformDataType.FILE_URI)) {
  6003. const fileUriUds =
  6004. records[i].getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri;
  6005. let typeDescriptor = uniformTypeDescriptor.getTypeDescriptor(fileUriUds.fileType);
  6006. if (typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.AUDIO)
  6007. ||typeDescriptor.belongsTo(uniformTypeDescriptor.UniformDataType.VIDEO)) {
  6008. this.targetFile = fileUriUds.oriUri;
  6009. this.saveVideoDatas([this.targetFile])
  6010. hilog.info(0x0000, 'Heanup', '当前targetFile:' + this.targetFile);
  6011. }
  6012. }
  6013. }
  6014. } else {
  6015. hilog.info(0x0000, TAG, `%{public}s`, `dragData arr is null`);
  6016. }
  6017. } else {
  6018. hilog.info(0x0000, TAG, `%{public}s`, `dragData is undefined`);
  6019. }
  6020. } catch (error) {
  6021. const err = error as BusinessError;
  6022. hilog.error(0x0000, TAG, `startDataLoading errorCode: ${err.code}, errorMessage: ${err.message}`);
  6023. }
  6024. })
  6025. }
  6026. setBarHeightNormal() {
  6027. this.hideDone = false;
  6028. this.getUIContext().animateTo({
  6029. duration: 300
  6030. }, () => {
  6031. this.bottomBarHeight = 68 + 0;
  6032. this.topBarHeight = 50 + 0;
  6033. this.barOpacity = 1;
  6034. this.barBottomOpacity = 1
  6035. this.currentYOffset = 0;
  6036. this.isHiding = false;
  6037. });
  6038. }
  6039. setBarHeightHide(offset: number) {
  6040. if (offset > 0 && !this.hideDone) {
  6041. this.currentYOffset += offset;
  6042. if (this.currentYOffset <= 100) {
  6043. this.bottomBarHeight = this.bottomBarHeight * (1 - this.currentYOffset / 100);
  6044. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  6045. this.barOpacity = 1 - this.currentYOffset / 100;
  6046. this.barBottomOpacity = 1 - this.currentYOffset / 100;
  6047. } else {
  6048. this.topBarHeight = 0;
  6049. this.bottomBarHeight = 0;
  6050. this.barBottomOpacity = 0
  6051. this.barOpacity = 0;
  6052. this.hideDone = true;
  6053. }
  6054. this.isHiding = true;
  6055. }
  6056. if (offset < 0 && this.isHiding) {
  6057. this.hideDone = false;
  6058. this.getUIContext().animateTo({
  6059. duration: 300
  6060. }, () => {
  6061. this.bottomBarHeight = 68 + 0;
  6062. this.topBarHeight = 50 + 0;
  6063. this.barOpacity = 1;
  6064. this.barBottomOpacity = 1
  6065. this.currentYOffset = 0;
  6066. this.isHiding = false;
  6067. });
  6068. }
  6069. }
  6070. //这个方法没隐藏bottomBar,只隐藏topbar
  6071. setBarHeightHide2(offset: number) {
  6072. if (offset > 0 && !this.hideDone) {
  6073. this.currentYOffset += offset;
  6074. if (this.currentYOffset <= 100) {
  6075. this.topBarHeight = this.topBarHeight * (1 - this.currentYOffset / 100);
  6076. this.barOpacity = 1 - this.currentYOffset / 100;
  6077. } else {
  6078. this.topBarHeight = 0;
  6079. this.barOpacity = 0;
  6080. this.hideDone = true;
  6081. }
  6082. this.isHiding = true;
  6083. }
  6084. if (offset < 0 && this.isHiding) {
  6085. this.hideDone = false;
  6086. this.getUIContext().animateTo({
  6087. duration: 300
  6088. }, () => {
  6089. this.topBarHeight = 50 + 0;
  6090. this.barOpacity = 1;
  6091. this.currentYOffset = 0;
  6092. this.isHiding = false;
  6093. });
  6094. }
  6095. }
  6096. private async doPlay(item: VideoItem, index?: number, isFromSonPlayList?: boolean,isOpen?:boolean) {
  6097. Logger.info(`heanup doPlay被调用 - 歌曲: ${item.name}, 文件路径: ${item.filePath}, 索引: ${index}, 类型: ${item.type}, isFromSonPlayList: ${isFromSonPlayList}`)
  6098. switch (item.type) {
  6099. case CommonConstants.TYPE_IS_DIR:
  6100. // 进入歌单前安全保存当前滚动偏移量,支持列表和网格
  6101. let offsetB = 0
  6102. if(this.twoFingerType==4){
  6103. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6104. let cur = this.waterScroller.currentOffset()
  6105. if (cur && typeof cur.yOffset === 'number') {
  6106. offsetB = cur.yOffset
  6107. }
  6108. }
  6109. this.mScrollMap.set('lastWaterDirScrollOffset', offsetB)
  6110. }else
  6111. if (this.isGridMusic) {
  6112. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6113. let cur = this.scroller.currentOffset()
  6114. if (cur && typeof cur.yOffset === 'number') {
  6115. offsetB = cur.yOffset
  6116. }
  6117. }
  6118. this.mScrollMap.set('lastGridDirScrollOffset', offsetB)
  6119. } else {
  6120. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6121. let cur = this.listScroller.currentOffset()
  6122. if (cur && typeof cur.yOffset === 'number') {
  6123. offsetB = cur.yOffset
  6124. }
  6125. }
  6126. this.mScrollMap.set('lastListDirScrollOffset', offsetB)
  6127. }
  6128. if (item.name === LocalMusic.STR_LOCK_VIDEO) {
  6129. this.showVerifyDialog()
  6130. this.currentTitleName = '私密音频'
  6131. this.currentTitleCover = $r('app.media.alt')
  6132. } else if (item.name === LocalMusic.STR_HISTORY_MUSIC) {
  6133. this.titleName = '最近播放'
  6134. this.currentTitleCover = $r('app.media.alt')
  6135. this.currentTitleName = '最近播放'
  6136. //加载动画效果
  6137. this.updateListData(this.historyList, true)
  6138. // this.videoLocalList = this.historyList
  6139. if (ArrayUtil.isEmpty(this.historyList)) {
  6140. ToastUtil.showToast('最近播放记录空空如也')
  6141. } else {
  6142. this.currentTitleCover = Utility.getFirstCoverFromList(this.historyList)
  6143. }
  6144. this.isHistory = true
  6145. } else if (item.name === LocalMusic.STR_FAC_VIDEO) {
  6146. this.titleName = '我的收藏'
  6147. this.currentTitleName = '我的收藏'
  6148. this.currentTitleCover = $r('app.media.alt')
  6149. //加载动画效果
  6150. this.updateListData(this.favList)
  6151. if (ArrayUtil.isEmpty(this.favList)) {
  6152. ToastUtil.showToast('无音乐收藏记录')
  6153. } else {
  6154. this.currentTitleCover = Utility.getFirstCoverFromList(this.favList)
  6155. }
  6156. this.isFavMusic = true
  6157. } else {
  6158. this.currentTitleName = item.name
  6159. this.currentPath = item.filePath
  6160. this.currentTitleCover = $r('app.media.alt')
  6161. this.getSortedFiles(this.currentPath)
  6162. }
  6163. //进入歌单的时候的滚动位置在顶部
  6164. if(this.twoFingerType==4){
  6165. setTimeout(() => {
  6166. this.waterScroller.scrollEdge(Edge.Top)
  6167. this.scroller.scrollEdge(Edge.Top)
  6168. }, 380)
  6169. }else{
  6170. if (this.isGridMusic) {
  6171. this.scroller.scrollEdge(Edge.Top)
  6172. }else{
  6173. this.listScroller.scrollEdge(Edge.Top)
  6174. }
  6175. }
  6176. this.rightTopImage = $r('sys.symbol.chevron_left')
  6177. break;
  6178. case CommonConstants.TYPE_IS_ARTIST:
  6179. // 进入艺术家前安全保存当前滚动偏移量,支持列表和网格
  6180. let offsetA = 0
  6181. if(this.twoFingerType==4){
  6182. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6183. let cur = this.waterScroller.currentOffset()
  6184. if (cur && typeof cur.yOffset === 'number') {
  6185. offsetA = cur.yOffset
  6186. }
  6187. }
  6188. this.mScrollMap.set('lastWaterArtistScrollOffset', offsetA)
  6189. }else
  6190. if (this.isGridMusic) {
  6191. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6192. let cur = this.scroller.currentOffset()
  6193. if (cur && typeof cur.yOffset === 'number') {
  6194. offsetA = cur.yOffset
  6195. }
  6196. }
  6197. this.mScrollMap.set('lastGridArtistScrollOffset', offsetA)
  6198. } else {
  6199. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6200. let cur = this.listScroller.currentOffset()
  6201. if (cur && typeof cur.yOffset === 'number') {
  6202. offsetA = cur.yOffset
  6203. }
  6204. }
  6205. this.mScrollMap.set('lastListArtistScrollOffset', offsetA)
  6206. }
  6207. let mList = this.artistMap.get(item.name)
  6208. if (mList !== undefined && ArrayUtil.isNotEmpty(mList)) {
  6209. Utility.doSortListAscending(mList)
  6210. this.isCanBack = true
  6211. this.titleName = item.name
  6212. this.currentTitleName = '艺术家:' + item.name
  6213. if (item.pixelMapPath) {
  6214. this.currentTitleCover = item.pixelMapPath
  6215. }
  6216. this.updateListData(mList)
  6217. }
  6218. this.rightTopImage = $r('sys.symbol.chevron_left')
  6219. //进入歌单的时候的滚动位置在顶部
  6220. if(this.twoFingerType==4){
  6221. setTimeout(() => {
  6222. this.waterScroller.scrollEdge(Edge.Top)
  6223. this.scroller.scrollEdge(Edge.Top)
  6224. }, 380)
  6225. }else{
  6226. if (this.isGridMusic) {
  6227. this.scroller.scrollEdge(Edge.Top)
  6228. }else{
  6229. this.listScroller.scrollEdge(Edge.Top)
  6230. }
  6231. }
  6232. break;
  6233. case CommonConstants.TYPE_IS_ALBUM:
  6234. // 进入专辑前安全保存当前滚动偏移量,支持列表和网格
  6235. let offset = 0
  6236. if(this.twoFingerType==4){
  6237. if (this.waterScroller && typeof this.waterScroller.currentOffset === 'function') {
  6238. let cur = this.waterScroller.currentOffset()
  6239. if (cur && typeof cur.yOffset === 'number') {
  6240. offset = cur.yOffset
  6241. }
  6242. }
  6243. this.mScrollMap.set('lastWaterAlBumScrollOffset', offset)
  6244. }else
  6245. if (this.isGridMusic) {
  6246. if (this.scroller && typeof this.scroller.currentOffset === 'function') {
  6247. let cur = this.scroller.currentOffset()
  6248. if (cur && typeof cur.yOffset === 'number') {
  6249. offset = cur.yOffset
  6250. }
  6251. }
  6252. this.mScrollMap.set('lastGridAlBumScrollOffset', offset)
  6253. } else {
  6254. if (this.listScroller && typeof this.listScroller.currentOffset === 'function') {
  6255. let cur = this.listScroller.currentOffset()
  6256. if (cur && typeof cur.yOffset === 'number') {
  6257. offset = cur.yOffset
  6258. }
  6259. }
  6260. this.mScrollMap.set('lastListAlBumScrollOffset', offset)
  6261. }
  6262. let albumList = this.albumMap.get(item.name)
  6263. if (albumList !== undefined && ArrayUtil.isNotEmpty(albumList)) {
  6264. Utility.doSortListAscending(albumList)
  6265. this.isCanBack = true
  6266. this.titleName = item.name
  6267. this.currentTitleName = '专辑:' + item.name
  6268. if (item.pixelMapPath) {
  6269. this.currentTitleCover = item.pixelMapPath
  6270. }
  6271. this.updateListData(albumList)
  6272. this.mScrollMap.set(item.name, this.selectedIndex)
  6273. this.rightTopImage = $r('sys.symbol.chevron_left')
  6274. }
  6275. //进入歌单的时候的滚动位置在顶部
  6276. if(this.twoFingerType==4){
  6277. setTimeout(() => {
  6278. this.waterScroller.scrollEdge(Edge.Top)
  6279. this.scroller.scrollEdge(Edge.Top)
  6280. }, 380)
  6281. }else{
  6282. if (this.isGridMusic) {
  6283. this.scroller.scrollEdge(Edge.Top)
  6284. }else{
  6285. this.listScroller.scrollEdge(Edge.Top)
  6286. }
  6287. }
  6288. break;
  6289. case CommonConstants.TYPE_IS_CSJAD:
  6290. return
  6291. break;
  6292. case CommonConstants.TYPE_LOCAL:
  6293. if(item&&item.filePath.toLowerCase().endsWith('.cue')){
  6294. const cueinfo:CueInfo = await parseCueFile(item.filePath)
  6295. const cueTracks:CueTrack[] = cueinfo.tracks
  6296. console.log('onecold cue cueTracks =', JSON.stringify(cueTracks));
  6297. if(ArrayUtil.isNotEmpty(cueTracks)){
  6298. this.showCueDialog(cueTracks,cueinfo)
  6299. }
  6300. // this.showCueSheet = !this.showCueSheet
  6301. return
  6302. }
  6303. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6304. this.stop();
  6305. }
  6306. if (isOpen) {
  6307. this.currentSong = item
  6308. if (index !== undefined) {
  6309. this.curIndex = index
  6310. }
  6311. this.songList = []
  6312. this.songList.push(item)
  6313. this.sonDataSource.pushArrayData(this.songList)
  6314. }else if(isFromSonPlayList){ //点击来自右下角的播放列表
  6315. this.currentSong = item
  6316. if (index !== undefined) {
  6317. this.curIndex = index
  6318. }
  6319. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  6320. Logger.info(`heanup isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  6321. }else {
  6322. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  6323. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, item.filePath)
  6324. this.songList = globalVideoList
  6325. this.sonDataSource.pushArrayData(this.songList)
  6326. this.currentSong = globalVideoList[this.curIndex]
  6327. }
  6328. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  6329. this.videoUrl = this.currentSong.filePath
  6330. this.name = this.currentSong.name
  6331. this.cover = this.currentSong.pixelMapPath
  6332. this.artist = this.currentSong.artist
  6333. LogUtil.info('onecold this.currentSong.cover =' + this.currentSong.pixelMapPath)
  6334. LogUtil.info('this.currentSongmimeType =' + this.currentSong.mimeType)
  6335. this.startPlayOrResumePlay()
  6336. break;
  6337. case CommonConstants.TYPE_WEBDAV:
  6338. case CommonConstants.TYPE_SMB:
  6339. case CommonConstants.TYPE_NAVIDROME:
  6340. case CommonConstants.TYPE_FTP:
  6341. // 处理网络音频播放(WebDAV/SMB)
  6342. Logger.info(`heanup 处理云端音频播放: ${item.name}, URL: ${item.filePath}`)
  6343. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6344. this.stop();
  6345. }
  6346. if (isOpen) {
  6347. this.currentSong = item
  6348. if (index !== undefined) {
  6349. this.curIndex = index
  6350. }
  6351. this.songList = []
  6352. this.songList.push(item)
  6353. this.sonDataSource.pushArrayData(this.songList)
  6354. } else if (isFromSonPlayList) {
  6355. // 点击来自右下角的播放列表
  6356. this.currentSong = item
  6357. if (index !== undefined) {
  6358. this.curIndex = index
  6359. }
  6360. // 确保播放列表是完整的歌单歌曲列表(已在finishLoadingPlaylist中设置)
  6361. Logger.info(`heanup 网络音频 isFromSonPlayList分支 - 当前播放列表长度: ${this.songList.length}, 当前索引: ${this.curIndex}`)
  6362. } else {
  6363. // 从全局网络音频列表中查找
  6364. let globalVideoList = this.videoLocalList.filter(video => isRemoteCloudType(video.type)) as VideoItem[];
  6365. this.curIndex = globalVideoList.findIndex(video => video.filePath === item.filePath);
  6366. if (this.curIndex === -1 && index !== undefined) {
  6367. this.curIndex = index;
  6368. }
  6369. this.songList = globalVideoList.length > 0 ? globalVideoList : [item];
  6370. this.currentSong = this.songList[this.curIndex];
  6371. this.sonDataSource.pushArrayData(this.songList)
  6372. }
  6373. await this.hydrateRemoteSongFromDb(this.currentSong);
  6374. await this.hydrateRemoteSongFromDb(this.currentSong);
  6375. AppStorage.setOrCreate('currentSong', this.currentSong);
  6376. // 使用辅助方法设置videoUrl,等待WebDAV URL构建完成
  6377. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  6378. context: this.context,
  6379. autoParseMusicName: this.autoParseMusicName
  6380. });
  6381. Logger.info(TAG, `WebDAV URL同步构建完成(分支2): ${this.videoUrl}`);
  6382. this.name = this.currentSong.name
  6383. this.cover = this.currentSong.pixelMapPath
  6384. this.artist = this.currentSong.artist
  6385. Logger.info(`heanup 准备播放网络音频 - 歌名: ${this.name}, 艺术家: ${this.artist}, 完整URL: ${this.videoUrl}`)
  6386. this.startPlayOrResumePlay()
  6387. break;
  6388. }
  6389. }
  6390. private cueComponentId: number = 0
  6391. //显示cue分轨列表对话框
  6392. showCueDialog(cueTracks:CueTrack[],cueinfo:CueInfo){
  6393. this.getUIContext().getPromptAction().openCustomDialog({
  6394. builder: () => {
  6395. this.cueComptentBuilder(cueTracks,cueinfo)
  6396. },
  6397. isModal:true,
  6398. showInSubWindow:false,
  6399. maskColor: Color.Transparent,
  6400. dialogTransition: // 设置弹窗内容显示的过渡效果
  6401. TransitionEffect.translate({ x: 0, y: 390, z: 0 })
  6402. .animation({ duration: 600, curve: Curve.Smooth }),
  6403. maskTransition: // 设置蒙层显示的过渡效果
  6404. TransitionEffect.opacity(0.5)
  6405. .animation({ duration: 600, curve: Curve.Smooth })
  6406. }).then((dialogId: number) => {
  6407. this.cueComponentId = dialogId
  6408. })
  6409. .catch((error: BusinessError) => {
  6410. console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
  6411. })
  6412. }
  6413. @Builder
  6414. cueComptentBuilder(cueTracks:CueTrack[]=[],cueinfo:CueInfo){
  6415. CueComptent({
  6416. title:cueinfo.title,
  6417. cueTracks:cueTracks,
  6418. isLongNameRoLL:this.isLongNameRoLL,
  6419. onCancel:()=>{
  6420. this.getUIContext().getPromptAction().closeCustomDialog(this.cueComponentId)
  6421. },
  6422. onDoItemClick: async (item: CueTrack, index: number)=>{
  6423. //获取cueinfo对应的filePath
  6424. let globalVideoList = Utility.getGlobalList(this.videoLocalList, CommonConstants.TYPE_LOCAL) as VideoItem[];
  6425. this.curIndex = Utility.getCurIndexFromGlobalList(globalVideoList, cueinfo.filePath)
  6426. this.currentSong = Utility.getItemByFilePath(globalVideoList, cueinfo.filePath)
  6427. console.info('onecold cueinfo.filePath=', cueinfo.filePath)
  6428. console.info('onecold this.currentSong =', JSON.stringify(this.currentSong))
  6429. if (this.currentSong){
  6430. if (this.CONTROL_PlayStatus !== PlayStatus.INIT) {
  6431. this.stop();//播放之前先停止之前播放。
  6432. }
  6433. this.songList = globalVideoList
  6434. this.sonDataSource.pushArrayData(this.songList)
  6435. if (this.currentSong) {
  6436. try {
  6437. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  6438. context: this.context,
  6439. autoParseMusicName: this.autoParseMusicName
  6440. });
  6441. } catch (error) {
  6442. Logger.error(TAG, `CUE 点播构建播放地址失败: ${(error as Error).message}`);
  6443. this.videoUrl = this.currentSong.filePath;
  6444. }
  6445. }
  6446. this.name = item.title||this.currentSong.name
  6447. this.cover = this.currentSong.pixelMapPath
  6448. this.artist = item.performer||this.currentSong.artist
  6449. this.currentSong.name = this.name
  6450. this.currentSong.artist = this.artist
  6451. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  6452. this.startPlayOrResumePlay(item.startOffset)//从cue的某个位置开始播放
  6453. }
  6454. }
  6455. })
  6456. }
  6457. @Builder
  6458. PlayController() {
  6459. Row() {
  6460. if(this.isHiCar()){
  6461. this.playConRigth()
  6462. Column(){
  6463. this.centerName()
  6464. }.layoutWeight(1)
  6465. .onClick(()=>{
  6466. this.showPlayerView()
  6467. })
  6468. this.playConLeft(false)
  6469. }else{
  6470. this.playConLeft()
  6471. this.playConRigth()
  6472. }
  6473. }
  6474. .width('100%')
  6475. .height(this.bottomBarHeight)
  6476. .hitTestBehavior(HitTestMode.Transparent)
  6477. .bindContentCover($$this.isShowPlay, this.MusicPlayBuilder(), {
  6478. modalTransition: ModalTransition.NONE,
  6479. onWillDisappear: () => {
  6480. this.setShowPlayFalse()
  6481. },
  6482. // backgroundColor: 'rgba(0, 0, 0, 0.9)',
  6483. })
  6484. .padding({
  6485. left: 16,
  6486. right: 16
  6487. })
  6488. }
  6489. @State isFrontWhite: boolean = false
  6490. @Builder
  6491. centerName() {
  6492. Column() {
  6493. Text(this.currentSong?.name)
  6494. .fontSize(16)
  6495. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  6496. .maxLines(1)
  6497. .fontColor(Color.White)
  6498. .fontWeight(500);
  6499. Row() {
  6500. Text(this.currentSong?.artist)
  6501. .margin({ top: 2 })
  6502. .fontSize(13)
  6503. .textAlign(TextAlign.Start)
  6504. .maxLines(1)
  6505. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  6506. .fontColor(Color.White)
  6507. }
  6508. .visibility(this.currentSong?.artist? Visibility.Visible:Visibility.None)
  6509. }
  6510. .geometryTransition('name', { follow: true }) // 绑定标识符
  6511. .alignItems(HorizontalAlign.Center)
  6512. }
  6513. @Builder
  6514. playConLeft(isLeft: boolean = true) {
  6515. Row() {
  6516. // RotatingCover({ songLabel: this.currentSong?.pixelMapPath })
  6517. Image( StrUtil.isNotEmpty(this.currentSong?.pixelMapPath)?
  6518. this.currentSong?.pixelMapPath:$r('app.media.music_red'))
  6519. .height(45)
  6520. .objectFit(ImageFit.Contain)
  6521. .alt( $r('app.media.music_red'))
  6522. .fillColor(this.themeColor)
  6523. .borderRadius(8)
  6524. .shadow({
  6525. radius: 10,
  6526. type: ShadowType.BLUR,
  6527. color: 'on_primary'
  6528. })
  6529. .geometryTransition('cover', { follow: true }) // 绑定标识符
  6530. Column() {
  6531. Text(this.currentSong?.name)
  6532. .fontSize(16)
  6533. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  6534. .maxLines(1)
  6535. .fontColor(Color.White)
  6536. .fontWeight(500);
  6537. Row() {
  6538. Text(this.currentSong?.artist)
  6539. .margin({ top: 2 })
  6540. .fontSize(13)
  6541. .textAlign(TextAlign.Start)
  6542. .maxLines(1)
  6543. .textOverflow({ overflow: TextOverflow.MARQUEE }) //超长滚动
  6544. .fontColor(Color.White)
  6545. }
  6546. .visibility(this.currentSong?.artist? Visibility.Visible:Visibility.None)
  6547. }
  6548. .padding({left:8})
  6549. .geometryTransition('name', { follow: true }) // 绑定标识符
  6550. .alignItems(isLeft?HorizontalAlign.Start:HorizontalAlign.End)
  6551. .margin({ right: isLeft?22:10 })
  6552. .visibility(isLeft? Visibility.Visible:Visibility.None)
  6553. }
  6554. .padding({ right: 18 })
  6555. .layoutWeight(isLeft?1:0)
  6556. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  6557. .onClick(() => {
  6558. this.showPlayerView()
  6559. })
  6560. }
  6561. setShowPlayTrue(){
  6562. this.getUIContext()?.animateTo({
  6563. duration: 500,
  6564. curve: Curve.Friction
  6565. }, () => {
  6566. this.isShowPlay = true;
  6567. });
  6568. }
  6569. setShowPlayFalse(){
  6570. this.getUIContext()?.animateTo({
  6571. duration: 500,
  6572. curve: Curve.Friction
  6573. }, () => {
  6574. this.isShowPlay = false;
  6575. });
  6576. }
  6577. //打开播放页
  6578. showPlayerView() {
  6579. if (ArrayUtil.isNotEmpty(this.songList)) {
  6580. this.setShowPlayTrue()
  6581. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc';
  6582. this.initLyric(lyricPath);
  6583. this.startAutoHide();
  6584. } else {
  6585. ToastUtil.showToast('当前播放列表为空,请先导入音乐。');
  6586. }
  6587. }
  6588. @Builder
  6589. playConRigth() {
  6590. Row() {
  6591. SymbolGlyph($r('sys.symbol.backward_end_fill'))
  6592. .fontSize(28)
  6593. .fontColor([this.themeColor])
  6594. .alignSelf(ItemAlign.Center)
  6595. .visibility(this.isShowPrecious? Visibility.Visible:Visibility.None)
  6596. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  6597. .margin({ left: 8, right: 14 })
  6598. .displayPriority(2)
  6599. .onClick(() => {
  6600. if (ArrayUtil.isNotEmpty(this.songList)) {
  6601. this.playPrevious()
  6602. } else {
  6603. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  6604. }
  6605. })
  6606. //播放进度条
  6607. Stack() {
  6608. Progress({
  6609. value: Math.floor(this.progressValue),
  6610. type: ProgressType.Ring,
  6611. })
  6612. .color(this.themeColor)// 进度条前景色为灰色
  6613. .height(38)
  6614. .aspectRatio(CommonConstants.ASPECT_RATIO)
  6615. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ? $r('app.media.hm_pause') : $r('app.media.hm_play2'))
  6616. .height(36)
  6617. .width(36)
  6618. .displayPriority(3)
  6619. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  6620. .fillColor(this.themeColor)
  6621. .onClick(() => {
  6622. if (ArrayUtil.isNotEmpty(this.songList)) {
  6623. console.info('onecold playOrPause 4642')
  6624. this.playOrPause()
  6625. } else {
  6626. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  6627. }
  6628. })
  6629. }
  6630. SymbolGlyph($r('sys.symbol.forward_end_fill'))
  6631. .fontSize(28)
  6632. .fontColor([this.themeColor])
  6633. .alignSelf(ItemAlign.Center)
  6634. .margin({
  6635. right: 14,
  6636. left: 14
  6637. })
  6638. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  6639. .displayPriority(2)
  6640. .onClick(() => {
  6641. if (ArrayUtil.isNotEmpty(this.songList)) {
  6642. this.playNext()
  6643. } else {
  6644. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  6645. }
  6646. })
  6647. Image($r('app.media.hm_playlist'))
  6648. .height(26)
  6649. .width(26)
  6650. .displayPriority(1)
  6651. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.5 })
  6652. .fillColor(this.themeColor)
  6653. .bindSheet($$this.isShowSheet, this.PlayListSheet(), {
  6654. height: '95%',
  6655. dragBar: true,
  6656. showClose: true,
  6657. blurStyle: BlurStyle.Thin,
  6658. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  6659. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  6660. title: {
  6661. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  6662. + `(${this.songList.length}首)`
  6663. }
  6664. })
  6665. .onClick(() => {
  6666. if (ArrayUtil.isNotEmpty(this.songList)) {
  6667. this.isShowSheet = !this.isShowSheet;
  6668. this.isFrontWhite = false
  6669. LogUtil.info('onecold scrollToIndex = ' + this.curIndex)
  6670. this.scrollIndex()
  6671. } else {
  6672. ToastUtil.showToast('当前播放列表为空,请先导入音乐。')
  6673. }
  6674. })
  6675. }
  6676. }
  6677. scrollIndex(){
  6678. try {
  6679. setTimeout(() => {
  6680. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  6681. if(this.curIndex>60){
  6682. this.playListScroller.scrollToIndex(this.curIndex,false, ScrollAlign.CENTER)
  6683. }else{
  6684. this.playListScroller.scrollToIndex(this.curIndex,true, ScrollAlign.CENTER)
  6685. }
  6686. })
  6687. }, 123)
  6688. }catch (error) {
  6689. console.error(`onecold scrollIndex出错: ${error}`);
  6690. }
  6691. }
  6692. //播放列表布局
  6693. @Builder
  6694. PlayListSheet() {
  6695. Column() {
  6696. this.PlayList()
  6697. }
  6698. .width('100%')
  6699. .height('100%')
  6700. }
  6701. @State titleStr: string = ''
  6702. @State ablumStr: string = ''
  6703. @State artistStr: string = ''
  6704. @State lyricConStr: string = ''
  6705. @State currentEditItem: string = ''
  6706. @State yearStr: string = ''
  6707. @State trackStr: string = ''
  6708. @State genreStr: string = ''
  6709. @State imagePathStr: string = ''
  6710. @State albumArtistStr: string = ''
  6711. @State composerStr: string = ''
  6712. @State lyricistStr: string = ''
  6713. @State commentStr: string = ''
  6714. @State discStr: string = ''
  6715. doUpdateData() {
  6716. setTimeout(() => {
  6717. if (this.modeType === 0) {
  6718. this.deleteCache(this.currentPath)
  6719. this.getSortedFiles(this.currentPath)
  6720. }else if (this.modeType === 1){
  6721. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6722. }
  6723. }, 500)
  6724. }
  6725. doAllUpdateData() {
  6726. setTimeout(() => {
  6727. if (this.modeType === 0) {
  6728. this.deleteCache(this.currentPath)
  6729. this.getSortedFiles(this.currentPath)
  6730. }
  6731. workerInstance.postMessage({ code: 2, data: this.context,data2:this.packName });
  6732. workerInstance.postMessage({ code: 3, data: this.context });
  6733. workerInstance.postMessage({ code: 4, data: this.context });
  6734. }, 999)
  6735. }
  6736. //编辑信息
  6737. async doEdit(item: VideoItem) {
  6738. if (!item) {
  6739. return
  6740. }
  6741. if (StrUtil.isEmpty(this.titleStr)) {
  6742. ToastUtil.showToast('标题不能为空')
  6743. return
  6744. }
  6745. //内嵌音乐标签不能开启监听
  6746. // this.deletionWatcher?.stop();
  6747. DialogHelper.showLoadingDialog()
  6748. await PermissionUtil.activatePermission(item.filePath)
  6749. let tempOutPath = ''
  6750. // 如果不是 packName 包下的文件,则直接路径用this.currentPath
  6751. if(!item.filePath.toLowerCase().includes(this.packName)){
  6752. tempOutPath = this.currentPath + '/' + item.fileName
  6753. }
  6754. console.info('onecold tempOutPath ='+tempOutPath)
  6755. //用户更改了封面,那就内嵌下封面
  6756. if(StrUtil.isNotEmpty(this.imagePathStr)){
  6757. const resultCover:boolean = await changeMusicCover(this.context,
  6758. item.filePath,this.imagePathStr,true,tempOutPath);
  6759. this.imagePathStr = ''
  6760. if(resultCover){
  6761. ToastUtil.showToast('内嵌封面成功')
  6762. }
  6763. }
  6764. const metadata:FFMpegTags = {
  6765. title: this.titleStr,
  6766. artist: this.artistStr,
  6767. album: this.ablumStr,
  6768. TYER:this.yearStr,
  6769. genre:this.genreStr,
  6770. track:this.trackStr,
  6771. album_artist:this.albumArtistStr,
  6772. TPE2:this.albumArtistStr,//ID3v2 中通常没有专门的 "专辑艺术家" 字段,但有些软件会使用 TPE2 来表示专辑艺
  6773. COMPOSER:this.composerStr,
  6774. lyricist:this.lyricistStr,
  6775. TEXT:this.lyricistStr,//ID3v2 使用 TEXT 字段来表示作词者
  6776. comment:this.commentStr,
  6777. disc:this.discStr,
  6778. };
  6779. let newInput = item.filePath
  6780. //内嵌标签歌路径如果不是包含包名,输入newInput要赋值tempOutPath,然后tempOutPath为空
  6781. if(!item.filePath.toLowerCase().includes(this.packName)&&FileUtil.accessSync(tempOutPath)){
  6782. newInput = tempOutPath
  6783. tempOutPath = ''
  6784. }
  6785. //内嵌下标签的值,设置overwrite为true会直接修改原文件
  6786. const result:boolean = await repairAudioMetadata(
  6787. newInput,
  6788. this.lyricConStr,
  6789. metadata,
  6790. true,
  6791. tempOutPath
  6792. );
  6793. if (result) {
  6794. if(!item.filePath.includes(this.packName)){
  6795. //内嵌成功的歌路径如果不是包含包名,则要入库
  6796. let newItem: VideoItem = await Utility.uriGetMusicAssetsFromFile(this.context, newInput,
  6797. CommonConstants.TYPE_LOCAL, this.autoParseMusicName);
  6798. this.table.insert(newItem, (id: number) => {
  6799. //加入数据库
  6800. if(this.modeType==0){
  6801. this.deleteCache(this.currentPath)
  6802. this.getSortedFiles(this.currentPath)
  6803. }
  6804. });
  6805. }
  6806. const task = new taskpool.Task(
  6807. updateInfoDb,
  6808. this.context,
  6809. item.filePath,
  6810. this.titleStr,
  6811. this.artistStr,
  6812. this.ablumStr,
  6813. this.lyricConStr,
  6814. this.yearStr,this.genreStr,
  6815. this.trackStr,this.albumArtistStr,
  6816. this.composerStr, this.lyricistStr,
  6817. this.commentStr,this.discStr
  6818. );
  6819. taskpool.execute(task, taskpool.Priority.HIGH).then((result) => {
  6820. if (result) {
  6821. console.log(" onecold 编辑信息成功,数据库已同步");
  6822. ToastUtil.showToast('内嵌音乐标签成功')
  6823. this.isShowMoreView = false
  6824. this.name = this.titleStr
  6825. this.syncEditedFields(item)
  6826. if (item.filePath == this.currentSong?.filePath) {
  6827. this.currentSong.name = this.titleStr
  6828. this.artist = this.artistStr
  6829. this.currentSong.artist = this.artistStr
  6830. this.currentSong.album = this.ablumStr
  6831. this.currentSong.year = this.yearStr
  6832. this.currentSong.genre = this.genreStr
  6833. this.currentSong.track = this.trackStr
  6834. this.currentSong.lyricContent = this.lyricConStr
  6835. this.currentSong.ALBUMARTIST = this.albumArtistStr
  6836. this.currentSong.COMPOSER = this.composerStr
  6837. this.currentSong.LYRICIST = this.lyricistStr
  6838. this.currentSong.COMMENT = this.commentStr
  6839. }
  6840. this.syncListsAfterEdit(item.filePath)
  6841. this.doUpateEditedFields(item)
  6842. //this.doUpdateData()
  6843. } else {
  6844. // ToastUtil.showToast('保存失败' + error?.toString())
  6845. console.error(" onecold 编辑信息数据库失败 ");
  6846. }
  6847. // 关闭进度条
  6848. DialogHelper.closeLoading();
  6849. }).catch((error: Error) => {
  6850. // 关闭进度条
  6851. DialogHelper.closeLoading();
  6852. console.error('onecold Subtitle sync failed:', error);
  6853. });
  6854. console.log(' onecold 元数据标签更新成功,');
  6855. } else {
  6856. // 关闭进度条
  6857. DialogHelper.closeLoading();
  6858. ToastUtil.showToast('内嵌音乐标签失败')
  6859. console.log('onecold 内嵌音乐标签失败');
  6860. }
  6861. this.longItemFilePath = ''
  6862. this.tempLyricContent = ''
  6863. this.isShowEdit = false
  6864. }
  6865. // 内嵌标签更新当前内嵌的Item
  6866. async doUpateEditedFields(item: VideoItem) {
  6867. // 找到当前项在 videoLocalList 中的索引
  6868. const index = this.videoLocalList.findIndex(video => video.filePath === item.filePath);
  6869. if (index !== -1) {
  6870. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  6871. const updatedItem = await this.table.queryVideoByFilePath(item.filePath)
  6872. // 只有当查询结果不为 null 时才更新列表
  6873. if (updatedItem !== null) {
  6874. // 更新 videoLocalList 中的项(通过创建新数组触发响应式更新)
  6875. this.videoLocalList = [
  6876. ...this.videoLocalList.slice(0, index),
  6877. updatedItem,
  6878. ...this.videoLocalList.slice(index + 1)
  6879. ];
  6880. // 同步更新 LazyDataSource
  6881. this.dataSource.pushArrayData(this.videoLocalList)
  6882. } else {
  6883. ToastUtil.showToast('未找到更新的数据');
  6884. }
  6885. }
  6886. DialogHelper.closeLoading();
  6887. }
  6888. @Builder
  6889. editSheet(item: VideoItem) {
  6890. Scroll() {
  6891. Column() {
  6892. this.editDetail(item)
  6893. }
  6894. }
  6895. .width('100%')
  6896. .height('100%')
  6897. }
  6898. @Builder
  6899. editDetail(item: VideoItem) {
  6900. Column() {
  6901. if (item) {
  6902. Row() {
  6903. Stack() {
  6904. Image(StrUtil.isNotEmpty(this.imagePathStr)?this.imagePathStr.startsWith('http')?
  6905. this.imagePathStr:fileUri.getUriFromPath(this.imagePathStr):
  6906. StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.add_image2') :
  6907. item.pixelMapPath)
  6908. .fillColor(this.themeColor)
  6909. .height(88)
  6910. .width(88)
  6911. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  6912. .borderRadius(12)
  6913. .clip(true)
  6914. .opacity(this.opacityItem)// 绑定透明度
  6915. .margin({ left: 25 })
  6916. }
  6917. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.6})
  6918. .onClick(async () => {
  6919. const imagePath:string | undefined = await this.goSelectImage(item);
  6920. if (imagePath) {
  6921. //用户更改过图片
  6922. this.imagePathStr = imagePath
  6923. }
  6924. })
  6925. .width('28%')
  6926. Row() {
  6927. Column() {
  6928. Text(item.name)
  6929. .fontSize(17)
  6930. .maxLines(1)
  6931. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6932. .animation({
  6933. duration: 555,
  6934. curve: 'Linear',
  6935. })
  6936. .fontColor(this.themeColor)
  6937. .margin({ left: 8 })
  6938. Row() {
  6939. Text(item.artist)
  6940. .fontSize(14)
  6941. .maxLines(1)
  6942. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  6943. .padding({ top: 8 })
  6944. .fontColor(this.themeColor)
  6945. .margin({ left: 8 })
  6946. }
  6947. }
  6948. .height('100%')
  6949. .width(100)
  6950. .layoutWeight(1)
  6951. .justifyContent(FlexAlign.Center)
  6952. .alignItems(HorizontalAlign.Start)
  6953. Column() {
  6954. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6955. Row(){
  6956. SymbolGlyph($r('sys.symbol.picture'))
  6957. .fontSize(18)
  6958. .fontColor([Color.White])
  6959. Text('获取封面')
  6960. .margin({ left: 4 })
  6961. .fontSize(11)
  6962. .fontColor(Color.White)
  6963. .fontWeight(480)
  6964. .textAlign(TextAlign.Center)
  6965. }
  6966. .justifyContent(FlexAlign.Center)
  6967. }
  6968. .height(38)
  6969. .width(100)
  6970. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  6971. .backgroundColor(this.themeColor)
  6972. .stateEffect(true)
  6973. .margin({ right: 35 })
  6974. .onClick(async () => {
  6975. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  6976. this.showTipsDialog();
  6977. return; // Return empty string when no API is configured
  6978. }
  6979. const imagePath:string | undefined = await this.doSearchCover(item,
  6980. this.titleStr,this.artistStr);
  6981. console.info('onecold imagePath = '+imagePath)
  6982. if (StrUtil.isNotEmpty(imagePath)) {
  6983. //用户更改过图片
  6984. this.imagePathStr = imagePath
  6985. ToastUtil.showToast('获取封面成功')
  6986. }else{
  6987. ToastUtil.showToast('获取封面失败,请重试')
  6988. }
  6989. })
  6990. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  6991. Row(){
  6992. SymbolGlyph($r('sys.symbol.input_mode'))
  6993. .fontSize(18)
  6994. .fontColor([Color.White])
  6995. Text('获取歌词')
  6996. .margin({ left: 4 })
  6997. .fontSize(11)
  6998. .fontColor(Color.White)
  6999. .fontWeight(480)
  7000. .textAlign(TextAlign.Center)
  7001. }
  7002. .justifyContent(FlexAlign.Center)
  7003. }
  7004. .height(38)
  7005. .width(100)
  7006. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7007. .backgroundColor(this.themeColor)
  7008. .stateEffect(true)
  7009. .margin({ top: 9, right: 35 })
  7010. .onClick(async () => {
  7011. //判断有没有设置api
  7012. let apiUrl = PreferencesUtil.getStringSync('LRC_API', '')
  7013. if (StrUtil.isEmpty(apiUrl)) {
  7014. this.isLyricSetting = false
  7015. this.showTipsDialog()
  7016. return
  7017. }
  7018. let res: string | undefined = await getApiLyric(apiUrl,
  7019. this.titleStr, this.artistStr, false);
  7020. if (res && StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  7021. this.lyricConStr = res;
  7022. ToastUtil.showToast('获取歌词成功')
  7023. }else{
  7024. ToastUtil.showToast('获取歌词失败,请重试')
  7025. }
  7026. })
  7027. }
  7028. .justifyContent(FlexAlign.Start)
  7029. }
  7030. .height('100%')
  7031. .justifyContent(FlexAlign.Start)
  7032. .layoutWeight(1)
  7033. }
  7034. .width('100%')
  7035. .height(98)
  7036. Row() {
  7037. Text('标题:')
  7038. .fontSize(14)
  7039. .fontColor($r('app.color.text_color'))
  7040. .margin({ left: 22 })
  7041. TextInput({ text: item.name })
  7042. .height(40)
  7043. .maxLines(1)
  7044. .fontSize(14)
  7045. .layoutWeight(1)
  7046. .fontColor($r('app.color.text_color'))
  7047. .margin({ right: 20, left: 10 })
  7048. .onChange((val: string) => {
  7049. this.titleStr = val
  7050. })
  7051. }
  7052. .width('100%')
  7053. .margin({ top: 10, bottom: 10 })
  7054. .justifyContent(FlexAlign.Start)
  7055. Row() {
  7056. Text('艺术家:')
  7057. .fontSize(14)
  7058. .fontColor($r('app.color.text_color'))
  7059. .margin({ left: 22 })
  7060. TextInput({ text: item.artist })
  7061. .height(40)
  7062. .maxLines(1)
  7063. .fontSize(14)
  7064. .layoutWeight(1)
  7065. .fontColor($r('app.color.text_color'))
  7066. .margin({ right: 20, left: 10 })
  7067. .onChange((val: string) => {
  7068. this.artistStr = val
  7069. })
  7070. }
  7071. .width('100%')
  7072. .margin({ top: 10, bottom: 10 })
  7073. .justifyContent(FlexAlign.Start)
  7074. Row() {
  7075. Text('专辑名:')
  7076. .fontSize(14)
  7077. .fontColor($r('app.color.text_color'))
  7078. .margin({ left: 22 })
  7079. TextInput({ text: item.album })
  7080. .height(40)
  7081. .maxLines(1)
  7082. .fontSize(14)
  7083. .layoutWeight(1)
  7084. .fontColor($r('app.color.text_color'))
  7085. .margin({ right: 20, left: 10 })
  7086. .onChange((val: string) => {
  7087. this.ablumStr = val
  7088. })
  7089. }
  7090. .width('100%')
  7091. .margin({ top: 10, bottom: 10 })
  7092. .justifyContent(FlexAlign.Start)
  7093. Row() {
  7094. Column(){
  7095. Column(){
  7096. Text('歌词:')
  7097. .fontSize(14)
  7098. .fontColor($r('app.color.text_color'))
  7099. .margin({ top:9,left: 22 })
  7100. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7101. SymbolGlyph($r('sys.symbol.trash_fill'))
  7102. .fontSize(25)
  7103. .alignSelf(ItemAlign.Center)
  7104. .margin({ left: 22,top:25})
  7105. }
  7106. .backgroundColor(Color.Transparent)
  7107. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  7108. Visibility.None:Visibility.Visible)
  7109. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7110. .onClick(()=>{
  7111. this.lyricConStr = ''
  7112. this.lyricContent = ''
  7113. this.tempLyricContent = ''
  7114. })
  7115. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7116. SymbolGlyph($r('sys.symbol.plus'))
  7117. .fontSize(25)
  7118. .alignSelf(ItemAlign.Center)
  7119. .margin({ left: 22,top:25})
  7120. }
  7121. .backgroundColor(Color.Transparent)
  7122. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7123. .onClick( ()=>{
  7124. this.callFilePickerSelectFileForLyric()
  7125. })
  7126. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7127. SymbolGlyph($r('sys.symbol.traditional_square'))
  7128. .fontSize(25)
  7129. .alignSelf(ItemAlign.Center)
  7130. .margin({ left: 22,top:25})
  7131. }
  7132. .backgroundColor(Color.Transparent)
  7133. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  7134. Visibility.None:Visibility.Visible)
  7135. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7136. .onClick( ()=>{
  7137. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  7138. this.lyricConStr = getTransverterText(lyricC,1)//1是简体转繁体 ,2是繁体转简体
  7139. })
  7140. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  7141. Image($r('app.media.jianti'))
  7142. .height(25)
  7143. .fillColor($r('app.color.text_color'))
  7144. .alignSelf(ItemAlign.Center)
  7145. .margin({ left: 22,top:25})
  7146. }
  7147. .backgroundColor(Color.Transparent)
  7148. .visibility(StrUtil.isEmpty(this.tempLyricContent)&&StrUtil.isEmpty(this.lyricConStr)?
  7149. Visibility.None:Visibility.Visible)
  7150. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7151. .onClick( ()=>{
  7152. let lyricC = StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr: this.tempLyricContent
  7153. this.lyricConStr = getTransverterText(lyricC,2)//1是简体转繁体 ,2是繁体转简体
  7154. })
  7155. }
  7156. .layoutWeight(1)
  7157. }
  7158. TextArea({ text: StrUtil.isNotEmpty(this.lyricConStr)?this.lyricConStr:
  7159. this.tempLyricContent })
  7160. .type(TextAreaType.NORMAL)
  7161. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?100:'auto')
  7162. .fontSize(14)
  7163. .layoutWeight(1)
  7164. .fontColor($r('app.color.text_color'))
  7165. .margin({ right: 20, left: 10 })
  7166. .onChange((val: string) => {
  7167. this.lyricConStr = val
  7168. })
  7169. }
  7170. .width('100%')
  7171. .height(StrUtil.isEmpty(this.lyricConStr)&&StrUtil.isEmpty(this.tempLyricContent)?120:'auto')
  7172. .margin({ top: 10, bottom: 10 })
  7173. .justifyContent(FlexAlign.Start)
  7174. Row() {
  7175. Text('年份:')
  7176. .fontSize(14)
  7177. .fontColor($r('app.color.text_color'))
  7178. .margin({ left: 22 })
  7179. TextInput({ text: item.year })
  7180. .height(40)
  7181. .maxLines(1)
  7182. .fontSize(14)
  7183. .type(InputType.Number)
  7184. .layoutWeight(1)
  7185. .fontColor($r('app.color.text_color'))
  7186. .margin({ right: 20, left: 10 })
  7187. .onChange((val: string) => {
  7188. this.yearStr = val
  7189. })
  7190. }
  7191. .width('100%')
  7192. .margin({ top: 10, bottom: 10 })
  7193. .justifyContent(FlexAlign.Start)
  7194. Row() {
  7195. Text('音轨号:')
  7196. .fontSize(14)
  7197. .fontColor($r('app.color.text_color'))
  7198. .margin({ left: 22 })
  7199. TextInput({ text:item.track=='未知'?'': item.track })
  7200. .height(40)
  7201. .maxLines(1)
  7202. .fontSize(14)
  7203. .type(InputType.Number)
  7204. .layoutWeight(1)
  7205. .fontColor($r('app.color.text_color'))
  7206. .margin({ right: 20, left: 10 })
  7207. .onChange((val: string) => {
  7208. this.trackStr = val
  7209. })
  7210. }
  7211. .width('100%')
  7212. .margin({ top: 10, bottom: 10 })
  7213. .justifyContent(FlexAlign.Start)
  7214. Row() {
  7215. Text('碟号:')
  7216. .fontSize(14)
  7217. .fontColor($r('app.color.text_color'))
  7218. .margin({ left: 22 })
  7219. TextInput({ text:item.disc })
  7220. .height(40)
  7221. .maxLines(1)
  7222. .fontSize(14)
  7223. .type(InputType.Number)
  7224. .layoutWeight(1)
  7225. .fontColor($r('app.color.text_color'))
  7226. .margin({ right: 20, left: 10 })
  7227. .onChange((val: string) => {
  7228. this.discStr = val
  7229. })
  7230. }
  7231. .width('100%')
  7232. .margin({ top: 10, bottom: 10 })
  7233. .justifyContent(FlexAlign.Start)
  7234. Row() {
  7235. Text('风格:')
  7236. .fontSize(14)
  7237. .fontColor($r('app.color.text_color'))
  7238. .margin({ left: 22 })
  7239. TextInput({ text: item.genre })
  7240. .height(40)
  7241. .maxLines(1)
  7242. .fontSize(14)
  7243. .layoutWeight(1)
  7244. .fontColor($r('app.color.text_color'))
  7245. .margin({ right: 20, left: 10 })
  7246. .onChange((val: string) => {
  7247. this.genreStr = val
  7248. })
  7249. }
  7250. .width('100%')
  7251. .margin({ top: 10, bottom: 10 })
  7252. .justifyContent(FlexAlign.Start)
  7253. Row() {
  7254. Text('专辑艺术家:')
  7255. .fontSize(14)
  7256. .fontColor($r('app.color.text_color'))
  7257. .margin({ left: 22 })
  7258. TextInput({ text: item.ALBUMARTIST })
  7259. .height(40)
  7260. .maxLines(1)
  7261. .fontSize(14)
  7262. .layoutWeight(1)
  7263. .fontColor($r('app.color.text_color'))
  7264. .margin({ right: 20, left: 10 })
  7265. .onChange((val: string) => {
  7266. this.albumArtistStr = val
  7267. })
  7268. }
  7269. .width('100%')
  7270. .margin({ top: 10, bottom: 10 })
  7271. .justifyContent(FlexAlign.Start)
  7272. Row() {
  7273. Text('作曲:')
  7274. .fontSize(14)
  7275. .fontColor($r('app.color.text_color'))
  7276. .margin({ left: 22 })
  7277. TextInput({ text: item.COMPOSER })
  7278. .height(40)
  7279. .maxLines(1)
  7280. .fontSize(14)
  7281. .layoutWeight(1)
  7282. .fontColor($r('app.color.text_color'))
  7283. .margin({ right: 20, left: 10 })
  7284. .onChange((val: string) => {
  7285. this.composerStr = val
  7286. })
  7287. }
  7288. .width('100%')
  7289. .margin({ top: 10, bottom: 10 })
  7290. .justifyContent(FlexAlign.Start)
  7291. Row() {
  7292. Text('作词:')
  7293. .fontSize(14)
  7294. .fontColor($r('app.color.text_color'))
  7295. .margin({ left: 22 })
  7296. TextInput({ text: item.LYRICIST })
  7297. .height(40)
  7298. .maxLines(1)
  7299. .fontSize(14)
  7300. .layoutWeight(1)
  7301. .fontColor($r('app.color.text_color'))
  7302. .margin({ right: 20, left: 10 })
  7303. .onChange((val: string) => {
  7304. this.lyricistStr = val
  7305. })
  7306. }
  7307. .width('100%')
  7308. .margin({ top: 10, bottom: 10 })
  7309. .justifyContent(FlexAlign.Start)
  7310. Row() {
  7311. Text('注释:')
  7312. .fontSize(14)
  7313. .fontColor($r('app.color.text_color'))
  7314. .margin({ left: 22 })
  7315. TextInput({ text: item.COMMENT })
  7316. .height(40)
  7317. .maxLines(1)
  7318. .fontSize(14)
  7319. .layoutWeight(1)
  7320. .fontColor($r('app.color.text_color'))
  7321. .margin({ right: 20, left: 10 })
  7322. .onChange((val: string) => {
  7323. this.commentStr = val
  7324. })
  7325. }
  7326. .width('100%')
  7327. .margin({ top: 10, bottom: 10 })
  7328. .justifyContent(FlexAlign.Start)
  7329. Row() {
  7330. Button('保存')
  7331. .fontColor(Color.White)
  7332. .layoutWeight(1)
  7333. .height(50)
  7334. .width(100)
  7335. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7336. .backgroundColor(this.themeColor)
  7337. .stateEffect(true)
  7338. .margin({ right: 20, bottom: 20 })
  7339. .onClick(async () => {
  7340. this.doEdit(item)
  7341. })
  7342. Button('取消')
  7343. .fontColor(Color.White)
  7344. .layoutWeight(1)
  7345. .height(50)
  7346. .width(100)
  7347. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  7348. .backgroundColor(this.themeColor)
  7349. .stateEffect(true)
  7350. .margin({ left: 20, bottom: 20 })
  7351. .onClick(async () => {
  7352. if(this.isGridMusic){
  7353. this.longItemFilePath =''
  7354. }else{
  7355. this.isShowEdit = false
  7356. }
  7357. this.setEditStrEmpty()
  7358. if(this.isShowPlay){
  7359. this.isShowEdit = false
  7360. }
  7361. })
  7362. }
  7363. .margin({
  7364. left: 38,
  7365. right: 38,
  7366. top: 10,
  7367. bottom: 10
  7368. })
  7369. .width(250)
  7370. .height(60)
  7371. }
  7372. }
  7373. .margin({ bottom: 20 })
  7374. }
  7375. setEditStrEmpty(){
  7376. this.imagePathStr = ''
  7377. this.lyricConStr = ''
  7378. this.artistStr = ''
  7379. this.titleStr = ''
  7380. this.ablumStr = ''
  7381. this.genreStr = ''
  7382. this.yearStr = ''
  7383. this.trackStr = ''
  7384. this.albumArtistStr = ''
  7385. this.composerStr = ''
  7386. this.lyricistStr = ''
  7387. this.commentStr = ''
  7388. this.discStr = ''
  7389. }
  7390. initEditFields(item?: VideoItem) {
  7391. if (!item) {
  7392. this.setEditStrEmpty()
  7393. return
  7394. }
  7395. this.imagePathStr = ''
  7396. this.titleStr = item.name ?? ''
  7397. this.artistStr = item.artist ?? ''
  7398. this.ablumStr = item.album ?? ''
  7399. this.genreStr = item.genre ?? ''
  7400. this.yearStr = item.year ?? ''
  7401. this.trackStr = item.track ?? ''
  7402. this.albumArtistStr = item.ALBUMARTIST ?? ''
  7403. this.composerStr = item.COMPOSER ?? ''
  7404. this.lyricistStr = item.LYRICIST ?? ''
  7405. this.commentStr = item.COMMENT ?? ''
  7406. this.discStr = item.disc ?? ''
  7407. this.lyricConStr = item.lyricContent ?? ''
  7408. }
  7409. private syncEditedFields(target?: VideoItem) {
  7410. if (!target) {
  7411. return
  7412. }
  7413. target.name = this.titleStr
  7414. target.artist = this.artistStr
  7415. target.album = this.ablumStr
  7416. target.lyricContent = this.lyricConStr
  7417. target.year = this.yearStr
  7418. target.genre = this.genreStr
  7419. target.track = this.trackStr
  7420. target.ALBUMARTIST = this.albumArtistStr
  7421. target.COMPOSER = this.composerStr
  7422. target.LYRICIST = this.lyricistStr
  7423. target.COMMENT = this.commentStr
  7424. target.disc = this.discStr
  7425. }
  7426. private replaceItemInList(list: Array<VideoItem> | undefined, filePath: string,
  7427. apply?: (next: Array<VideoItem>) => void) {
  7428. if (!list || ArrayUtil.isEmpty(list)) {
  7429. return
  7430. }
  7431. const index = list.findIndex((video: VideoItem) => video.filePath === filePath)
  7432. if (index < 0) {
  7433. return
  7434. }
  7435. const nextList = [...list]
  7436. this.syncEditedFields(nextList[index])
  7437. apply?.(nextList)
  7438. }
  7439. private syncListsAfterEdit(filePath: string) {
  7440. this.replaceItemInList(this.videoLocalList, filePath, (next: Array<VideoItem>) => {
  7441. this.videoLocalList = next
  7442. this.dataSource.pushArrayData(next)
  7443. })
  7444. this.replaceItemInList(this.songList, filePath, (next: Array<VideoItem>) => {
  7445. this.songList = next
  7446. this.sonDataSource.pushArrayData(next)
  7447. })
  7448. this.replaceItemInList(this.favList, filePath, (next: Array<VideoItem>) => {
  7449. this.favList = next
  7450. })
  7451. this.replaceItemInList(this.historyList, filePath, (next: Array<VideoItem>) => {
  7452. this.historyList = next
  7453. })
  7454. this.replaceItemInList(this.currentSongList, filePath, (next: Array<VideoItem>) => {
  7455. this.currentSongList = next
  7456. })
  7457. this.replaceItemInList(this.mediaKuList, filePath, (next: Array<VideoItem>) => {
  7458. this.mediaKuList = next
  7459. })
  7460. this.replaceItemInList(this.filteredList, filePath, (next: Array<VideoItem>) => {
  7461. this.filteredList = next
  7462. })
  7463. this.replaceItemInList(this.artistList, filePath, (next: Array<VideoItem>) => {
  7464. this.artistList = next
  7465. })
  7466. this.replaceItemInList(this.albumList, filePath, (next: Array<VideoItem>) => {
  7467. this.albumList = next
  7468. })
  7469. this.listRefreshKey++
  7470. }
  7471. private refreshLazyListViews(mainListUpdated: boolean, playlistUpdated: boolean): void {
  7472. if (!mainListUpdated && !playlistUpdated) {
  7473. return;
  7474. }
  7475. this.listRefreshKey++;
  7476. if (mainListUpdated) {
  7477. this.dataSource.notifyDataReload();
  7478. }
  7479. if (playlistUpdated) {
  7480. this.sonDataSource.notifyDataReload();
  7481. }
  7482. }
  7483. @Builder
  7484. detailSheet(item:VideoItem) {
  7485. Scroll() {
  7486. Column() {
  7487. this.songDetail(item)
  7488. }
  7489. }
  7490. .width('100%')
  7491. .height('100%')
  7492. }
  7493. @Builder
  7494. songDetail(currentItem:VideoItem) {
  7495. Column() {
  7496. if (currentItem) {
  7497. Row() {
  7498. Stack() {
  7499. Image(StrUtil.isEmpty(currentItem.pixelMapPath) ? $r('app.media.music_red') :
  7500. currentItem.pixelMapPath)
  7501. .fillColor(this.themeColor)
  7502. .height(80)
  7503. .width(80)
  7504. .borderRadius(10)
  7505. .opacity(this.opacityItem)// 绑定透明度
  7506. .margin({ left: 22 })
  7507. }
  7508. Column() {
  7509. Column() {
  7510. Text(currentItem.name)
  7511. .fontSize(16)
  7512. .maxLines(1)
  7513. .animation({
  7514. duration: 555,
  7515. curve: 'Linear',
  7516. })
  7517. .fontColor($r('app.color.text_color'))
  7518. .margin({ left: 15 })
  7519. }
  7520. .height('100%')
  7521. .width('100%')
  7522. .justifyContent(FlexAlign.Center)
  7523. .alignItems(HorizontalAlign.Start)
  7524. }
  7525. .height('100%')
  7526. }
  7527. .width('100%')
  7528. .height(90)
  7529. .justifyContent(FlexAlign.SpaceBetween)
  7530. Row() {
  7531. Text('艺术家:')
  7532. .fontSize(14)
  7533. .fontColor($r('app.color.text_color'))
  7534. .margin({ left: 22 })
  7535. Text(currentItem?.artist ? currentItem.artist : '未知歌手')
  7536. .fontSize(14)
  7537. .fontColor($r('app.color.text_color'))
  7538. .margin({ left: 10 })
  7539. .layoutWeight(1)
  7540. }
  7541. .width('100%')
  7542. .margin({ top: 10, bottom: 10 })
  7543. .justifyContent(FlexAlign.Start)
  7544. Row() {
  7545. Text('专辑名:')
  7546. .fontSize(14)
  7547. .fontColor($r('app.color.text_color'))
  7548. .margin({ left: 22 })
  7549. Text(currentItem?.album ?currentItem.album : '未知专辑')
  7550. .fontSize(14)
  7551. .margin({ left: 10 })
  7552. .fontColor($r('app.color.text_color'))
  7553. .layoutWeight(1)
  7554. }
  7555. .width('100%')
  7556. .margin({ top: 10, bottom: 10 })
  7557. .justifyContent(FlexAlign.Start)
  7558. Row() {
  7559. Text('时长:')
  7560. .fontSize(14)
  7561. .fontColor($r('app.color.text_color'))
  7562. .margin({ left: 22 })
  7563. Text(StrUtil.isEmpty(currentItem.duration)?
  7564. (this.isShowDetailMore?this.totalTime:'未知'):currentItem.duration)
  7565. .fontSize(14)
  7566. .margin({ left: 10 })
  7567. .fontColor($r('app.color.text_color'))
  7568. .layoutWeight(1)
  7569. }
  7570. .width('100%')
  7571. .margin({ top: 10, bottom: 10 })
  7572. .justifyContent(FlexAlign.Start)
  7573. Row() {
  7574. Text('采样率:')
  7575. .fontSize(14)
  7576. .fontColor($r('app.color.text_color'))
  7577. .margin({ left: 22 })
  7578. Text(Utility.convertToKHz(currentItem.sampleRate))
  7579. .fontSize(14)
  7580. .margin({ left: 10 })
  7581. .fontColor($r('app.color.text_color'))
  7582. .layoutWeight(1)
  7583. }
  7584. .width('100%')
  7585. .margin({ top: 10, bottom: 10 })
  7586. .justifyContent(FlexAlign.Start)
  7587. Row() {
  7588. Text('比特率:')
  7589. .fontSize(14)
  7590. .fontColor($r('app.color.text_color'))
  7591. .margin({ left: 22 })
  7592. Text(currentItem.bit_rate)
  7593. .fontSize(14)
  7594. .margin({ left: 10 })
  7595. .fontColor($r('app.color.text_color'))
  7596. .layoutWeight(1)
  7597. }
  7598. .width('100%')
  7599. .margin({ top: 10, bottom: 10 })
  7600. .justifyContent(FlexAlign.Start)
  7601. Row() {
  7602. Text('位深:')
  7603. .fontSize(14)
  7604. .fontColor($r('app.color.text_color'))
  7605. .margin({ left: 22 })
  7606. Text(`${currentItem.bits_per_raw_sample} bits`)
  7607. .fontSize(14)
  7608. .margin({ left: 10 })
  7609. .fontColor($r('app.color.text_color'))
  7610. .layoutWeight(1)
  7611. }
  7612. .width('100%')
  7613. .margin({ top: 10, bottom: 10 })
  7614. .justifyContent(FlexAlign.Start)
  7615. Row() {
  7616. Text('声道:')
  7617. .fontSize(14)
  7618. .fontColor($r('app.color.text_color'))
  7619. .margin({ left: 22 })
  7620. Text(`${currentItem.channels}`)
  7621. .fontSize(14)
  7622. .margin({ left: 10 })
  7623. .fontColor($r('app.color.text_color'))
  7624. .layoutWeight(1)
  7625. }
  7626. .width('100%')
  7627. .margin({ top: 10, bottom: 10 })
  7628. .justifyContent(FlexAlign.Start)
  7629. Row() {
  7630. Text('声道布局:')
  7631. .fontSize(14)
  7632. .fontColor($r('app.color.text_color'))
  7633. .margin({ left: 22 })
  7634. Text(`${currentItem.channel_layout}`)
  7635. .fontSize(14)
  7636. .margin({ left: 10 })
  7637. .fontColor($r('app.color.text_color'))
  7638. .layoutWeight(1)
  7639. }
  7640. .width('100%')
  7641. .margin({ top: 10, bottom: 10 })
  7642. .justifyContent(FlexAlign.Start)
  7643. Row() {
  7644. Text('起始播放点:')
  7645. .fontSize(14)
  7646. .fontColor($r('app.color.text_color'))
  7647. .margin({ left: 22 })
  7648. Text(`${currentItem.start_time}`)
  7649. .fontSize(14)
  7650. .margin({ left: 10 })
  7651. .fontColor($r('app.color.text_color'))
  7652. .layoutWeight(1)
  7653. }
  7654. .width('100%')
  7655. .margin({ top: 10, bottom: 10 })
  7656. .justifyContent(FlexAlign.Start)
  7657. Row() {
  7658. Text('风格:')
  7659. .fontSize(14)
  7660. .fontColor($r('app.color.text_color'))
  7661. .margin({ left: 22 })
  7662. Text(currentItem.genre)
  7663. .fontSize(14)
  7664. .margin({ left: 10 })
  7665. .fontColor($r('app.color.text_color'))
  7666. .layoutWeight(1)
  7667. }
  7668. .width('100%')
  7669. .margin({ top: 10, bottom: 10 })
  7670. .justifyContent(FlexAlign.Start)
  7671. Row() {
  7672. Text('发行时间:')
  7673. .fontSize(14)
  7674. .fontColor($r('app.color.text_color'))
  7675. .margin({ left: 22 })
  7676. Text(currentItem.year)
  7677. .fontSize(14)
  7678. .margin({ left: 10 })
  7679. .fontColor($r('app.color.text_color'))
  7680. .layoutWeight(1)
  7681. }
  7682. .width('100%')
  7683. .margin({ top: 10, bottom: 10 })
  7684. .justifyContent(FlexAlign.Start)
  7685. Row() {
  7686. Text('质量评分:')
  7687. .fontSize(14)
  7688. .fontColor($r('app.color.text_color'))
  7689. .margin({ left: 22 })
  7690. Text(currentItem.probe_score+"")
  7691. .fontSize(14)
  7692. .margin({ left: 10 })
  7693. .fontColor($r('app.color.text_color'))
  7694. .layoutWeight(1)
  7695. }
  7696. .width('100%')
  7697. .margin({ top: 10, bottom: 10 })
  7698. .justifyContent(FlexAlign.Start)
  7699. Row() {
  7700. Text('音轨号:')
  7701. .fontSize(14)
  7702. .fontColor($r('app.color.text_color'))
  7703. .margin({ left: 22 })
  7704. Text(currentItem.track)
  7705. .fontSize(14)
  7706. .margin({ left: 10 })
  7707. .fontColor($r('app.color.text_color'))
  7708. .layoutWeight(1)
  7709. }
  7710. .width('100%')
  7711. .margin({ top: 10, bottom: 10 })
  7712. .justifyContent(FlexAlign.Start)
  7713. Row() {
  7714. Text('碟号:')
  7715. .fontSize(14)
  7716. .fontColor($r('app.color.text_color'))
  7717. .margin({ left: 22 })
  7718. Text(currentItem.disc)
  7719. .fontSize(14)
  7720. .margin({ left: 10 })
  7721. .fontColor($r('app.color.text_color'))
  7722. .layoutWeight(1)
  7723. }
  7724. .width('100%')
  7725. .margin({ top: 10, bottom: 10 })
  7726. .justifyContent(FlexAlign.Start)
  7727. Row() {
  7728. Text('专辑艺术家:')
  7729. .fontSize(14)
  7730. .fontColor($r('app.color.text_color'))
  7731. .margin({ left: 22 })
  7732. Text(currentItem.ALBUMARTIST)
  7733. .fontSize(14)
  7734. .margin({ left: 10 })
  7735. .fontColor($r('app.color.text_color'))
  7736. .layoutWeight(1)
  7737. }
  7738. .width('100%')
  7739. .margin({ top: 10, bottom: 10 })
  7740. .justifyContent(FlexAlign.Start)
  7741. Row() {
  7742. Text('作曲家:')
  7743. .fontSize(14)
  7744. .fontColor($r('app.color.text_color'))
  7745. .margin({ left: 22 })
  7746. Text(currentItem.COMPOSER)
  7747. .fontSize(14)
  7748. .margin({ left: 10 })
  7749. .fontColor($r('app.color.text_color'))
  7750. .layoutWeight(1)
  7751. }
  7752. .width('100%')
  7753. .margin({ top: 10, bottom: 10 })
  7754. .justifyContent(FlexAlign.Start)
  7755. Row() {
  7756. Text('作词家:')
  7757. .fontSize(14)
  7758. .fontColor($r('app.color.text_color'))
  7759. .margin({ left: 22 })
  7760. Text(currentItem.LYRICIST)
  7761. .fontSize(14)
  7762. .margin({ left: 10 })
  7763. .fontColor($r('app.color.text_color'))
  7764. .layoutWeight(1)
  7765. }
  7766. .width('100%')
  7767. .margin({ top: 10, bottom: 10 })
  7768. .justifyContent(FlexAlign.Start)
  7769. Row() {
  7770. Text('注释:')
  7771. .fontSize(14)
  7772. .fontColor($r('app.color.text_color'))
  7773. .margin({ left: 22 })
  7774. Text(currentItem.COMMENT)
  7775. .fontSize(14)
  7776. .margin({ left: 10 })
  7777. .fontColor($r('app.color.text_color'))
  7778. .layoutWeight(1)
  7779. }
  7780. .width('100%')
  7781. .margin({ top: 10, bottom: 10 })
  7782. .justifyContent(FlexAlign.Start)
  7783. Row() {
  7784. Text('格式:')
  7785. .fontSize(14)
  7786. .fontColor($r('app.color.text_color'))
  7787. .margin({ left: 22 })
  7788. Text(Utility.formatMimeType(currentItem.mimeType))
  7789. .fontSize(14)
  7790. .margin({ left: 10 })
  7791. .fontColor($r('app.color.text_color'))
  7792. .layoutWeight(1)
  7793. }
  7794. .width('100%')
  7795. .margin({ top: 10, bottom: 10 })
  7796. .justifyContent(FlexAlign.Start)
  7797. Row() {
  7798. Text('播放次数:')
  7799. .fontSize(14)
  7800. .fontColor($r('app.color.text_color'))
  7801. .margin({ left: 22 })
  7802. Text(currentItem.playCount?.toString())
  7803. .fontSize(14)
  7804. .margin({ left: 10 })
  7805. .fontColor($r('app.color.text_color'))
  7806. .layoutWeight(1)
  7807. }
  7808. .width('100%')
  7809. .margin({ top: 10, bottom: 10 })
  7810. .justifyContent(FlexAlign.Start)
  7811. Row() {
  7812. Text('流数量:')
  7813. .fontSize(14)
  7814. .fontColor($r('app.color.text_color'))
  7815. .margin({ left: 22 })
  7816. Text(currentItem.nb_streams?.toString())
  7817. .fontSize(14)
  7818. .margin({ left: 10 })
  7819. .fontColor($r('app.color.text_color'))
  7820. .layoutWeight(1)
  7821. }
  7822. .width('100%')
  7823. .margin({ top: 10, bottom: 10 })
  7824. .justifyContent(FlexAlign.Start)
  7825. Row() {
  7826. Text('文件大小:')
  7827. .fontSize(14)
  7828. .fontColor($r('app.color.text_color'))
  7829. .margin({ left: 22 })
  7830. Text(currentItem.size)
  7831. .fontSize(14)
  7832. .margin({ left: 10 })
  7833. .fontColor($r('app.color.text_color'))
  7834. .layoutWeight(1)
  7835. }
  7836. .width('100%')
  7837. .margin({ top: 10, bottom: 10 })
  7838. .justifyContent(FlexAlign.Start)
  7839. Row() {
  7840. Text('文件名:')
  7841. .fontSize(14)
  7842. .fontColor($r('app.color.text_color'))
  7843. .margin({ left: 22 })
  7844. Text(currentItem.fileName)
  7845. .fontSize(14)
  7846. .margin({ left: 10 })
  7847. .fontColor($r('app.color.text_color'))
  7848. .layoutWeight(1)
  7849. }
  7850. .width('100%')
  7851. .margin({ top: 10, bottom: 10 })
  7852. .justifyContent(FlexAlign.Start)
  7853. Row() {
  7854. Text('修改时间:')
  7855. .fontSize(14)
  7856. .fontColor($r('app.color.text_color'))
  7857. .margin({ left: 22 })
  7858. Text(currentItem.cTime)
  7859. .fontSize(14)
  7860. .margin({ left: 10 })
  7861. .fontColor($r('app.color.text_color'))
  7862. .layoutWeight(1)
  7863. }
  7864. .width('100%')
  7865. .margin({ top: 10, bottom: 10 })
  7866. .justifyContent(FlexAlign.Start)
  7867. Row() {
  7868. Text('存放目录:')
  7869. .fontSize(14)
  7870. .fontColor($r('app.color.text_color'))
  7871. .margin({ left: 22 })
  7872. Text(currentItem.filePath)
  7873. .fontSize(12)
  7874. .margin({ left: 10 })
  7875. .fontColor($r('app.color.text_color'))
  7876. .layoutWeight(1)
  7877. }
  7878. .margin({ top: 10, bottom: 10 })
  7879. .width('100%')
  7880. .justifyContent(FlexAlign.Start)
  7881. Row() {
  7882. Text('内嵌歌词:')
  7883. .fontSize(14)
  7884. .fontColor($r('app.color.text_color'))
  7885. .margin({ left: 22 })
  7886. Text(currentItem.lyricContent)
  7887. .fontSize(12)
  7888. .copyOption(CopyOptions.InApp)
  7889. .margin({ left: 10 })
  7890. .fontColor($r('app.color.text_color'))
  7891. .layoutWeight(1)
  7892. }
  7893. .margin({ top: 10, bottom: 10 })
  7894. .width('100%')
  7895. .justifyContent(FlexAlign.Start)
  7896. }
  7897. }
  7898. .margin({ bottom: 20 })
  7899. }
  7900. //定时关闭布局
  7901. @Builder
  7902. TimeCloseSheet() {
  7903. Scroll() {
  7904. Column() {
  7905. this.TimeClose()
  7906. }
  7907. }
  7908. .width('100%')
  7909. .height('100%')
  7910. }
  7911. //倒计时关闭音乐,退出App功能实现。
  7912. @State selectedMinutes: number = 0 // 0表示未开启
  7913. @State remainingSeconds: number = 0
  7914. // 预设时间选项
  7915. private presetTimes: number[] = [0, 5, 15, 30, 45, 60, -1]
  7916. private formatTime(seconds: number): string {
  7917. const mins = Math.floor(seconds / 60)
  7918. const secs = seconds % 60
  7919. return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  7920. }
  7921. // 开始倒计时
  7922. private handleTimeSelect(minutes: number) {
  7923. if (minutes === this.selectedMinutes) {
  7924. this.stopCountdown();
  7925. this.selectedMinutes = 0;
  7926. return;
  7927. }
  7928. this.selectedMinutes = minutes;
  7929. this.remainingSeconds = minutes * 60;
  7930. this.startCountdown(); // 新增调用
  7931. }
  7932. @Builder
  7933. TimeClose() {
  7934. Column() {
  7935. // 倒计时显示区域
  7936. Text(this.selectedMinutes > 0 ?
  7937. `剩余时间:${this.formatTime(this.remainingSeconds)}` :
  7938. "定时关闭未开启")
  7939. .fontSize(17)
  7940. .fontColor($r('app.color.text_color'))
  7941. .margin({ top: 2, bottom: 8 });
  7942. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  7943. ForEach(this.presetTimes, (minutes: number, index: number) => {
  7944. // 单行时间选项容器
  7945. Row() {
  7946. // 文字描述区域
  7947. Text(this.getDisplayText(minutes))
  7948. .fontSize(15)
  7949. .fontColor(minutes === this.selectedMinutes ? this.themeColor :
  7950. $r('app.color.text_color'))// 选中态颜色变化
  7951. .textAlign(TextAlign.Start)
  7952. .layoutWeight(1); // 占据剩余空间
  7953. // 复选框样式的选择器
  7954. Row() {
  7955. if (minutes === this.selectedMinutes) {
  7956. // 选中状态 - 带勾号的圆形复选框
  7957. Row() {
  7958. // 使用系统内置的勾号图标
  7959. Image($r('sys.media.ohos_ic_public_ok'))
  7960. .width(14)
  7961. .height(14)
  7962. .fillColor(Color.White)
  7963. }
  7964. .width(24)
  7965. .height(24)
  7966. .borderRadius(12)
  7967. .backgroundColor(this.themeColor)
  7968. .justifyContent(FlexAlign.Center)
  7969. .alignItems(VerticalAlign.Center)
  7970. } else {
  7971. // 未选中状态的圆形边框
  7972. Row()
  7973. .width(24)
  7974. .height(24)
  7975. .borderRadius(12)
  7976. .border({
  7977. width: 2,
  7978. color: $r('app.color.text_color'),
  7979. style: BorderStyle.Solid
  7980. })
  7981. .backgroundColor(Color.Transparent)
  7982. }
  7983. }
  7984. .width(24)
  7985. .height(24)
  7986. .margin({ left: 20 })
  7987. .justifyContent(FlexAlign.Center)
  7988. .alignItems(VerticalAlign.Center)
  7989. }
  7990. .width('100%')
  7991. .padding({
  7992. top: 18,
  7993. bottom: 18,
  7994. left: 18,
  7995. right: 18
  7996. })
  7997. .backgroundColor(minutes === this.selectedMinutes ? $r('app.color.timeColor_bg') :
  7998. $r('app.color.bottom_control_background')) // 选中背景高亮
  7999. .borderRadius(12)
  8000. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  8001. .margin({ bottom: 18 })
  8002. .onClick(() => this.handleSelect(minutes)); // 点击整行触发选择
  8003. });
  8004. }
  8005. .width('100%')
  8006. .padding(16)
  8007. }
  8008. }
  8009. // 获取显示文本
  8010. private getDisplayText(minutes: number): string {
  8011. if (minutes === -1) {
  8012. return Utility.resourceToString(getContext(this), $r('app.string.customize'));
  8013. }
  8014. return minutes === 0 ? Utility.resourceToString(getContext(this), $r('app.string.close')) :
  8015. `${minutes}` + Utility.resourceToString(getContext(this), $r('app.string.minute_after'));
  8016. }
  8017. // 处理选择事件
  8018. private handleSelect(minutes: number): void {
  8019. if (minutes === -1) { // 自定义
  8020. // 弹出自定义时间对话框
  8021. DialogHelper.showTextInputDialog({
  8022. title: '自定义时间',
  8023. maskColor: Color.Transparent,
  8024. inputType: InputType.Number,
  8025. text: '',
  8026. onChange: (text) => {
  8027. console.error("onChange: " + text);
  8028. },
  8029. onAction: (action, dialogId, content) => {
  8030. if (action == DialogAction.TWO) {
  8031. const customMinutes = Number(content);
  8032. if (customMinutes > 0) {
  8033. this.handleTimeSelect(customMinutes); // 设置自定义时间
  8034. ToastUtil.showToast("设置成功," + customMinutes + "分钟后定时关闭");
  8035. }
  8036. }
  8037. }
  8038. });
  8039. } else {
  8040. this.handleTimeSelect(minutes); // 统一调用选择处理方法
  8041. }
  8042. }
  8043. // 添加定时器引用
  8044. private timerId: number = -1;
  8045. // 启动/重置倒计时
  8046. private startCountdown() {
  8047. // 清除旧定时器
  8048. if (this.timerId !== -1) {
  8049. clearInterval(this.timerId);
  8050. }
  8051. // 创建新定时器
  8052. if (this.selectedMinutes > 0) {
  8053. this.timerId = setInterval(() => {
  8054. if (this.remainingSeconds === 15) {
  8055. this.showConfirmationDialog();
  8056. }
  8057. if (this.remainingSeconds > 0) {
  8058. this.remainingSeconds -= 1;
  8059. } else {
  8060. this.stopCountdown();
  8061. this.handleTimeout();
  8062. }
  8063. }, 1000);
  8064. }
  8065. }
  8066. // 15倒计时后再次提示显示确认是否关闭App对话框
  8067. private showConfirmationDialog() {
  8068. DialogHelper.showAlertDialog({
  8069. backgroundColor: $r('app.color.btn_green'),
  8070. title: '确认关闭',
  8071. maskColor: Color.Transparent,
  8072. content: "马上到达定时关闭时间,您是否确定要退出应用?",
  8073. borderStyle: BorderStyle.Dashed,
  8074. primaryButton: '暂不关闭',
  8075. secondaryButton: '确定',
  8076. onAction: (action) => {
  8077. if (action == DialogAction.ONE) { //暂不关闭,取消定时
  8078. this.stopCountdown();
  8079. this.selectedMinutes = 0
  8080. } else if (action == DialogAction.TWO) {
  8081. }
  8082. }
  8083. })
  8084. }
  8085. // 停止倒计时
  8086. private stopCountdown() {
  8087. if (this.timerId !== -1) {
  8088. clearInterval(this.timerId);
  8089. this.timerId = -1;
  8090. }
  8091. }
  8092. // 超时处理
  8093. private handleTimeout() {
  8094. // 执行播放器关闭逻辑
  8095. this.selectedMinutes = 0;
  8096. ToastUtil.showToast(" 定时关闭已完成");
  8097. this.stop(); // 假设存在的播放器实例
  8098. //退出APP
  8099. const mContext = getContext(this) as common.UIAbilityContext
  8100. mContext.terminateSelf();
  8101. AvSessionController.getInstance(true).unregisterSessionListener()
  8102. }
  8103. //倒计时关闭音乐,退出App功能实现结束。
  8104. //播放列表的拖动List 重新排序
  8105. @State sonDataSource: LazyDataSource<VideoItem> = new LazyDataSource(this.songList)
  8106. //左滑操作 移动文件 重命名 删除等操作
  8107. @Builder
  8108. sonButton(item: VideoItem, index: number, filePath: string) {
  8109. Row() {
  8110. //加入下一首播放
  8111. Button() {
  8112. Image($r('app.media.next_to_play'))
  8113. .fillColor(Color.White)
  8114. .width(20)
  8115. }
  8116. .width(40)
  8117. .height(40)
  8118. .type(ButtonType.Circle)
  8119. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  8120. .backgroundColor(this.themeColor)
  8121. .margin(5)
  8122. .onClick(() => {
  8123. this.addToNextPlay(item);
  8124. })
  8125. Button() {
  8126. Image($r('app.media.close'))
  8127. .fillColor(Color.White)
  8128. .width(20)
  8129. }
  8130. .width(40)
  8131. .height(40)
  8132. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  8133. .type(ButtonType.Circle)
  8134. .backgroundColor(this.themeColor)
  8135. .margin(5)
  8136. .onClick(() => {
  8137. this.songList.splice(Number(index), 1)
  8138. this.sonDataSource.pushArrayData(this.songList)
  8139. })
  8140. Button() {
  8141. Image($r('app.media.share2'))
  8142. .fillColor(Color.White)
  8143. .width(20)
  8144. }
  8145. .width(40)
  8146. .height(40)
  8147. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.7})
  8148. .type(ButtonType.Circle)
  8149. .backgroundColor(this.themeColor)
  8150. .margin(5)
  8151. .onClick(() => {
  8152. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  8153. })
  8154. }
  8155. }
  8156. itemMoveSon(index: number, newIndex: number): void {
  8157. if (newIndex < 0 || newIndex >= this.songList.length) {
  8158. return;
  8159. }
  8160. let tmp = this.songList.splice(index, 1);
  8161. this.songList.splice(newIndex, 0, tmp[0]);
  8162. this.sonDataSource.pushArrayData(this.songList)
  8163. this.curIndex = Utility.getIndexFromList(this.songList, this.videoUrl)
  8164. if(this.modeType==4&&this.playlistTable){
  8165. updateAllSongsSortOrder(this.playlistTable, this.songList,this.currentSongListID)
  8166. }
  8167. }
  8168. @Builder
  8169. PlayList() {
  8170. List({ scroller: this.playListScroller }) {
  8171. LazyForEach(this.sonDataSource, (item: VideoItem, index: number) => {
  8172. ListItem() {
  8173. this.MusicItemSon(item, index)
  8174. }
  8175. .swipeAction({ end: this.sonButton(item, index, item.filePath) }) //左滑
  8176. .animation({
  8177. duration: 666,
  8178. curve: 'ease-in-out' // 可选动画曲线
  8179. })
  8180. .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 600 }),
  8181. TransitionEffect.scale({ x: 0, y: 0 })))
  8182. .clickEffect({ level: ClickEffectLevel.MIDDLE })
  8183. //拖动List关键代码开始
  8184. .scale({ x: this.scaleSelect(index), y: this.scaleSelect(index) })
  8185. .zIndex(this.dragItem === index ? 1 : 0)
  8186. .translate(this.dragItem === index ? { y: this.offsetY } : { y: 0 })
  8187. .gesture(
  8188. GestureGroup(GestureMode.Sequence,
  8189. LongPressGesture({ repeat: true })
  8190. .onAction((event?: GestureEvent) => {
  8191. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  8192. this.scaleItem = index
  8193. })
  8194. })
  8195. .onActionEnd(() => {
  8196. animateTo({ curve: Curve.Friction, duration: 300 }, () => {
  8197. this.scaleItem = -1
  8198. })
  8199. }),
  8200. PanGesture({ fingers: 1, direction: null, distance: 0 })
  8201. .onActionStart(() => {
  8202. this.dragItem = index // 记录当前拖动项索引
  8203. this.dragRefOffset = 0 // 重置偏移基准
  8204. })
  8205. .onActionUpdate((event: GestureEvent) => {
  8206. this.offsetY = event.offsetY - this.dragRefOffset;
  8207. this.neighborItem = -1;
  8208. let indexA = this.songList.indexOf(item);
  8209. // LogUtil.info('onecold indexA = '+indexA +' index=='+index)
  8210. let curveValue: curves.ICurve = curves.initCurve(Curve.Sharp);
  8211. let value: number = 0;
  8212. if (this.offsetY < 0) {
  8213. value = curveValue.interpolate(-this.offsetY / this.ITEM_INTV);
  8214. this.neighborItem = indexA - 1;
  8215. this.neighborScale = 1 - value / 20;
  8216. } else if (this.offsetY > 0) {
  8217. value = curveValue.interpolate(this.offsetY / this.ITEM_INTV);
  8218. this.neighborItem = indexA + 1;
  8219. this.neighborScale = 1 - value / 20;
  8220. }
  8221. if (this.offsetY > this.ITEM_INTV / 2 && indexA + 1 < this.songList.length) {
  8222. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8223. this.offsetY -= this.ITEM_INTV;
  8224. this.dragRefOffset += this.ITEM_INTV;
  8225. this.itemMoveSon(indexA, indexA + 1);
  8226. });
  8227. } else if (this.offsetY < -this.ITEM_INTV / 2 && indexA - 1 >= 0) {
  8228. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8229. this.offsetY += this.ITEM_INTV;
  8230. this.dragRefOffset -= this.ITEM_INTV;
  8231. this.itemMoveSon(indexA, indexA - 1);
  8232. });
  8233. }
  8234. })
  8235. .onActionEnd((event: GestureEvent) => {
  8236. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8237. this.dragItem = -1
  8238. this.neighborItem = -1
  8239. })
  8240. animateTo({
  8241. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  8242. }, () => {
  8243. this.scaleItem = -1
  8244. })
  8245. })
  8246. )
  8247. .onCancel(() => {
  8248. animateTo({ curve: curves.interpolatingSpring(0, 1, 400, 38) }, () => {
  8249. this.dragItem = -1
  8250. this.neighborItem = -1
  8251. })
  8252. animateTo({
  8253. curve: curves.interpolatingSpring(14, 1, 170, 17), delay: 150
  8254. }, () => {
  8255. this.scaleItem = -1
  8256. })
  8257. })
  8258. ) //拖动List关键代码结束
  8259. .onClick(() => {
  8260. this.doPlay(item, index, true)
  8261. })
  8262. }, (item: VideoItem) => item.filePath + '_' + this.listRefreshKey)
  8263. }
  8264. .width('100%')
  8265. .height('100%')
  8266. // .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  8267. // .animation({ duration: 500, curve: Curve.Ease }))
  8268. .cachedCount(10)
  8269. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  8270. .gesture(PinchGesture({ fingers: 2 })
  8271. .onActionEnd((event: GestureEvent) => {
  8272. this.setSonListTwoFingers()
  8273. })
  8274. .onActionUpdate(e => {
  8275. this.scaleValue = this.pinchValue * e.scale
  8276. })
  8277. .onActionStart(e => {
  8278. }))
  8279. .padding({
  8280. bottom: 0
  8281. })
  8282. }
  8283. setSonListTwoFingers() {
  8284. this.pinchValue = this.scaleValue;
  8285. Logger.info('this.pinchValue = ' + this.pinchValue);
  8286. if (this.pinchValue >= 1) {
  8287. this.sonTwoFingerType++
  8288. Logger.info('this.twoFingerType1 = ' + this.sonTwoFingerType);
  8289. if (this.sonTwoFingerType > 3) {
  8290. this.sonTwoFingerType = 1
  8291. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  8292. }
  8293. } else {
  8294. this.sonTwoFingerType--
  8295. Logger.info('this.twoFingerType2 = ' + this.sonTwoFingerType);
  8296. if (this.sonTwoFingerType < 1) {
  8297. this.sonTwoFingerType = 1
  8298. }
  8299. }
  8300. PreferencesUtil.put('sonTwoFingerType', this.sonTwoFingerType)
  8301. this.pinchValue = 1;
  8302. this.scaleValue = 1;
  8303. }
  8304. @State sonTwoFingerType:number = 3
  8305. @Builder
  8306. private MusicItemSon(item: VideoItem, index?: number) {
  8307. Button({ type: ButtonType.Normal, stateEffect: true }) {
  8308. Row() {
  8309. Stack() {
  8310. Image(StrUtil.isEmpty(item.pixelMapPath) ? $r('app.media.music_red') : item.pixelMapPath)
  8311. .height(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  8312. .width(this.sonTwoFingerType == 3||this.sonTwoFingerType==4 ? 55 : this.sonTwoFingerType == 2 ? 48 : 40)
  8313. .alt($r('app.media.music_red'))
  8314. .fillColor(this.themeColor)
  8315. .borderRadius('100%')
  8316. .clip(true)
  8317. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  8318. .draggable(false)// 禁止长按手势拖动
  8319. .autoResize(true) // 重采样,可减少内存占用
  8320. .margin({ left: 20 })
  8321. }
  8322. .width('15%')
  8323. Column() {
  8324. Column() {
  8325. Text(this.isShowFileName?item.fileName :item.name)
  8326. .fontSize(this.sonTwoFingerType == 1 ? 12 : this.sonTwoFingerType == 2 ? 15 : 18)
  8327. .fontColor(this.curIndex === index ? this.themeColor :
  8328. this.isFrontWhite ? Color.White : $r('app.color.text_color'))
  8329. .maxLines(1)
  8330. .margin({ left: this.sonTwoFingerType == 3 ? 18 : 10 })
  8331. Row() {
  8332. Column(){
  8333. Text(item.md5Str?.includes('Lossless')?
  8334. Utility.resourceToString(this.context,$r('app.string.lossless')):item.md5Str)//音质
  8335. .fontSize(this.sonTwoFingerType == 1 ? 8 : this.sonTwoFingerType == 2 ? 9 : 11)
  8336. .padding({ top: 3,right:6,left:6,bottom:3 })
  8337. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  8338. $r('app.color.text_color'))
  8339. .fontWeight(500)
  8340. .borderRadius(12)
  8341. .margin({ left: this.sonTwoFingerType == 3 ? 12 : 10 })
  8342. .backgroundColor('#FFC107')
  8343. }
  8344. .padding({ top: 8 })
  8345. Text(StrUtil.isEmpty(item.artist) ? item.duration :
  8346. item.artist + ' ' + item?.duration)
  8347. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  8348. .padding({ top: 8 })
  8349. .maxLines(1)
  8350. .fontColor(this.curIndex === index ? this.themeColor :
  8351. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  8352. .margin({ left: this.sonTwoFingerType == 3 ? 5 : 3 })
  8353. Blank()
  8354. Text(item.size)
  8355. .fontSize(this.sonTwoFingerType == 1 ? 11 : this.sonTwoFingerType == 2 ? 12 : 14)
  8356. .padding({ top: 8 })
  8357. .maxLines(1)
  8358. .visibility(StrUtil.isEmpty(item.artist) ? Visibility.Visible : Visibility.None)
  8359. .fontColor(this.curIndex === index ? $r('app.color.title_bar_bg_text') :
  8360. this.isFrontWhite ? $r('app.color.playlistText_color') : $r('app.color.text_color'))
  8361. .margin({ left: 10 })
  8362. }
  8363. }
  8364. .height('100%')
  8365. .width('100%')
  8366. .justifyContent(FlexAlign.Center)
  8367. .alignItems(HorizontalAlign.Start)
  8368. }
  8369. .height('100%')
  8370. .width('65%')
  8371. Column() {
  8372. ImageAnimator()
  8373. .images(this.imagesF)// 动画数组
  8374. .duration(1000)// 持续
  8375. .state(this.animationState)// 动画状态
  8376. .fillMode(FillMode.Forwards)
  8377. .width(18)
  8378. .visibility(this.videoUrl === item.filePath ? this.isMultiSelect ? Visibility.None : Visibility.Visible :
  8379. Visibility.None)
  8380. .height(18)
  8381. .iterations(-1) // 播放次数
  8382. }
  8383. .width('20%')
  8384. }
  8385. }
  8386. .backgroundColor(Color.Transparent)
  8387. .width('100%')
  8388. .reuseId('son_item')
  8389. .height(this.sonTwoFingerType == 3 ? ITEM_HEIGHT_BIG : this.sonTwoFingerType == 2 ? ITEM_HEIGHT+10 : ITEM_HEIGHT_SMALL+10)
  8390. .shadow(this.scaleItem === index ? {
  8391. radius: 70,
  8392. color: '#15000000',
  8393. offsetX: 0,
  8394. offsetY: 0
  8395. } :
  8396. {
  8397. radius: 0,
  8398. color: '#15000000',
  8399. offsetX: 0,
  8400. offsetY: 0
  8401. })
  8402. .animation({ curve: Curve.Sharp, duration: 300 })
  8403. }
  8404. @Builder
  8405. MusicPlayBuilder() {
  8406. Column() {
  8407. this.IjkMusicPlayerView()
  8408. }
  8409. .transition(TransitionEffect.asymmetric(
  8410. TransitionEffect.opacity(1),
  8411. TransitionEffect.OPACITY
  8412. ))
  8413. .visualEffect(deviceInfo.sdkApiVersion>=20&&this.bgController?
  8414. new hdsEffect.HdsEffectBuilder()
  8415. .shaderEffect({
  8416. effectType: hdsEffect.EffectType.UV_BACKGROUND_FLOW_LIGHT,
  8417. animation: {
  8418. duration: 10000,
  8419. iterations: -1,
  8420. autoPlay: true,
  8421. onFinish: ()=> {
  8422. console.info('Succeeded in finishing');
  8423. }
  8424. },
  8425. controller: this.bgController,
  8426. })
  8427. .buildEffect():null)
  8428. .height('100%')
  8429. .width('100%')
  8430. .onDisAppear(() => {
  8431. this.translateY = 0;
  8432. })
  8433. .translate({ y: this.translateY })
  8434. .gesture(
  8435. PanGesture(this.panOption)
  8436. .onActionUpdate((event?: GestureEvent) => {
  8437. if (event) {
  8438. // 只允许向下滑动,向上滑动时限制为0
  8439. this.translateY = Math.max(0, event.offsetY);
  8440. this.getUIContext().animateTo({
  8441. duration: 500,
  8442. curve: Curve.Sharp
  8443. }, () => {
  8444. this.scaleValueImage = Math.min(1, Math.max(0.3, 1 - event.offsetY / 350));
  8445. console.info('onecold scaleValueImage:', this.scaleValueImage)
  8446. this.scaleValueText =Math.min(1, Math.max(0.6, 1 - event.offsetY / 400));
  8447. })
  8448. }
  8449. })
  8450. .onActionEnd((event?: GestureEvent) => {
  8451. // 使用更低的阈值和滑动速度判断
  8452. const minDistance = 300; // 最小滑动距离 100vp
  8453. const minVelocity = 500; // 最小滑动速度
  8454. // 获取滑动速度(如果可用)
  8455. const velocity = event?.velocityY || 0;
  8456. // 判断是否应该关闭:距离足够 或者 速度足够快
  8457. const shouldClose = this.translateY > minDistance || velocity > minVelocity;
  8458. if (shouldClose) {
  8459. // 添加关闭动画
  8460. this.getUIContext().animateTo({
  8461. duration: 600,
  8462. curve: Curve.Friction
  8463. }, () => {
  8464. this.isShowPlay = false;
  8465. this.scaleValueImage = 1
  8466. this.scaleValueText = 1
  8467. this.translateY = 0;
  8468. })
  8469. } else {
  8470. // 回弹动画
  8471. this.getUIContext().animateTo({
  8472. duration: 600,
  8473. curve: Curve.Friction
  8474. }, () => {
  8475. this.scaleValueImage = 1
  8476. this.scaleValueText = 1
  8477. this.translateY = 0;
  8478. })
  8479. }
  8480. })
  8481. )
  8482. }
  8483. @StorageProp('currentBreakpoint') currentBreakpoint: string = BreakpointTypeEnum.MD; //一多界面适配
  8484. @StorageProp('currentHeightBreakpoint') currentHeightBreakpoint: HeightBreakpoint | undefined =
  8485. HeightBreakpoint.HEIGHT_LG;
  8486. @StorageProp('currentWidthBreakpoint') currentWidthBreakpoint: WidthBreakpoint | undefined = WidthBreakpoint.WIDTH_SM;
  8487. @State topBarHeight: number = 50
  8488. @State barOpacity: number = 1
  8489. @State barBottomOpacity: number = 1
  8490. private hideDone: boolean = false;
  8491. @State currentYOffset: number = 0;
  8492. @State bottomBarHeight: number = 68;
  8493. private isHiding: boolean = false;
  8494. //是否是Pura X外屏,或者小屏幕
  8495. isPuraWP() {
  8496. return this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  8497. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_MD
  8498. }
  8499. //是否是Pura X外屏,或者小屏幕,手机横屏
  8500. /**
  8501. * 是否是Pura X外屏,或者小屏幕,手机横屏
  8502. * @returns
  8503. */
  8504. isCoverOpacity() {
  8505. if (this.isPuraWP()) {
  8506. return true
  8507. }
  8508. if (this.isPhoneLan()) {
  8509. return true
  8510. }
  8511. if (deviceInfo.marketName.includes('Pura X')
  8512. && this.currentHeightBreakpoint === HeightBreakpoint.HEIGHT_SM) {
  8513. return true
  8514. }
  8515. return false
  8516. }
  8517. //是不是手机横屏
  8518. isPhoneLan() {
  8519. // LogUtil.info('twocold this.currentHeightBreakpoint = '+this.currentHeightBreakpoint)
  8520. // LogUtil.info('twocold this.currentWidthBreakpoint = '+this.currentWidthBreakpoint)
  8521. LogUtil.info('hicar isPhoneLan width= ' + this.windowWidth);
  8522. LogUtil.info('hicar isPhoneLan height= ' + this.windowHeight);
  8523. LogUtil.info(`twocold hicarWindow size: ${this.windowWidth}x${this.windowHeight}, this.isHiCarStatus: ${this.isHiCarStatus}`);
  8524. LogUtil.info(`twocold hicar Window size: ${this.windowWidth}x${this.windowHeight}, isHiCarSmall: ${this.isHiCarSmall()}`);
  8525. if (this.isHiCarKuanBianPing()) {
  8526. return true
  8527. }
  8528. if (this.isHiCar()) {
  8529. return false
  8530. }
  8531. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8532. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_SM
  8533. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_MD&&this.isLandscape) { //如果是手机横屏,返回true
  8534. return true
  8535. }
  8536. return false
  8537. }
  8538. //是不是1920x720的hicar的屏幕分辨率
  8539. isHiCarKuanBianPing(){
  8540. if(!this.isHiCar()){
  8541. return false
  8542. }
  8543. const hiCarAspectRatios: HiCarAspectRatio[] = [
  8544. { ratio: 1920 / 720, name: "1920x720" },
  8545. ];
  8546. const currentRatio: number = this.windowWidth / this.windowHeight;
  8547. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  8548. LogUtil.info('twocold isHiCarKuanBianPing currentRatio = ' + currentRatio)
  8549. for (const hiCarRatio of hiCarAspectRatios) {
  8550. LogUtil.info('twocold isHiCarKuanBianPing hiCarRatio= ' + hiCarRatio.ratio)
  8551. LogUtil.info('twocold isHiCarKuanBianPing Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  8552. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  8553. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  8554. //宽扁平的尺寸设置列表展示
  8555. this.twoFingerType ==3
  8556. this.isGridMusic = false
  8557. return true;
  8558. }
  8559. }
  8560. return false;
  8561. }
  8562. //是不是hicar的屏幕分辨率
  8563. isHiCarSmall() {
  8564. if(!this.isHiCar()){
  8565. return false
  8566. }
  8567. if(this.windowWidth>1800&&this.windowHeight>=1200)//大屏幕可以Grid
  8568. {
  8569. this.columns = 6
  8570. return false
  8571. }
  8572. const hiCarAspectRatios: HiCarAspectRatio[] = [
  8573. { ratio: 800 / 480, name: "800x480" },
  8574. { ratio: 1280 / 720, name: "1280x720" },
  8575. { ratio: 1920 / 1080, name: "1920x1080" },
  8576. ];
  8577. const currentRatio: number = this.windowWidth / this.windowHeight;
  8578. const RATIO_TOLERANCE: number = 0.22; // 宽高比容差
  8579. LogUtil.info('twocold isHiCarSmall currentRatio = ' + currentRatio)
  8580. for (const hiCarRatio of hiCarAspectRatios) {
  8581. LogUtil.info('twocold isHiCarSmall hiCarRatio= ' + hiCarRatio.ratio)
  8582. LogUtil.info('twocold isHiCarSmall Math.abs(currentRatio - hiCarRatio.ratio)= ' + Math.abs(currentRatio - hiCarRatio.ratio))
  8583. LogUtil.info('twocold isHiCarSmall isHiCarStatus= ' + this.isHiCarStatus);
  8584. if (Math.abs(currentRatio - hiCarRatio.ratio) <= RATIO_TOLERANCE) {
  8585. // LogUtil.info(`HiCar detected: ${hiCarRatio.name}, actual: ${this.windowWidth}x${this.windowHeight}`);
  8586. //宽扁平的尺寸设置列表展示
  8587. return true;
  8588. }
  8589. }
  8590. return false;
  8591. }
  8592. isHiCar() {
  8593. return this.isHiCarStatus&&this.curDisplayIsHiCar;
  8594. }
  8595. //是不是正常的手机竖屏
  8596. isPhonePortrait() {
  8597. // LogUtil.info('twocold this.currentHeightBreakpoint = ' + this.currentHeightBreakpoint)
  8598. // LogUtil.info('twocold this.currentWidthBreakpoint = ' + this.currentWidthBreakpoint)
  8599. // LogUtil.info('Heanup 当前设备类型:' + DeviceUtil.getDeviceType())
  8600. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  8601. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG
  8602. && this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_SM) { //如果是手机横屏,返回false
  8603. return true
  8604. }
  8605. return false
  8606. }
  8607. @State showSpeedDialog: boolean = false
  8608. @State longPressSpeed: number = 3 //长按默认倍数
  8609. @Builder
  8610. SpeedDialog() {
  8611. Stack() {
  8612. Column() {
  8613. Text('已切换至' + this.longPressSpeed + '倍速播放')
  8614. .fontColor(Color.White)
  8615. .visibility(Visibility.Hidden)
  8616. }
  8617. .backgroundColor(Color.Black)
  8618. .borderRadius(20)
  8619. .padding({
  8620. top: 10,
  8621. right: 20,
  8622. left: 15,
  8623. bottom: 20
  8624. })
  8625. .opacity(0.6)
  8626. Text('已切换至' + this.longPressSpeed + '倍速播放')
  8627. .fontColor(Color.White)
  8628. }
  8629. .transition(TransitionEffect.OPACITY.animation({ duration: 500, curve: Curve.Ease }))
  8630. .zIndex(5)
  8631. .margin({ top: 80 })
  8632. }
  8633. @Builder
  8634. IjkMusicPlayerView() {
  8635. Stack() {
  8636. if(canIUse("SystemCapability.UIDesign.HDSComponent.Core")
  8637. &&deviceInfo.sdkApiVersion>=20&&this.sceneBgController){
  8638. HdsVisualComponent()
  8639. .scene(HdsSceneType.DUAL_EDGE_FLOW_LIGHT_WITH_BACKGROUND_MASK, this.sceneBgController, () => {
  8640. console.info('Succeeded in finishing');
  8641. })
  8642. .width('100%')
  8643. .height('100%')
  8644. .visibility(this.isShowBgLiuGUANG?Visibility.Visible:Visibility.None)
  8645. }
  8646. Column() {
  8647. Column() {
  8648. //播放标题
  8649. Column() {
  8650. this.PlayTitle()
  8651. }
  8652. .position({ x: 0, y: this.isCoverOpacity() ? 15 : 40 })
  8653. .width('100%')
  8654. .margin({ top: 0 })
  8655. .height(PlayConstants.HEIGHT)
  8656. .visibility(DeviceUtil.getDeviceType() == resourceManager.DeviceType.DEVICE_TYPE_2IN1 ?
  8657. Visibility.Visible : this.isShowPlayPageBack ? Visibility.Visible : Visibility.None)
  8658. if (this.showSpeedDialog) {
  8659. this.SpeedDialog()
  8660. }
  8661. Stack() {
  8662. //手势拖动快进
  8663. Column()
  8664. .width(CommonConstants.FULL_PERCENT)
  8665. .height('100%')
  8666. .gesture(
  8667. GestureGroup(GestureMode.Parallel,
  8668. // 长按屏幕倍数播放
  8669. LongPressGesture({ repeat: true })
  8670. .onAction(() => {
  8671. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8672. this.showSpeedDialog = true;
  8673. this.mIjkMediaPlayer.setSpeed(this.longPressSpeed + 'f');
  8674. }
  8675. })
  8676. .onActionEnd(() => {
  8677. this.showSpeedDialog = false;
  8678. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  8679. }),
  8680. //双击屏幕暂停或者播放
  8681. TapGesture({ count: 2 })
  8682. .onAction((event: GestureEvent) => {
  8683. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  8684. ToastUtil.showToast('已暂停')
  8685. }
  8686. console.info('onecold playOrPause 6693')
  8687. this.playOrPause()
  8688. })
  8689. )
  8690. )
  8691. }
  8692. .height('65%')
  8693. Swiper() {
  8694. this.CoverInfo()
  8695. this.PlayerLyrics()
  8696. }
  8697. .onChange((index: number) => {
  8698. this.currentSwiperIndex = index
  8699. })
  8700. .indicator(false)
  8701. .displayCount(new BreakpointType({
  8702. sm: 1,
  8703. md: 2,
  8704. lg: 2,
  8705. xl: 2,
  8706. xxl: 2
  8707. }).getValue(this.currentBreakpoint))
  8708. .clip(false)
  8709. .loop(false)
  8710. .autoPlay(false)
  8711. // .interval(8000)
  8712. .position({ x: 0, y: this.isCoverOpacity() ? 30 : 40 })
  8713. .height('100%')
  8714. .hitTestBehavior(HitTestMode.Transparent)
  8715. Image($r('app.media.icon_replay'))
  8716. .objectFit(ImageFit.Auto)
  8717. .width('120px')
  8718. .height('120px')
  8719. .position({ x: '45.1%', y: '47.5%' })// .visibility(this.replayVisible)
  8720. .border({ width: 0 })
  8721. .visibility(Visibility.None)
  8722. .borderStyle(BorderStyle.Dashed)// .hitTestBehavior(HitTestMode.Transparent)
  8723. .onClick(() => {
  8724. console.info('onecold startPlayOrResumePlay 6744')
  8725. this.startPlayOrResumePlay();
  8726. })
  8727. }
  8728. .width(CommonConstants.FULL_PERCENT)
  8729. .height(CommonConstants.FULL_PERCENT)
  8730. .justifyContent(FlexAlign.End)
  8731. }
  8732. .justifyContent(FlexAlign.End)
  8733. .margin({ bottom: 8 })
  8734. }
  8735. .backgroundImage(!this.isMusicBGCover||StrUtil.isEmpty(this.cover)?null: this.cover)
  8736. .backgroundImageSize(this.isPuraWP()||!this.isMusicBGCover ? { width: '100%' } : { height: '150%', width: '100%' })
  8737. .animation({
  8738. duration: 666,
  8739. curve: 'ease-in-out' // 可选动画曲线
  8740. })
  8741. .backgroundBlurStyle((this.isPuraWP() && this.currentSwiperIndex === 0) ||!this.isMusicBGCover
  8742. ? BlurStyle.NONE :
  8743. BlurStyle.BACKGROUND_ULTRA_THICK)
  8744. .hitTestBehavior(HitTestMode.Transparent)
  8745. .backgroundBrightness({ rate: this.isPuraWP() ? 0.1 : 0, lightUpDegree: -0.1 })
  8746. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
  8747. .onClick(() => {
  8748. if(this.isHiCar())
  8749. return
  8750. if(this.is_auto_hide_progress){
  8751. this.is_auto_hide_progress = false
  8752. }
  8753. this.startAutoHide()
  8754. })
  8755. }
  8756. @State progressValue: number = 0;
  8757. @State currentTime: string = "00:00";
  8758. @State totalTime: string = "00:00";
  8759. @State loadingVisible: Visibility = Visibility.None;
  8760. @State replayVisible: Visibility = Visibility.None;
  8761. @State slideEnable: boolean = false;
  8762. @State aspRatio: number = 0.5;
  8763. @State mContext: object | undefined = undefined;
  8764. // private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  8765. @State mFirst: boolean = true;
  8766. @State mDestroyPage: boolean = false;
  8767. @State playSpeed: number = 1;
  8768. @State oldSeconds: number = 0;
  8769. @State isSeekTo: boolean = false;
  8770. @State isCurrentTime: boolean = false;
  8771. @State videoWidth: string = '100%';
  8772. @State videoHeight: string = '100%';
  8773. @State initAspectRatio: number = 1;
  8774. @State videoAspectRatio: number = this.initAspectRatio;
  8775. @State videoUrl: string = '';
  8776. private last: number = 0;
  8777. @State videoParentAspectRatio: number = this.initAspectRatio;
  8778. private mIjkMediaPlayer = IjkMediaPlayer.getInstance();
  8779. @State CONTROL_PlayStatus: number = PlayStatus.INIT;
  8780. @State PROGRESS_MAX_VALUE: number = 100;
  8781. @State updateProgressTimer: number = 0;
  8782. @State isHide: boolean = false; //是否因此播放器的按钮,默认是进入横屏模式隐藏,点击视频的时候显示
  8783. @State name: string = '';
  8784. // @State loop: boolean = false;
  8785. @State playType: number = 0; //0:连续播放 1:单片重复播放 2:正常播放 3:随机播放
  8786. @State multiple: string = '1.0X';
  8787. xcomponentController: XComponentController = new XComponentController()
  8788. private panOptionBright: PanGestureOptions =
  8789. new PanGestureOptions({ direction: PanDirection.Up | PanDirection.Down });
  8790. private panOptionVolume: PanGestureOptions =
  8791. new PanGestureOptions({ direction: PanDirection.Vertical | PanDirection.Up | PanDirection.Down });
  8792. private panOptionSeekTo: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Horizontal });
  8793. //手势的音量控制和亮度控制
  8794. private positionX: number = PlayConstants.POSITION_X;
  8795. private positionY: number = PlayConstants.POSITION_Y;
  8796. private windowClass: window.Window = globalThis.windowClass
  8797. @State volume: number = 0.5;
  8798. @State volumeSmall: boolean = false
  8799. @State autoParseMusicName: boolean = true
  8800. @State isShowFileName: boolean = false
  8801. @State isLongNameRoLL: boolean = true//长歌名滚动
  8802. @State volumeShow: boolean = PlayConstants.VOLUME_SHOW;
  8803. @State bright: number = PlayConstants.BRIGHT;
  8804. @State brightShow: boolean = PlayConstants.BRIGHT_SHOW;
  8805. @State seekToShow: boolean = PlayConstants.BRIGHT_SHOW;
  8806. @State screenWidth: number = 0
  8807. @State screenHeight: number = 0
  8808. @State statusBarHeight: number = 0
  8809. @State isYesFull: boolean = false
  8810. private seekValue: number = 0
  8811. @State isVideoLock: boolean = false; // Whether the video playback is locked
  8812. eventHub = getContext().eventHub;
  8813. //投播组件
  8814. private avSessionController: AvSessionController = AvSessionController.getInstance(false);
  8815. private castController: avSession.AVCastController | undefined = undefined;
  8816. @State isCastPlaying: boolean = false;
  8817. @State currentTime2: number = 0;
  8818. @State currentStringTime: string = '00:00';
  8819. @State duration: number = 0;
  8820. @State isReady: boolean = false;
  8821. @State durationTime: number = 0;
  8822. @State durationStringTime: string = '00:00';
  8823. @StorageLink('isPlaying') @Watch('animationRoFun') isPlaying: boolean = false;
  8824. // @State isPlaying: boolean = false;
  8825. private castSeek: boolean = false;
  8826. private castItem: avSession.AVQueueItem | undefined = undefined;
  8827. // @State isBgPlayOpen:boolean = true //是否启用后台播放
  8828. @State rotateAngle2: number = -9
  8829. @StorageLink('imageColor') imageColor: string = 'rgba(0, 0, 2, 1.00)';
  8830. @State cover: string | undefined = '';
  8831. @State artist: string | undefined = ''
  8832. // 1.初始化controller
  8833. private lyricController: LyricController = new LyricController()
  8834. private lyricControllerXF: LyricController = new LyricController() //悬浮歌词控制器
  8835. private lyricControllerSingle: LyricController = new LyricController() //播放页单行歌词控制器
  8836. private parser = new LyricParser()
  8837. @State randomColor: string = 'rgb(0,0,0)'
  8838. @State randomShakenX: number = 0
  8839. @State randomShakenY: number = 0
  8840. @State lyricTextSize: number = 24
  8841. @State lyricContent: string = ''
  8842. @State isDebug: boolean = false
  8843. @State isHightLightCenter: boolean = true
  8844. /**
  8845. * 初始化歌词加载与展示逻辑
  8846. * @param lyricPath 歌词文件路径(支持普通.lrc和加密.lrcc)
  8847. * @param isOnLineAndToast 是否弹出Toast提示(可选)获取在线歌词为true
  8848. * @param isApi2 是否使用API2获取歌词(可选)
  8849. *
  8850. * 主要流程:
  8851. * 1. 设置歌词显示样式(字号、颜色、行距、对齐、动画等)。
  8852. * 2. 优先尝试本地读取歌词文件(支持加密和普通两种后缀)。
  8853. * 3. 若本地无歌词且满足条件(调试模式或会员且安装时间超过2天),则联网获取歌词。
  8854. * 4. 获取到歌词后,解析并设置到lyricController,并保存到本地。
  8855. * 5. 本地有歌词时,读取文件内容(自动检测编码,支持解密),解析后设置到lyricController。
  8856. * 6. 解析失败或读取失败时,清空歌词显示。
  8857. *
  8858. * 注意事项:
  8859. * - 仅会员且安装时间超过2天才可联网获取歌词(调试模式isDebug=true时跳过限制)。
  8860. * - 支持加密歌词文件(.lrcc),自动检测并解密。
  8861. * - 歌词内容解析后通过lyricController驱动UI渲染。
  8862. */
  8863. async initLyric(lyricPath: string, isOnLineAndToast?: boolean, isApi2?: boolean, isLocal?: boolean) {
  8864. if (StrUtil.isEmpty(lyricPath)) {
  8865. return
  8866. }
  8867. this.initPipLyricSetting()
  8868. this.lyricControllerSingle
  8869. .setTextSize(15)
  8870. .setCacheSize(4)
  8871. .setTextColor("#FFFFFF")
  8872. .setHighlightColor("#FFFFFF")
  8873. .setHighlightScale(1.2)
  8874. .setEmptyHint("")
  8875. .setAlignMode('center')
  8876. .setAnimationDuration(500)
  8877. .setSingleLine(true)
  8878. this.lyricContent = ''
  8879. this.lyricController
  8880. .setTextSize(this.currentLyricSize)
  8881. .setCacheSize(4)
  8882. .setTextColor("#DDDDDD")
  8883. .setHighlightColor("#FFFFFF")
  8884. .setEmptyHint("")
  8885. .setAnimationDuration(1000)
  8886. this.currentLyricAlignMode = PreferencesUtil.getNumberSync('LyricAlignMode', 1)
  8887. this.blurDegree = PreferencesUtil.getNumberSync('setBlurDegree', 3)
  8888. this.setBlurDegree(this.blurDegree, false)
  8889. this.setLyricAlignMode(this.currentLyricAlignMode, false)
  8890. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSize', 18), false)
  8891. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSize', 1.23), false)
  8892. this.lyricController.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpace', 10))
  8893. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColor', '#FFFFFF'), false)
  8894. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColor', '#FFFFFF'), false)
  8895. this.isHightLightCenter = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_SIMI, true)
  8896. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  8897. this.lyricTextWeight = PreferencesUtil.getNumberSync('lyricTextWeight', 400)
  8898. this.lyricController.setTextWeight(this.lyricTextWeight)
  8899. this.showSingleLyric = false
  8900. this.timeOffset = 0
  8901. this.lyricController.setLyric(null)
  8902. this.lyricControllerSingle.setLyric(null)
  8903. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc'
  8904. console.log("onecold lyricPath =" + lyricPath)
  8905. let neiqianLrc = ''
  8906. let lyContent = this.currentSong?.lyricContent
  8907. if(lyContent&&StrUtil.isNotEmpty(lyContent)){//取数据库里面的歌词lyContent
  8908. neiqianLrc = lyContent
  8909. }
  8910. if (StrUtil.isNotEmpty(neiqianLrc) && !isOnLineAndToast&&!isLocal&&!isLocal) {
  8911. console.log("onecold 找到内嵌歌词 neiqianLrc =" + neiqianLrc)
  8912. //赋值给this.lyricContent,播控中心才可以显示歌词
  8913. this.lyricContent = neiqianLrc
  8914. // 将文件内容按行分割成字符串数组
  8915. let lines = neiqianLrc.split('\n').map(line => line.trim());
  8916. // 3.解析歌词
  8917. let lyric = this.parser.parse(lines);
  8918. // 4.设置歌词
  8919. this.lyricController.setLyric(lyric);
  8920. this.lyricControllerXF.setLyric(lyric)
  8921. this.lyricControllerSingle.setLyric(lyric)
  8922. return
  8923. }
  8924. if (isOnLineAndToast || ((!FileUtil.accessSync(lyricPath) && !FileUtil.accessSync(jiaMilyricPath))
  8925. && !Utility.isVideoByExtension(this.videoUrl))) {
  8926. if (this.currentSong !== undefined) {
  8927. // ToastUtil.showShort('正在为你搜索在线歌词!')
  8928. //判断是不是赞助会员,是会员的话才开启歌词功能
  8929. // if (!this.isDebug) {
  8930. // if (!Utility.isNoble()) {
  8931. // LogUtil.debug("onecold 不是赞助会员")
  8932. // return
  8933. // }
  8934. // if(!Utility.isPassInstallTime(33)){
  8935. // LogUtil.debug("onecold not pass time")
  8936. // // LogUtil.debug("onecold 用户安装app没超过12天" )
  8937. // return
  8938. // }
  8939. // }
  8940. let artist = this.currentSong?.artist
  8941. if (artist === undefined) {
  8942. artist = ''
  8943. }
  8944. if (isApi2 === undefined) {
  8945. isApi2 = false
  8946. }
  8947. NetAxiosUtil.getLyric(this.name, artist, isApi2).then((res) => {
  8948. // LogUtil.debug("onecold res =" + res)
  8949. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  8950. if (StrUtil.isNotEmpty(res)) {
  8951. this.lyricContent = res
  8952. let lines = res.split('\n').map(line => line.trim());
  8953. // 3.解析歌词
  8954. let lyric = this.parser.parse(lines);
  8955. // 4.设置歌词
  8956. this.lyricController.setLyric(lyric);
  8957. this.lyricControllerXF.setLyric(lyric)
  8958. this.lyricControllerSingle.setLyric(lyric)
  8959. this.showSingleLyric = true
  8960. // 4.保存歌词文件lyric到本地
  8961. //2025年8月28日歌词不再加密下载
  8962. this.saveDataToFile(res, lyricPath, false)
  8963. } else {
  8964. this.lyricController.setLyric(null)
  8965. this.lyricControllerXF.setLyric(null)
  8966. this.lyricControllerSingle.setLyric(null)
  8967. if (isOnLineAndToast) {
  8968. ToastUtil.showShort('未获取到歌词!')
  8969. }
  8970. }
  8971. } else {
  8972. this.lyricController.setLyric(null)
  8973. this.lyricControllerXF.setLyric(null)
  8974. this.lyricControllerSingle.setLyric(null)
  8975. if (isOnLineAndToast) {
  8976. ToastUtil.showShort('未获取到歌词!')
  8977. }
  8978. }
  8979. })
  8980. } else {
  8981. this.lyricController.setLyric(null)
  8982. this.lyricControllerXF.setLyric(null)
  8983. this.lyricControllerSingle.setLyric(null)
  8984. if (isOnLineAndToast) {
  8985. ToastUtil.showShort('未获取到歌词!')
  8986. }
  8987. }
  8988. return
  8989. }
  8990. try {
  8991. let isJiaMi = false;
  8992. let realLyricPath = lyricPath
  8993. if (FileUtil.accessSync(jiaMilyricPath)) {
  8994. isJiaMi = true
  8995. realLyricPath = jiaMilyricPath
  8996. console.info("onecold 找到加密本地歌词 ");
  8997. } else {
  8998. isJiaMi = false
  8999. realLyricPath = lyricPath
  9000. console.info("onecold 找到本地歌词 ");
  9001. }
  9002. // 3.读取文件内容并指定编码为 UTF-8
  9003. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  9004. const stat = await fileIo.stat(file.fd);
  9005. const arrayBuffer = new ArrayBuffer(stat.size);
  9006. fs.read(file.fd, arrayBuffer)
  9007. .then((readLen: number) => {
  9008. console.info("read file data succeed");
  9009. // let buf = buffer.from(arrayBuffer, 0, readLen);
  9010. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  9011. // 检查 buf 是否为空
  9012. if (buf.length === 0) {
  9013. throw new Error("Buffer is empty after reading the file");
  9014. }
  9015. try {
  9016. // 检测文件编码
  9017. // let detectedEncoding = chardet.detect(buf);
  9018. // console.info("onecoldT Detected encoding: " + detectedEncoding);
  9019. let detectedEncoding = this.detect(arrayBuffer)
  9020. console.info("onecoldT Detected encoding: " + detectedEncoding);
  9021. // 使用检测到的编码解码,解决中文乱码问题
  9022. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  9023. console.info("onecoldT Detected textDecoder: " + textDecoder);
  9024. let fileContent = textDecoder.decode(buf);
  9025. console.info(`onecoldT The content of file1: ${fileContent}`);
  9026. //解密
  9027. if (isJiaMi) {
  9028. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent))
  9029. }
  9030. console.info(`onecold The content of file2: ${fileContent}`);
  9031. this.lyricContent = fileContent
  9032. if(isLocal){//编辑标签选择本地歌词需要赋值给this.lyricConStr
  9033. this.lyricConStr = fileContent
  9034. }
  9035. // 将文件内容按行分割成字符串数组
  9036. let lines = fileContent.split('\n').map(line => line.trim());
  9037. console.info(`onecold The content of file: ${fileContent}`);
  9038. // 3.解析歌词
  9039. let lyric = this.parser.parse(lines);
  9040. // 4.设置歌词
  9041. this.lyricController.setLyric(lyric);
  9042. this.lyricControllerXF.setLyric(lyric)
  9043. this.lyricControllerSingle.setLyric(lyric)
  9044. this.showSingleLyric = true
  9045. console.info(`The content of file: ${fileContent}`);
  9046. } catch (chardetError) {
  9047. console.error("chardet.detect failed with error: " + chardetError.message);
  9048. this.lyricController.setLyric(null);
  9049. this.lyricControllerXF.setLyric(null)
  9050. this.lyricControllerSingle.setLyric(null)
  9051. }
  9052. })
  9053. .catch((err: BusinessError) => {
  9054. this.lyricController.setLyric(null)
  9055. this.lyricControllerXF.setLyric(null)
  9056. this.lyricControllerSingle.setLyric(null)
  9057. console.error("read file data failed with error message: " + err.message + ", error code: " + err.code);
  9058. })
  9059. .catch((err: Error) => {
  9060. this.lyricController.setLyric(null)
  9061. this.lyricControllerXF.setLyric(null)
  9062. this.lyricControllerSingle.setLyric(null)
  9063. console.error("read file 2 data failed with error message: " + err.message);
  9064. })
  9065. .finally(() => {
  9066. fs.closeSync(file);
  9067. });
  9068. } catch (error) {
  9069. this.lyricController.setLyric(null)
  9070. this.lyricControllerSingle.setLyric(null)
  9071. this.lyricControllerXF.setLyric(null)
  9072. Logger.error(TAG, 'init Lyric failed with err: ' + JSON.stringify(error));
  9073. }
  9074. }
  9075. detect(data: ArrayBuffer): string {
  9076. //创建检测对象
  9077. let detector: UniversalDetector = new UniversalDetector();
  9078. // 传入检测数据并实时判断编码格式
  9079. detector.handleData(data, 0, data.byteLength);
  9080. // 标记检测数据 读取结束
  9081. detector.dataEnd();
  9082. // 获取检测结果
  9083. let detected: string = detector.getDetectedCharset();
  9084. // 释放资源
  9085. detector.reset();
  9086. return detected;
  9087. }
  9088. //初始化悬浮歌词的自定义设置
  9089. initPipLyricSetting() {
  9090. this.lyricControllerXF
  9091. .setTextSize(this.currentLyricSize)
  9092. .setCacheSize(4)
  9093. .setTextColor("#DDDDDD")
  9094. .setHighlightColor("#FFFFFF")// .setLineSpace(18)
  9095. .setEmptyHint("")
  9096. .setAnimationDuration(1000)
  9097. this.currentLyricAlignModePip = PreferencesUtil.getNumberSync('LyricAlignModePip', 0)
  9098. this.blurDegreePip = PreferencesUtil.getNumberSync('setBlurDegreePip', 3)
  9099. this.setBlurDegree(this.blurDegreePip, true)
  9100. this.setLyricAlignMode(this.currentLyricAlignModePip, true)
  9101. this.setLyricTextSize(PreferencesUtil.getNumberSync('LyricTextSizePip', 18), true)
  9102. this.setHighLyricTextSize(PreferencesUtil.getNumberSync('HighLyricTextSizePip', 1.23), true)
  9103. this.lyricControllerXF.setLineSpace(PreferencesUtil.getNumberSync('LyricLineSpacePip', 10))
  9104. this.changeLyricColor(PreferencesUtil.getStringSync('LyricColorPip', '#FFFFFF'), true)
  9105. this.changeLyricHightLightColor(PreferencesUtil.getStringSync('LyricHighLightColorPip', '#FFFFFF'), true)
  9106. this.lyricControllerXF.setHightLightCenter(true)
  9107. this.lyricTextWeightPip = PreferencesUtil.getNumberSync('lyricTextWeightPip', 400)
  9108. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  9109. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  9110. this.pipBgIndex = PreferencesUtil.getNumberSync('pipBgIndex', 0)
  9111. if (this.pipBgIndex === 0) {
  9112. if (this.cover) {
  9113. this.pipBg = this.cover
  9114. } else {
  9115. this.pipBg = this.imageColor
  9116. }
  9117. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  9118. }
  9119. }
  9120. //根据item返回歌词内容
  9121. async getLyricContent(item: VideoItem): Promise<string> {
  9122. let neiqianLrc = ''
  9123. let lyContent = item?.lyricContent
  9124. if(lyContent&&StrUtil.isNotEmpty(lyContent)){
  9125. neiqianLrc = lyContent
  9126. return neiqianLrc
  9127. }
  9128. try {
  9129. //取数据库里面的歌词lyContent
  9130. const lyricContent = await this.table.getLyricContentByFilePath(item.filePath);
  9131. if (lyricContent&&StrUtil.isNotEmpty(lyricContent)) {
  9132. console.log("onecold Lyrics:", lyricContent);
  9133. neiqianLrc = lyricContent
  9134. return neiqianLrc
  9135. }
  9136. } catch (error) {
  9137. console.error("Error fetching lyrics:", error);
  9138. }
  9139. try {
  9140. let filePath = item.filePath;
  9141. let lyricPath = filePath.substring(0, filePath.lastIndexOf('.')) + '.lrc';
  9142. let jiaMilyricPath = lyricPath.substring(0, lyricPath.lastIndexOf('.')) + '.lrcc';
  9143. let isJiaMi = false;
  9144. let realLyricPath = lyricPath;
  9145. if (FileUtil.accessSync(jiaMilyricPath)) {
  9146. isJiaMi = true;
  9147. realLyricPath = jiaMilyricPath;
  9148. console.info("onecold 找到加密本地歌词");
  9149. } else {
  9150. console.info("onecold 找到本地歌词");
  9151. }
  9152. let file = fs.openSync(realLyricPath, fs.OpenMode.READ_ONLY);
  9153. const stat = await fileIo.stat(file.fd);
  9154. const arrayBuffer = new ArrayBuffer(stat.size);
  9155. const readLen = await fs.read(file.fd, arrayBuffer);
  9156. console.info("read file data succeed");
  9157. let buf = new Uint8Array(arrayBuffer, 0, readLen);
  9158. if (buf.length === 0) {
  9159. throw new Error("Buffer is empty after reading the file");
  9160. }
  9161. // let detectedEncoding = chardet.detect(buf);
  9162. let detectedEncoding = this.detect(arrayBuffer)
  9163. console.info("Detected encoding: " + detectedEncoding);
  9164. let textDecoder = new util.TextDecoder(detectedEncoding || 'utf-8');
  9165. let fileContent = textDecoder.decode(buf);
  9166. console.info(`onecold The content of file1: ${fileContent}`);
  9167. if (isJiaMi) {
  9168. fileContent = StrUtil.unit8ArrayToStr(Base64Util.decodeSync(fileContent));
  9169. }
  9170. console.info(`onecold The content of file2: ${fileContent}`);
  9171. fs.closeSync(file);
  9172. return fileContent;
  9173. } catch (error) {
  9174. console.error('init Lyric failed with err: ' + JSON.stringify(error));
  9175. return '';
  9176. }
  9177. }
  9178. async saveDataToFile(content: string, filePath: string, isJiaMi?: boolean) {
  9179. if (StrUtil.isEmpty(filePath)) {
  9180. return
  9181. }
  9182. try {
  9183. //将content进行加密
  9184. // let jiaMilyricPath = filePath.substring(0,filePath.lastIndexOf('.'))+'.lrcc'
  9185. let lyricContent = ''
  9186. if (isJiaMi) {
  9187. lyricContent = Base64Util.encodeToStrSync(StrUtil.strToUint8Array(content))
  9188. } else {
  9189. lyricContent = content
  9190. }
  9191. const file = await fileIo.open(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
  9192. // 清空文件内容
  9193. await fileIo.truncate(file.fd, 0);
  9194. await fileIo.write(file.fd, lyricContent);
  9195. await fileIo.close(file);
  9196. console.log('onecold lyric file Data saved successfully.');
  9197. } catch (error) {
  9198. console.error('onecold lyric file Failed to save data:', error);
  9199. }
  9200. }
  9201. // 定义开始旋转的方法
  9202. // 定时器用于一百毫秒执行一次旋转角度
  9203. @State timer: number = 0
  9204. @State rotateAngle: number = 0
  9205. //封面旋转动画
  9206. animationRoFun() {
  9207. if (this.isPlaying && !this.isCoverRectangle) {
  9208. this.timer = setInterval(() => {
  9209. this.rotateAngle += 1
  9210. }, 100)
  9211. this.startRotation()
  9212. } else {
  9213. clearInterval(this.timer)
  9214. this.stopRotation()
  9215. }
  9216. }
  9217. // 定义开始旋转的方法
  9218. startRotation() {
  9219. if (this.isPlaying) {
  9220. animateTo({
  9221. duration: 777,
  9222. iterations: 1,
  9223. curve: Curve.Linear
  9224. }, () => {
  9225. this.rotateAngle2 = -9
  9226. })
  9227. }
  9228. }
  9229. // 回调,暂停和播放按钮回调,下一首和上一首
  9230. playChange() {
  9231. // if(this.isCoverRectangle){
  9232. // return
  9233. // }
  9234. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  9235. this.setIsPlaying(true)
  9236. this.animationState = AnimationStatus.Running
  9237. } else {
  9238. this.setIsPlaying(false)
  9239. this.animationState = AnimationStatus.Paused
  9240. }
  9241. AppStorage.setOrCreate('animationState', this.animationState);
  9242. }
  9243. // 定义停止旋转的方法
  9244. stopRotation() {
  9245. if (this.isCoverRectangle) {
  9246. this.rotateAngle = 0
  9247. } else {
  9248. //唱针以左上角为点选择逆时针40度
  9249. animateTo({
  9250. duration: 1000,
  9251. curve: Curve.Linear,
  9252. iterations: 1,
  9253. }, () => {
  9254. this.rotateAngle2 = -45;
  9255. });
  9256. }
  9257. }
  9258. @Builder
  9259. private LyricsTopItem() {
  9260. Row() {
  9261. Stack() {
  9262. Image(this.cover)
  9263. .height(58)
  9264. .width(58)
  9265. .alt($r('app.media.alt'))
  9266. .borderRadius(8)
  9267. .clickEffect({ level: ClickEffectLevel.HEAVY })
  9268. .margin({ left: this.currentLyricAlignMode === 0 ? 28 : -15 })
  9269. .shadow({
  9270. radius: 22,
  9271. type: ShadowType.BLUR,
  9272. color: 'on_primary'
  9273. })
  9274. }
  9275. .width('18%')
  9276. Column() {
  9277. Column() {
  9278. Text(this.name)
  9279. .fontSize(16)
  9280. .maxLines(1)
  9281. .fontWeight(FontWeight.Bolder)
  9282. .fontColor(this.currentLyricColor)
  9283. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  9284. Row() {
  9285. Text(this.currentSong?.artist !== undefined ? this.currentSong?.artist : '')
  9286. .fontSize(13)
  9287. .fontWeight(FontWeight.Bold)
  9288. .padding({ top: 8 })
  9289. .fontColor(this.currentLyricColor)
  9290. .margin({ left: this.currentLyricAlignMode === 0 ? 24 : 0 })
  9291. Blank()
  9292. }
  9293. }
  9294. .height('100%')
  9295. .width('100%')
  9296. .justifyContent(FlexAlign.Center)
  9297. .alignItems(HorizontalAlign.Start)
  9298. }
  9299. .height('100%')
  9300. .width('65%')
  9301. Column() {
  9302. Image($r('app.media.lyric'))
  9303. .width(28)
  9304. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9305. .margin({ right: 30 })
  9306. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9307. .onClick(() => {
  9308. this.isLyricSetting = !this.isLyricSetting;
  9309. })
  9310. .bindSheet($$this.isLyricSetting, this.lyricSettingSheet(false), {
  9311. height: '95%',
  9312. dragBar: true,
  9313. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9314. showClose: true,
  9315. blurStyle: BlurStyle.Thin,
  9316. backgroundColor: Color.Transparent,
  9317. // title: { title: $r('app.string.lyric_setting') }
  9318. })
  9319. }
  9320. .width('18%')
  9321. }
  9322. .width('82%')
  9323. .height(58)
  9324. .justifyContent(FlexAlign.SpaceBetween)
  9325. }
  9326. //歌词显示
  9327. @Builder
  9328. PlayerLyrics() {
  9329. Column() {
  9330. Column() {
  9331. this.LyricsTopItem()
  9332. }
  9333. .height(this.isPuraWP() ? 15 : 58)
  9334. .visibility(this.currentBreakpoint !== BreakpointTypeEnum.SM ?
  9335. Visibility.None : Visibility.Visible)
  9336. .margin({ left: 6, top: this.isPuraWP() ? 5 : 38 })
  9337. .width("100%")
  9338. Column() {
  9339. LyricView2({
  9340. controller: this.lyricController,
  9341. enableSeek: true,
  9342. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  9343. seekLineColor: "#80ffffff", // 滑动定位线颜色
  9344. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  9345. onSeekAction: (position: number) => { // 滑动歌词触发seek定位回调
  9346. if (!this.isPlaying) {
  9347. console.info('onecold startPlayOrResumePlay 7527')
  9348. this.startPlayOrResumePlay()
  9349. }
  9350. else {
  9351. this.isSeekTo = true;
  9352. this.mDestroyPage = false;
  9353. this.showLoadIng();
  9354. this.seekTo(position + "");
  9355. this.isSeekTo = false;
  9356. }
  9357. return true
  9358. }
  9359. })
  9360. .width("100%")
  9361. .layoutWeight(1)
  9362. .margin({ left: this.currentLyricAlignMode === 0 ? 0 : 50, top: 2, bottom: this.isPhoneLan()||this.isHiCarKuanBianPing() ? 40 : 10 })
  9363. if (this.isPhoneLan()) {
  9364. Column() {
  9365. this.playProgressView()
  9366. // this.playCenterView()
  9367. }
  9368. .margin({ bottom: 30, right: this.currentLyricAlignMode == 0 ? 0 : 30 })
  9369. }
  9370. }
  9371. .position({
  9372. top: this.currentBreakpoint !== BreakpointTypeEnum.SM ? (this.isPhoneLan() ? 0 : 45) :
  9373. (this.isPuraWP() ? 58 : 99)
  9374. })
  9375. .justifyContent(FlexAlign.Center)
  9376. .height(this.isCoverOpacity() ? this.isPhoneLan()?'95%':'90%' : '82%')
  9377. }
  9378. }
  9379. @Builder
  9380. SingleLyricView() {
  9381. Column() {
  9382. Column() {
  9383. LyricView2({
  9384. controller: this.lyricControllerSingle,
  9385. enableSeek: false,
  9386. seekUIColor: "#ff0000", // 滑动定位的按钮和文本颜色
  9387. seekLineColor: "#80ffffff", // 滑动定位线颜色
  9388. seekUIStyle: "listItem", // 滑动定位样式(seekLine传统样式,listItem类似抖音汽水音乐样式)
  9389. })
  9390. }
  9391. .height(66)
  9392. .margin({ bottom: 20 })
  9393. }
  9394. }
  9395. //播放器的底部控制中心,上一首,暂停,下一首,播放进度条等
  9396. @Builder
  9397. BottomControl() {
  9398. Column() {
  9399. this.TopPlayProgressView()
  9400. //播放 暂停,下一首,上一首
  9401. this.playCenterView()
  9402. //播放进度条
  9403. this.BottomView()
  9404. }
  9405. .position({ bottom: this.isHiCarSmall()?50:(this.isCoverOpacity() ? 55 : 70) }) // 将 固定在底部
  9406. }
  9407. //播放控制上一首 下一首 暂停和播放
  9408. @Builder
  9409. playCenterView(){
  9410. Row() {
  9411. Button({type:ButtonType.Circle,stateEffect:true}){
  9412. //更多功能
  9413. Image($r('app.media.menu'))
  9414. .width(24)
  9415. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9416. .bindSheet($$this.isShowMoreView, this.PlayMoreSheet(), {
  9417. height: '99%',
  9418. preferType: this.currentBreakpoint!==BreakpointTypeEnum.SM?SheetType.CENTER:SheetType.BOTTOM,
  9419. dragBar: true,
  9420. showClose: true,
  9421. blurStyle: BlurStyle.Thin,
  9422. backgroundColor: Color.Transparent,
  9423. })
  9424. }
  9425. .height(45)
  9426. .width(45)
  9427. .margin({ left: 5 })
  9428. .backgroundColor(Color.Transparent)
  9429. .onClick(() => {
  9430. this.isShowMoreView = !this.isShowMoreView;
  9431. })
  9432. Button({type:ButtonType.Circle,stateEffect:true}){
  9433. Image($r('app.media.ic_previous'))
  9434. .width(33)
  9435. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9436. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9437. }
  9438. .height(45)
  9439. .width(45)
  9440. .onClick(async () => {
  9441. await this.playPrevious()
  9442. })
  9443. .backgroundColor(Color.Transparent)
  9444. Button({type:ButtonType.Circle,stateEffect:true}){
  9445. Column() {
  9446. Image(this.CONTROL_PlayStatus === PlayStatus.PLAY ?
  9447. (this.isCircleBtn?$r('app.media.hm_pause'):$r('app.media.ic_public_play'))
  9448. : (this.isCircleBtn?$r('app.media.hm_play2'):$r('app.media.ic_public_pause')))
  9449. .width(this.isPhoneLan()?45:55)
  9450. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9451. .fillColor(Color.White)
  9452. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9453. }
  9454. }
  9455. .onClick(async () => {
  9456. this.playOrPause()
  9457. })
  9458. .backgroundColor(Color.Transparent)
  9459. .layoutWeight(1)
  9460. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9461. Image($r('app.media.ic_next'))
  9462. .width(33)
  9463. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9464. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9465. }
  9466. .height(45)
  9467. .width(45)
  9468. .backgroundColor(Color.Transparent)
  9469. .onClick(async () => {
  9470. await this.playNext();
  9471. })
  9472. this.fullButton()
  9473. }
  9474. .width('95%')
  9475. .margin({ bottom:this.isCoverOpacity()?0:15 })
  9476. .justifyContent(FlexAlign.SpaceEvenly)
  9477. }
  9478. @Builder
  9479. TopPlayProgressView(){
  9480. Row() {
  9481. Column(){
  9482. Row(){
  9483. Stack(){
  9484. SymbolGlyph($r('sys.symbol.arrow_counterclockwise'))
  9485. .fontColor([Color.White])
  9486. .fontSize(21)
  9487. .effectStrategy(1)
  9488. Text(this.fastForwardSeconds)
  9489. .fontColor(Color.White)
  9490. .fontSize(10)
  9491. .fontWeight(FontWeight.Bold)
  9492. }
  9493. .margin({left:12,bottom:6})
  9494. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  9495. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9496. .onClick(()=>{
  9497. this.backForward()
  9498. })
  9499. Slider({
  9500. value: this.progressValue,
  9501. min: 0,
  9502. max: this.PROGRESS_MAX_VALUE,
  9503. step: 1,
  9504. style: SliderStyle.InSet
  9505. })
  9506. .height(20)
  9507. .blockColor('rgba(255,255,255,1)')
  9508. .trackColor('rgba(255,255,255,0.3)')
  9509. .selectedColor(Color.White)
  9510. .trackThickness(4)
  9511. .layoutWeight(1)
  9512. .showSteps(false)
  9513. .showTips(true)
  9514. .alignSelf(ItemAlign.Center)
  9515. .enabled(this.slideEnable)
  9516. .onChange((value: number, mode: SliderChangeMode) => {
  9517. // if (mode == 2) {
  9518. this.isSeekTo = true;
  9519. this.mDestroyPage = false;
  9520. this.showLoadIng();
  9521. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  9522. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  9523. this.seekTo(seekValue + "");
  9524. // this.setProgress()
  9525. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  9526. this.isSeekTo = false;
  9527. // }
  9528. })
  9529. Stack(){
  9530. SymbolGlyph($r('sys.symbol.arrow_clockwise'))
  9531. .fontColor([Color.White])
  9532. .fontSize(21)
  9533. .effectStrategy(1)
  9534. Text(this.fastForwardSeconds)
  9535. .fontColor(Color.White)
  9536. .fontSize(10)
  9537. .fontWeight(FontWeight.Bold)
  9538. }
  9539. .margin({right:10,bottom:6})
  9540. .visibility(this.isShowBackFast?Visibility.Visible:Visibility.None)
  9541. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.6 })
  9542. .onClick(()=>{
  9543. this.fastForward()
  9544. })
  9545. }
  9546. .padding({ right: 7,left:22 })
  9547. Row(){
  9548. Text(this.currentTime)
  9549. .fontSize(10)
  9550. .fontColor(Color.White)
  9551. Blank()
  9552. .layoutWeight(1)
  9553. Text(this.totalTime)
  9554. .fontSize(10)
  9555. .fontColor(Color.White)
  9556. }
  9557. .justifyContent(FlexAlign.Start)
  9558. .padding({ right: 18,left:36 })
  9559. }
  9560. }
  9561. //x5的竖屏模式需要99%
  9562. .width(this.isLandscape?'80%':'93%')
  9563. .justifyContent(FlexAlign.Center)
  9564. .margin({bottom:3})
  9565. .animation({
  9566. duration: 666,
  9567. curve: 'ease-in-out' // 可选动画曲线
  9568. })
  9569. }
  9570. //播放进度条
  9571. @Builder
  9572. BottomView(){
  9573. Row() {
  9574. Button({type:ButtonType.Circle,stateEffect:true}){
  9575. Column() {
  9576. if (this.playType === 0) {
  9577. Image($r('app.media.loop'))
  9578. .width(27)
  9579. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9580. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9581. } else if (this.playType === 1) {
  9582. Image($r('app.media.single'))
  9583. .width(27)
  9584. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9585. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9586. } else if (this.playType === 2) {
  9587. Image($r('app.media.normal_play'))
  9588. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9589. .width(27)
  9590. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9591. } else if (this.playType === 3) {
  9592. Image($r('app.media.random'))
  9593. .width(27)
  9594. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9595. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9596. }
  9597. }
  9598. }
  9599. .layoutWeight(1)
  9600. .margin({ left: 5 })
  9601. .height(45)
  9602. .width(45)
  9603. .backgroundColor(Color.Transparent)
  9604. .onClick(async () => {
  9605. this.setLoopMode()
  9606. })
  9607. if(this.currentSong){
  9608. Button({type:ButtonType.Circle,stateEffect:true}){
  9609. Column() {
  9610. Image($r('app.media.rename2'))
  9611. .width(21)
  9612. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9613. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9614. }
  9615. }
  9616. .bindSheet($$this.isShowEdit, this.editSheet(this.currentSong), {
  9617. height: '99%',
  9618. dragBar: true,
  9619. showClose: true,
  9620. preferType: SheetType.BOTTOM,
  9621. title: { title: '编辑标签' }
  9622. })
  9623. .height(45)
  9624. .width(45)
  9625. .layoutWeight(1)
  9626. .backgroundColor(Color.Transparent)
  9627. .onClick(async () => {
  9628. this.initEditFields(this.currentSong)
  9629. this.tempLyricContent = this.lyricContent
  9630. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  9631. this.lyricConStr = this.tempLyricContent
  9632. }
  9633. this.isShowEdit = !this.isShowEdit;
  9634. })
  9635. }
  9636. Button({type:ButtonType.Circle,stateEffect:true}){
  9637. Column() {
  9638. Image($r('app.media.lyric'))
  9639. .width(26)
  9640. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9641. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9642. }
  9643. }
  9644. .height(45)
  9645. .width(45)
  9646. .layoutWeight(1)
  9647. .backgroundColor(Color.Transparent)
  9648. .onClick(async () => {
  9649. this.isLyricSetting = !this.isLyricSetting;
  9650. })
  9651. //播放列表
  9652. Button({type:ButtonType.Circle,stateEffect:true}){
  9653. Image($r('app.media.hm_playlist'))
  9654. .width(24)
  9655. .fillColor(Color.White)
  9656. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9657. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9658. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  9659. height: '95%',
  9660. dragBar: true,
  9661. showClose: true,
  9662. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9663. blurStyle: BlurStyle.Thin,
  9664. backgroundColor: this.isPlayListBgGrass?Color.Transparent:$r('app.color.silvery'),
  9665. title: {
  9666. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  9667. + `(${this.songList.length}首)`
  9668. }
  9669. })
  9670. }
  9671. .layoutWeight(1)
  9672. .height(45)
  9673. .width(45)
  9674. .backgroundColor(Color.Transparent)
  9675. .onClick(() => {
  9676. this.isShowSheetView = !this.isShowSheetView;
  9677. if(this.isPlayListBgGrass){
  9678. this.isFrontWhite = true
  9679. }else{
  9680. this.isFrontWhite = false
  9681. }
  9682. this.scrollIndex()
  9683. })
  9684. }
  9685. .width(this.isLandscape?'88%':'95%')
  9686. .justifyContent(FlexAlign.SpaceAround)
  9687. .height(30)
  9688. .animation({
  9689. duration: 666,
  9690. curve: 'ease-in-out' // 可选动画曲线
  9691. })
  9692. }
  9693. @Builder
  9694. fullButton(){
  9695. Button({type:ButtonType.Circle,stateEffect:true}){
  9696. Column() {
  9697. Image($r('app.media.full_4'))
  9698. .width(25)
  9699. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  9700. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9701. }
  9702. }
  9703. .layoutWeight(1)
  9704. .backgroundColor(Color.Transparent)
  9705. .height(45)
  9706. .width(45)
  9707. .onClick(async () => {
  9708. if (this.isLandscape) {
  9709. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  9710. } else {
  9711. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  9712. }
  9713. })
  9714. }
  9715. //旧版本播放进度条
  9716. @Builder
  9717. playProgressView() {
  9718. Row() {
  9719. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9720. Column() {
  9721. if (this.playType === 0) {
  9722. Image($r('app.media.loop'))
  9723. .width($r('app.float.control_image_width'))
  9724. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9725. } else if (this.playType === 1) {
  9726. Image($r('app.media.single'))
  9727. .width($r('app.float.control_image_width'))
  9728. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9729. } else if (this.playType === 2) {
  9730. Image($r('app.media.normal_play'))
  9731. .width($r('app.float.control_image_width'))
  9732. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9733. } else if (this.playType === 3) {
  9734. Image($r('app.media.random'))
  9735. .width($r('app.float.control_image_width'))
  9736. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9737. }
  9738. }
  9739. }
  9740. .visibility(this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  9741. .animation({
  9742. duration: 666,
  9743. curve: 'ease-in-out' // 可选动画曲线
  9744. })
  9745. .backgroundColor(Color.Transparent)
  9746. .margin({ right: 10 })
  9747. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9748. .onClick(async () => {
  9749. this.setLoopMode()
  9750. })
  9751. Text(this.currentTime)
  9752. .fontSize($r('app.float.slider_font_size'))
  9753. .fontColor(Color.White)
  9754. .margin(3)
  9755. Slider({
  9756. value: this.progressValue,
  9757. min: 0,
  9758. max: this.PROGRESS_MAX_VALUE,
  9759. step: 1,
  9760. style: SliderStyle.OutSet
  9761. })
  9762. .width('600px')
  9763. .blockColor('rgba(255,255,255,1)')
  9764. .trackColor('rgba(255,255,255,0.3)')
  9765. .selectedColor(Color.White)
  9766. .trackThickness(PlayConstants.PROGRESS_TRACK_THICKNESS)
  9767. .layoutWeight(1)
  9768. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  9769. .showSteps(false)
  9770. .showTips(true)
  9771. .enabled(this.slideEnable)
  9772. .onChange((value: number, mode: SliderChangeMode) => {
  9773. // if (mode == 2) {
  9774. this.isSeekTo = true;
  9775. this.mDestroyPage = false;
  9776. this.showLoadIng();
  9777. LogUtils.getInstance().LOGI("slider-->seekValue start:" + value);
  9778. let seekValue = value * (this.mIjkMediaPlayer.getDuration() / 100);
  9779. this.seekTo(seekValue + "");
  9780. // this.setProgress()
  9781. LogUtils.getInstance().LOGI("slider-->seekValue end:" + seekValue);
  9782. this.isSeekTo = false;
  9783. // }
  9784. })
  9785. Text(this.totalTime)
  9786. .fontSize($r('app.float.slider_font_size'))
  9787. .fontColor(Color.White)
  9788. .margin(3)
  9789. .margin({ left: PlayConstants.PROGRESS_MARGIN_LEFT })
  9790. //播放列表
  9791. Button({ type: ButtonType.Circle, stateEffect: true }) {
  9792. Image($r('app.media.hm_playlist'))
  9793. .width($r('app.float.control_image_width'))
  9794. .fillColor(Color.White)
  9795. .aspectRatio(CommonConstants.ASPECT_RATIO)
  9796. .bindSheet($$this.isShowSheetView, this.PlayListSheet(), {
  9797. height: '95%',
  9798. dragBar: true,
  9799. showClose: true,
  9800. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  9801. blurStyle: BlurStyle.Thin,
  9802. backgroundColor: this.isPlayListBgGrass ? Color.Transparent : $r('app.color.silvery'),
  9803. title: {
  9804. title: Utility.resourceToString(this.context, $r('app.string.current_play_list'))
  9805. + `(${this.songList.length}首)`
  9806. }
  9807. })
  9808. }
  9809. .visibility( this.is_auto_hide_progress ? Visibility.None : Visibility.Visible)
  9810. .animation({
  9811. duration: 666,
  9812. curve: 'ease-in-out' // 可选动画曲线
  9813. })
  9814. .backgroundColor(Color.Transparent)
  9815. .margin({ right: 20, left: 10 })
  9816. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  9817. .onClick(() => {
  9818. this.isShowSheetView = !this.isShowSheetView;
  9819. if (this.isPlayListBgGrass) {
  9820. this.isFrontWhite = true
  9821. } else {
  9822. this.isFrontWhite = false
  9823. }
  9824. this.scrollIndex()
  9825. })
  9826. }
  9827. //x5的竖屏模式需要99%
  9828. .width(this.isPhonePortrait() ? '93.4%'
  9829. : this.currentHeightBreakpoint == 1 && this.currentWidthBreakpoint == 2 ? '99%' : '82%')
  9830. .height(this.isPhoneLan() ? 25 : 33)
  9831. .animation({
  9832. duration: 666,
  9833. curve: 'ease-in-out' // 可选动画曲线
  9834. })
  9835. }
  9836. isBigScreen() {
  9837. if (this.currentWidthBreakpoint == WidthBreakpoint.WIDTH_LG) {
  9838. return true
  9839. }
  9840. if (DeviceUtil.getDeviceType() === resourceManager.DeviceType.DEVICE_TYPE_PHONE
  9841. && this.currentWidthBreakpoint === WidthBreakpoint.WIDTH_SM
  9842. && this.currentHeightBreakpoint == HeightBreakpoint.HEIGHT_LG) {
  9843. return false
  9844. } else {
  9845. return true
  9846. }
  9847. return false
  9848. }
  9849. @State is_auto_hide_progress: boolean = false //手机横屏自动隐藏播放进退条,点击屏幕可以显示,倒计时4秒后又自动隐藏
  9850. @State isCoverRectangle: boolean = false
  9851. @State isCoverTop: boolean = true
  9852. // 添加控制缩放的状态变量
  9853. @State scaleValueImage: number = 1
  9854. @State scaleValueText: number = 1
  9855. @Builder
  9856. CoverInfo() {
  9857. Column() {
  9858. //如果是方形,判断是不是封面在顶部,如果不是顶部,显示musicNameInfo, 如果是圆形显示musicNameInfo
  9859. if (this.isCoverRectangle) {
  9860. if (!this.isCoverTop) {
  9861. this.musicNameInfo(false)
  9862. }
  9863. } else {
  9864. this.musicNameInfo(false)
  9865. }
  9866. Stack() {
  9867. // 唱片旋转效果
  9868. Image($r('app.media.ic_music_disc'))
  9869. .width(245)
  9870. .height(245)
  9871. .margin({ right: 20, left: 20 ,top:this.isCoverRectangle||this.isLandscape?0:43})
  9872. .aspectRatio(1)
  9873. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  9874. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  9875. .borderRadius('100%')
  9876. .align(Alignment.Center)
  9877. .clip(true)// .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
  9878. .rotate({
  9879. angle: this.rotateAngle,
  9880. centerX: "50%",
  9881. centerY: "50%",
  9882. })
  9883. .animation({
  9884. duration: 100,
  9885. curve: Curve.Linear
  9886. })
  9887. .shadow({
  9888. radius: 22,
  9889. type: ShadowType.BLUR,
  9890. color: 'on_primary'
  9891. })
  9892. Column() {
  9893. if (this.isCoverTop && this.isCoverRectangle) {
  9894. Image(this.cover)
  9895. .height(this.isHiCar()?(px2vp(this.windowHeight)*0.46):
  9896. this.isCoverOpacity()?(px2vp(this.windowHeight)*0.6):'auto')
  9897. .width(this.isHiCar()||this.isCoverOpacity()?'auto':this.isBigScreen() ? '72%' : this.isCoverTopBig ? '100%' : '88%')
  9898. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  9899. .alt($r('app.media.alt'))
  9900. .margin({ right: 8, left: 8, top: 8 })
  9901. .aspectRatio(1)
  9902. .geometryTransition('cover') // 绑定标识符
  9903. .opacity(this.opacityValueImage)
  9904. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  9905. // 设置左下角为缩放中心点
  9906. centerX: '0%',
  9907. centerY: '100%' })
  9908. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  9909. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  9910. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  9911. .clip(true)
  9912. .rotate({
  9913. x: 0,
  9914. y: 0,
  9915. z: 1,
  9916. angle: this.rotateAngle
  9917. })
  9918. .shadow({
  9919. radius: 22,
  9920. type: ShadowType.BLUR,
  9921. color: 'on_primary'
  9922. })
  9923. .onClick(() => {
  9924. })
  9925. // .visualEffect(new hdsEffect.HdsEffectBuilder()
  9926. // .shaderEffect({
  9927. // effectType: hdsEffect.EffectType.DUAL_EDGE_FLOW_LIGHT,
  9928. // animation: {
  9929. // duration: 4000,
  9930. // iterations: -1,
  9931. // autoPlay: true,
  9932. // onFinish: () => {
  9933. // console.info('Succeeded in finishing');
  9934. // }
  9935. // },
  9936. // controller: this.controller,
  9937. // params: {
  9938. // firstEdgeFlowLight: {
  9939. // startPos: 0,
  9940. // endPos: 1.0,
  9941. // color: '#1AD0F1',
  9942. // },
  9943. // secondEdgeFlowLight: {
  9944. // startPos: 0.5,
  9945. // endPos: 1.5,
  9946. // color: '#FFA4E5',
  9947. // }
  9948. // }
  9949. // })
  9950. // .buildEffect())
  9951. this.musicNameInfo(false)
  9952. } else {
  9953. Image(this.cover)
  9954. .height(this.isHiCarSmall()?(this.isHiCarKuanBianPing()?140:px2vp(this.windowHeight)*0.38):
  9955. (this.isCoverOpacity() ? (px2vp(this.windowHeight)*0.62) : this.isCoverRectangle ? 320 : 162))
  9956. .objectFit(this.isCoverRectangle ? ImageFit.Contain : ImageFit.Auto)
  9957. .alt($r('app.media.alt'))
  9958. .geometryTransition('cover') // 绑定标识符
  9959. .margin({ right: 20, left: 20,top:this.isCoverRectangle||this.isLandscape?0:43 })
  9960. .aspectRatio(1)
  9961. .opacity(this.opacityValueImage)
  9962. .scale({ x: this.scaleValueImage, y: this.scaleValueImage,
  9963. // 设置左下角为缩放中心点
  9964. centerX: '0%',
  9965. centerY: '100%' })
  9966. .visibility(this.isPuraWP() ? Visibility.None : Visibility.Visible)
  9967. .borderRadius(this.isCoverRectangle ? 20 : '100%')
  9968. .clickEffect({ level: ClickEffectLevel.MIDDLE,scale:0.8 })
  9969. .align(Alignment.Center)//
  9970. .clip(true)
  9971. .shadow({
  9972. radius: 22,
  9973. type: ShadowType.BLUR,
  9974. color: 'on_primary'
  9975. })
  9976. .rotate({
  9977. x: 0,
  9978. y: 0,
  9979. z: 1,
  9980. angle: this.rotateAngle
  9981. })
  9982. .onClick(() => {
  9983. })
  9984. }
  9985. if (this.isPhoneLan()) {
  9986. Text(this.name)
  9987. .fontSize(18)
  9988. .fontWeight(FontWeight.Bold)
  9989. .margin({ top: 13 })
  9990. .textOverflow({ overflow: TextOverflow.Ellipsis })
  9991. .maxLines(1)
  9992. .width('99%')
  9993. .textAlign(TextAlign.Center)
  9994. .fontColor(Color.White)
  9995. }
  9996. }
  9997. // 唱针以左上角为点选择逆时针40度
  9998. Image($r('app.media.ic_music_cover_hand'))
  9999. .height(130)
  10000. .margin({ bottom: 220, top: 0 })
  10001. .align(Alignment.Top)
  10002. .rotate({ angle: this.rotateAngle2, centerX: 0, centerY: 0 })
  10003. .opacity(this.isCoverOpacity() || this.isCoverRectangle ? 0 : 1)
  10004. .visibility(this.isCoverOpacity() || this.isCoverRectangle ? Visibility.None : Visibility.Visible)
  10005. Column({ space: 8 }) {
  10006. Text(this.name)
  10007. .fontSize(this.isPuraWP() ? 24 : (this.name.length >= 28 || this.isCoverOpacity() ? 18 : 22))
  10008. .fontWeight(FontWeight.Bold)
  10009. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  10010. .maxLines(1)
  10011. .width('48%')
  10012. .textAlign(TextAlign.Center)
  10013. .fontColor(Color.White)
  10014. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  10015. Text(this.artist)
  10016. .fontSize(this.isPuraWP() ? 18 : (this.isCoverOpacity() ? 12 : 15))
  10017. .fontColor(Color.White)
  10018. .fontWeight(FontWeight.Bold)
  10019. .visibility(this.isPhoneLan() ? Visibility.None : Visibility.Visible)
  10020. }
  10021. .justifyContent(FlexAlign.Start)
  10022. .zIndex(1)
  10023. .geometryTransition('name')
  10024. .visibility(this.isCoverOpacity() ? Visibility.Visible : Visibility.None)
  10025. }
  10026. .margin({
  10027. bottom: this.isCoverOpacity() || this.isCoverRectangle ?
  10028. (this.isPhonePortrait() && this.isShowSingleLineLyric ? 20 : 55) : 0,
  10029. top: this.isCoverOpacity() ? 0 : 20
  10030. })
  10031. if (this.isPhonePortrait() && this.isShowSingleLineLyric) {
  10032. this.SingleLyricView()
  10033. }
  10034. if (this.isPhoneLan()) {
  10035. Column() {
  10036. this.playCenterView()
  10037. // this.playProgressView()
  10038. }
  10039. .position({ left: 28, bottom: 38 })
  10040. } else {
  10041. this.BottomControl()
  10042. }
  10043. }
  10044. .width(CommonConstants.FULL_PERCENT)
  10045. .clip(true)
  10046. }
  10047. @Builder
  10048. private musicNameInfo(isHidden: boolean) {
  10049. Row(){
  10050. Column({ space: 8 }) {
  10051. Text(this.name)
  10052. .fontSize(this.name.length >= 28 || this.isCoverOpacity() ? 18 : 20)
  10053. .fontWeight(FontWeight.Bold)
  10054. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  10055. .maxLines(1)
  10056. .width('99%')
  10057. .textAlign(TextAlign.Start)
  10058. .fontColor(Color.White)
  10059. Text(this.artist + ' ' + this.currentSong?.album)
  10060. .fontSize(this.isCoverOpacity() ? 12 : 15)
  10061. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  10062. .fontColor(Color.White)
  10063. .textAlign(TextAlign.Start)
  10064. .visibility(StrUtil.isEmpty(this.artist)?Visibility.None:Visibility.Visible)
  10065. .width('99%')
  10066. .maxLines(1)
  10067. }
  10068. .zIndex(1)
  10069. .geometryTransition('name') // 绑定标识符
  10070. .layoutWeight(1)
  10071. .margin({ left: 15 })
  10072. Blank()
  10073. Row(){
  10074. Button({type:ButtonType.Circle,stateEffect:true}){
  10075. //添加或取消收藏
  10076. SymbolGlyph(Utility.getIsFav(this.favList,this.currentSong)?
  10077. $r('sys.symbol.heart_fill'):$r('sys.symbol.heart'))
  10078. .fontSize(22)
  10079. .fontColor([Color.White])
  10080. .alignSelf(ItemAlign.Center)
  10081. // .width(24)
  10082. .clickEffect({level:ClickEffectLevel.MIDDLE})
  10083. .aspectRatio(CommonConstants.ASPECT_RATIO)
  10084. .clickEffect({level:ClickEffectLevel.LIGHT, scale: 0.5})
  10085. .onClick(async () => {
  10086. if(this.currentSong){
  10087. this.doFav(this.currentSong)
  10088. }
  10089. })
  10090. }
  10091. .margin({ left: 15,right:3 })
  10092. .backgroundColor(Color.Transparent)
  10093. .width(45)
  10094. .height(45)
  10095. }
  10096. }
  10097. .width('90%')
  10098. .scale({ x: this.scaleValueText, y: this.scaleValueText }) // 添加缩放效果
  10099. .margin({ top: this.isCoverOpacity() ? 10 : isHidden ? 20 : 10 })
  10100. .visibility(this.isCoverOpacity() || isHidden ? Visibility.None : Visibility.Visible)
  10101. }
  10102. @Builder
  10103. private PlayTitle() {
  10104. Row() {
  10105. Row() {
  10106. Image($r('app.media.ic_back_down'))
  10107. .width($r('app.float.title_image_size'))// .aspectRatio(CommonConstants.ASPECT_RATIO)
  10108. .hitTestBehavior(HitTestMode.Transparent)
  10109. Text(this.name + ' ' + this.artist)
  10110. .fontColor(Color.White)
  10111. .fontSize($r('app.float.title_font_size'))
  10112. .textOverflow({ overflow: TextOverflow.MARQUEE })//超长滚动
  10113. .maxLines(1)
  10114. .visibility(Visibility.None)
  10115. .margin({ left: 2, right: 30 })
  10116. }
  10117. .layoutWeight(1)
  10118. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10119. .visibility(this.isHide ? Visibility.Hidden : Visibility.Visible)
  10120. .onClick(() => {
  10121. this.setShowPlayFalse()
  10122. })
  10123. Column() {
  10124. AVCastPicker({
  10125. normalColor: Color.White,
  10126. onStateChange: this.onStateVastChange
  10127. })
  10128. .width(24)
  10129. .height(24)
  10130. }
  10131. .visibility(this.isHide ? Visibility.Hidden : Visibility.None)
  10132. }
  10133. .width(PlayConstants.ROW_WIDTH)
  10134. }
  10135. @Builder
  10136. lyricSettingSheet(isPip: boolean) {
  10137. Scroll() {
  10138. this.lyricSetting(isPip)
  10139. }
  10140. .width('100%')
  10141. .height('100%')
  10142. }
  10143. @Builder
  10144. lyricSetting(isPip: boolean) {
  10145. Column() {
  10146. // 时间调节模块
  10147. if (!isPip) {
  10148. this.BuildTimeControls()
  10149. }
  10150. // 字号控制模块
  10151. this.BuildFontControls(isPip)
  10152. }
  10153. }
  10154. // 歌词时间偏移状态
  10155. @State timeOffset: number = 0.0
  10156. @State currentLyricColor: string = '#FFFFFF'
  10157. @State currentLyricColorPip: string = '#FFFFFF'
  10158. @State currentHighLightLyricColor: string = '#FF4081'
  10159. @State currentHighLightLyricColorPip: string = '#FF4081'
  10160. // 歌词字号状态
  10161. @State currentLyricSize: number = 20
  10162. @State currentLyricSizePip: number = 20
  10163. // 高亮歌词放大倍数
  10164. @State currentHightLyricSize: number = 1.2
  10165. @State currentHightLyricSizePip: number = 1.2
  10166. @State currentLyricLineSpace: number = 10
  10167. @State currentLyricLineSpacePip: number = 10
  10168. @State currentLyricAlignMode: number = 1
  10169. @State currentLyricAlignModePip: number = 1
  10170. @State blurDegree: number = 2
  10171. @State blurDegreePip: number = 2
  10172. @State isShowSelectColor: boolean = false
  10173. @State isShowHLSelectColor: boolean = false
  10174. @State isShowPipBgSelectColor: boolean = false
  10175. @State pipLyWidth: number = 330
  10176. @State pipLyHeight: number = 120
  10177. // 构建颜色选择器
  10178. @Builder
  10179. SelectColor(isHighColor: boolean, isPip: boolean, isBGPip?: boolean) {
  10180. Row({ space: 10 }) {
  10181. HSBColorPicker({
  10182. color: '#FFFFFF',
  10183. radius: 8,
  10184. layout: HSBColorPickerLayout.COLUMN,
  10185. predefine: ['#8b27f4', '#73f9fc', '#fffe55', '#f5cee3', '#eb4827', '#e93bf4', '#3e68f4', '#c5e6d3', '#e4e4e4',
  10186. '#fa7105'],
  10187. onChange: (value: string) => isHighColor ? this.changeLyricHightLightColor(value, isPip) :
  10188. this.changeLyricColor(value, isPip, isBGPip)
  10189. })
  10190. .height(250)
  10191. .layoutWeight(1)
  10192. .padding(25)
  10193. }
  10194. .width('66%')
  10195. }
  10196. @State isOpenPip: boolean = false
  10197. @State pipBgIndex: number = 0
  10198. // 构建字号控制器
  10199. @Builder
  10200. BuildFontControls(isPip: boolean) {
  10201. Column() {
  10202. if (isPip) {
  10203. Column() {
  10204. Row() {
  10205. Text('悬浮歌词')
  10206. .margin({ left: 18 })
  10207. .fontSize(15)
  10208. .fontColor(Color.White)
  10209. .fontWeight(480)
  10210. .layoutWeight(1)
  10211. Toggle({ type: ToggleType.Switch, isOn: this.isOpenPip })
  10212. .selectedColor(this.themeColor)
  10213. .switchPointColor(Color.White)
  10214. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10215. .margin({ right: 18 })
  10216. .onChange((checked: boolean) => {
  10217. this.isOpenPip = checked;
  10218. if (this.isOpenPip) {
  10219. this.startPip()
  10220. } else {
  10221. this.stopPip()
  10222. }
  10223. PreferencesUtil.put('isOpenPip', this.isOpenPip)
  10224. })
  10225. .width(50)
  10226. .height(30);
  10227. }
  10228. .height(55)
  10229. }
  10230. .backgroundColor(Color.Transparent)
  10231. .borderRadius(15)
  10232. .margin({
  10233. left: 30,
  10234. right: 30,
  10235. top: 0,
  10236. bottom: 20
  10237. })
  10238. .padding(0)
  10239. .border({
  10240. color: Color.White,
  10241. width: 1.8
  10242. })
  10243. }else{
  10244. Column() {
  10245. Row() {
  10246. Text('单行歌词')
  10247. .margin({ left: 18 })
  10248. .fontSize(15)
  10249. .fontColor(Color.White)
  10250. .fontWeight(480)
  10251. .layoutWeight(1)
  10252. Toggle({ type: ToggleType.Switch, isOn: this.isShowSingleLineLyric })
  10253. .selectedColor(this.themeColor)
  10254. .switchPointColor(Color.White)
  10255. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10256. .margin({ right: 18 })
  10257. .onChange((checked: boolean) => {
  10258. this.isShowSingleLineLyric = checked;
  10259. PreferencesUtil.put(SettingPage.IS_SHOW_SLLYRIC, this.isShowSingleLineLyric)
  10260. })
  10261. .width(50)
  10262. .height(30);
  10263. }
  10264. .height(55)
  10265. }
  10266. .backgroundColor(Color.Transparent)
  10267. .borderRadius(15)
  10268. .margin({
  10269. left: 30,
  10270. right: 30,
  10271. top: 10,
  10272. bottom: 10
  10273. })
  10274. .padding(0)
  10275. .border({
  10276. color: Color.White,
  10277. width: 1.8
  10278. })
  10279. }
  10280. Row() {
  10281. Text(`歌词居中:`)
  10282. .fontSize(14)
  10283. .fontColor(Color.White)
  10284. .margin({ left: 2 })
  10285. Row() {
  10286. ForEach(['居中', '居左'], (size: string, index: number) => {
  10287. Button(size)
  10288. .width(60)
  10289. .height(28)
  10290. .fontSize(12)
  10291. .fontColor('#FFFFFF')
  10292. .backgroundColor((!isPip && this.currentLyricAlignMode === index) ||
  10293. (isPip && this.currentLyricAlignModePip === index) ? this.themeColor : Color.Transparent)
  10294. .border({
  10295. color: (!isPip && this.currentLyricAlignMode === index) ||
  10296. (isPip && this.currentLyricAlignModePip === index) ?
  10297. '#007DFF' : '#DDDDDD',
  10298. width: 1.8
  10299. })
  10300. .onClick(() => {
  10301. this.setLyricAlignMode(index, isPip)
  10302. })
  10303. .margin({ left: 10, right: 8 })
  10304. })
  10305. }
  10306. .width('76%')
  10307. Blank()
  10308. }
  10309. .margin({
  10310. top: 10,
  10311. bottom: 10,
  10312. right: 20,
  10313. left: 20
  10314. })
  10315. if (isPip) {
  10316. Row() {
  10317. Text(`悬浮背景:`)
  10318. .fontSize(14)
  10319. .fontColor(Color.White)
  10320. Select([
  10321. { value: CommonConstants.PIP_LYRIC_BG[0] },
  10322. { value: CommonConstants.PIP_LYRIC_BG[1] }])
  10323. .font({ size: 13, weight: FontWeight.Medium })
  10324. .fontColor(Color.White)
  10325. .margin({ left: 10 })
  10326. .selected(this.pipBgIndex)
  10327. .value(CommonConstants.PIP_LYRIC_BG[this.pipBgIndex])
  10328. .onSelect(async (_index: number, text?: string | undefined) => {
  10329. this.pipBgIndex = _index
  10330. PreferencesUtil.put('pipBgIndex', this.pipBgIndex)
  10331. if (this.pipBgIndex === 0) {
  10332. if (this.cover) {
  10333. this.pipBg = this.cover
  10334. } else {
  10335. this.pipBg = this.imageColor
  10336. }
  10337. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  10338. } else {
  10339. this.pipBg = PreferencesUtil.getStringSync('BGColorPip', '#FFFF54')
  10340. }
  10341. })
  10342. Column() {
  10343. }
  10344. .backgroundColor(this.pipBg)
  10345. .margin({ left: 10, right: 10 })
  10346. .borderRadius(20)
  10347. .height(28)
  10348. .width(28)
  10349. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10350. Row() {
  10351. SymbolGlyph($r('sys.symbol.paintbrush'))
  10352. .fontColor([Color.White])
  10353. .effectStrategy(1)
  10354. Text(`选择颜色`)
  10355. .fontSize(13)
  10356. .margin({ left: 10 })
  10357. .fontColor(Color.White)
  10358. }
  10359. }
  10360. .visibility(this.pipBgIndex === 1 ? Visibility.Visible : Visibility.None)
  10361. .backgroundColor(Color.Transparent)
  10362. .border({
  10363. color: '#FFFFFF',
  10364. radius: 20,
  10365. width: 1.8
  10366. })
  10367. .height(36)
  10368. .width(110)
  10369. .onClick(() => {
  10370. this.isShowPipBgSelectColor = !this.isShowPipBgSelectColor
  10371. })
  10372. .bindPopup(this.isShowPipBgSelectColor, {
  10373. builder: this.SelectColor(false, isPip, true),
  10374. placement: Placement.Top,
  10375. mask: { color: '#33000000' },
  10376. enableArrow: false, //是否显示箭头
  10377. showInSubWindow: false,
  10378. onStateChange: (e) => {
  10379. if (!e.isVisible) {
  10380. this.isShowPipBgSelectColor = false
  10381. }
  10382. }
  10383. })
  10384. }
  10385. .width('76%')
  10386. .margin({ bottom: 5, right: 45, left: 20 })
  10387. }
  10388. if (!isPip) {
  10389. Row() {
  10390. Text(`高亮居中:`)
  10391. .fontSize(14)
  10392. .fontColor(Color.White)
  10393. Column() {
  10394. Toggle({ type: ToggleType.Switch, isOn: this.isHightLightCenter })
  10395. .selectedColor(this.themeColor)
  10396. .switchPointColor(Color.White)
  10397. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  10398. .onChange((checked: boolean) => {
  10399. this.isHightLightCenter = checked;
  10400. PreferencesUtil.put(SettingPage.IS_SHOW_SIMI, this.isHightLightCenter)
  10401. this.lyricController.setHightLightCenter(this.isHightLightCenter)
  10402. })
  10403. .width(50)
  10404. .height(30)
  10405. .alignSelf(ItemAlign.Start)
  10406. .margin({ left: 12 })
  10407. Blank()
  10408. }
  10409. .width('76%')
  10410. }
  10411. .margin({
  10412. left: 20,
  10413. right: 15,
  10414. top: 10,
  10415. bottom: 10
  10416. })
  10417. }
  10418. Row() {
  10419. Text(`歌词颜色:`)
  10420. .fontSize(14)
  10421. .fontColor(Color.White)
  10422. Text(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  10423. .fontSize(15)
  10424. .fontColor(Color.White)
  10425. .margin({ left: 12, right: 12 })
  10426. Column() {
  10427. }
  10428. .backgroundColor(isPip ? this.currentLyricColorPip : this.currentLyricColor)
  10429. .margin({ right: 12 })
  10430. .borderRadius(20)
  10431. .height(28)
  10432. .width(28)
  10433. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10434. Row() {
  10435. SymbolGlyph($r('sys.symbol.paintbrush'))
  10436. .fontColor([Color.White])
  10437. .effectStrategy(1)
  10438. Text(`选择颜色`)
  10439. .fontSize(13)
  10440. .margin({ left: 10 })
  10441. .fontColor(Color.White)
  10442. }
  10443. }
  10444. .backgroundColor(Color.Transparent)
  10445. .border({
  10446. color: '#FFFFFF',
  10447. radius: 20,
  10448. width: 1.8
  10449. })
  10450. .height(36)
  10451. .width(110)
  10452. .onClick(() => {
  10453. this.isShowSelectColor = !this.isShowSelectColor
  10454. })
  10455. .bindPopup(this.isShowSelectColor, {
  10456. builder: this.SelectColor(false, isPip),
  10457. placement: Placement.Top,
  10458. mask: { color: '#33000000' },
  10459. enableArrow: false, //是否显示箭头
  10460. showInSubWindow: false,
  10461. onStateChange: (e) => {
  10462. if (!e.isVisible) {
  10463. this.isShowSelectColor = false
  10464. }
  10465. }
  10466. })
  10467. }
  10468. .width('76%')
  10469. .margin({
  10470. top: 10,
  10471. bottom: 10,
  10472. right: 45,
  10473. left: 20
  10474. })
  10475. Row() {
  10476. Text(`高亮颜色:`)
  10477. .fontSize(14)
  10478. .fontColor(Color.White)
  10479. Text(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  10480. .fontSize(15)
  10481. .fontColor(Color.White)
  10482. .margin({ left: 12, right: 12 })
  10483. Column() {
  10484. }
  10485. .backgroundColor(isPip ? this.currentHighLightLyricColorPip : this.currentHighLightLyricColor)
  10486. .margin({ right: 12 })
  10487. .borderRadius(20)
  10488. .height(28)
  10489. .width(28)
  10490. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10491. Row() {
  10492. SymbolGlyph($r('sys.symbol.paintbrush'))
  10493. .fontColor([Color.White])
  10494. .effectStrategy(1)
  10495. Text(`选择颜色`)
  10496. .fontSize(13)
  10497. .margin({ left: 10 })
  10498. .fontColor(Color.White)
  10499. }
  10500. }
  10501. .backgroundColor(Color.Transparent)
  10502. .border({
  10503. color: '#FFFFFF',
  10504. radius: 20,
  10505. width: 1.8
  10506. })
  10507. .height(36)
  10508. .width(110)
  10509. .onClick(() => {
  10510. this.isShowHLSelectColor = !this.isShowHLSelectColor
  10511. })
  10512. .bindPopup(this.isShowHLSelectColor, {
  10513. builder: this.SelectColor(true, isPip),
  10514. placement: Placement.Top,
  10515. mask: { color: '#33000000' },
  10516. enableArrow: false, //是否显示箭头
  10517. showInSubWindow: false,
  10518. onStateChange: (e) => {
  10519. if (!e.isVisible) {
  10520. this.isShowHLSelectColor = false
  10521. }
  10522. }
  10523. })
  10524. }
  10525. .width('76%')
  10526. .margin({
  10527. top: 10,
  10528. bottom: 10,
  10529. right: 45,
  10530. left: 20
  10531. })
  10532. if (isPip) {
  10533. Row() {
  10534. Text(`显示宽度:`)
  10535. .fontSize(14)
  10536. .fontColor(Color.White)
  10537. Slider({
  10538. value: this.pipLyWidth,
  10539. min: 10,
  10540. max: 800,
  10541. step: 1,
  10542. style: SliderStyle.OutSet
  10543. })
  10544. .blockColor(this.themeColor)
  10545. .trackColor($r('app.color.speed_text_color'))
  10546. .selectedColor(Color.White)
  10547. .trackThickness(6)
  10548. .onChange((value: number) => {
  10549. this.pipLyWidth = value
  10550. if (this.pipController) {
  10551. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  10552. PreferencesUtil.putSync('pipLyWidth', this.pipLyWidth)
  10553. }
  10554. })
  10555. .width('76%')
  10556. }
  10557. .margin({
  10558. left: 20,
  10559. right: 15,
  10560. top: 5,
  10561. bottom: 5
  10562. })
  10563. Row() {
  10564. Text(`显示高度:`)
  10565. .fontSize(14)
  10566. .fontColor(Color.White)
  10567. Slider({
  10568. value: this.pipLyHeight,
  10569. min: 10,
  10570. max: 1000,
  10571. step: 1,
  10572. style: SliderStyle.OutSet
  10573. })
  10574. .blockColor(this.themeColor)
  10575. .trackColor($r('app.color.speed_text_color'))
  10576. .selectedColor(Color.White)
  10577. .trackThickness(6)
  10578. .onChange((value: number) => {
  10579. this.pipLyHeight = value
  10580. if (this.pipController) {
  10581. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  10582. PreferencesUtil.putSync('pipLyHeight', this.pipLyHeight)
  10583. }
  10584. })
  10585. .width('76%')
  10586. }
  10587. .margin({
  10588. left: 20,
  10589. right: 15,
  10590. top: 5,
  10591. bottom: 5
  10592. })
  10593. }
  10594. Row() {
  10595. Text(`歌词字号:`)
  10596. .fontSize(14)
  10597. .fontColor(Color.White)
  10598. Slider({
  10599. value: isPip ? this.currentLyricSizePip : this.currentLyricSize,
  10600. min: 12,
  10601. max: 30,
  10602. step: 0.1,
  10603. style: SliderStyle.OutSet
  10604. })
  10605. .blockColor(this.themeColor)
  10606. .trackColor($r('app.color.speed_text_color'))
  10607. .selectedColor(Color.White)
  10608. .trackThickness(6)
  10609. .onChange((value: number) => {
  10610. this.setLyricTextSize(value, isPip)
  10611. })
  10612. .width('76%')
  10613. }
  10614. .margin({
  10615. left: 20,
  10616. right: 15,
  10617. top: 5,
  10618. bottom: 5
  10619. })
  10620. Row() {
  10621. Text(`高亮倍数:`)
  10622. .fontSize(14)
  10623. .fontColor(Color.White)
  10624. Slider({
  10625. value: isPip ? this.currentHightLyricSizePip : this.currentHightLyricSize,
  10626. min: 1,
  10627. max: 2,
  10628. step: 0.1,
  10629. style: SliderStyle.OutSet
  10630. })
  10631. .blockColor(this.themeColor)
  10632. .trackColor($r('app.color.speed_text_color'))
  10633. .selectedColor(Color.White)
  10634. .trackThickness(6)
  10635. .onChange((value: number) => {
  10636. this.setHighLyricTextSize(value, isPip)
  10637. })
  10638. .width('76%')
  10639. }
  10640. .margin({
  10641. left: 20,
  10642. right: 15,
  10643. top: 5,
  10644. bottom: 5
  10645. })
  10646. Row() {
  10647. Text(`歌词间隙:`)
  10648. .fontSize(14)
  10649. .fontColor(Color.White)
  10650. Slider({
  10651. value: isPip ? this.currentLyricLineSpacePip : this.currentLyricLineSpace,
  10652. min: 0,
  10653. max: 100,
  10654. step: 1,
  10655. style: SliderStyle.OutSet
  10656. })
  10657. .blockColor(this.themeColor)
  10658. .trackColor($r('app.color.speed_text_color'))
  10659. .selectedColor(Color.White)
  10660. .trackThickness(6)
  10661. .onChange((value: number) => {
  10662. this.setLyricLineSpace(value, isPip)
  10663. })
  10664. .width('76%')
  10665. }
  10666. .margin({
  10667. left: 20,
  10668. right: 15,
  10669. top: 5,
  10670. bottom: 5
  10671. })
  10672. //取值间隔为100,默认为400,取值越大,字体越粗
  10673. Row() {
  10674. Text(`歌词字重:`)
  10675. .fontSize(14)
  10676. .fontColor(Color.White)
  10677. Slider({
  10678. value: isPip ? this.lyricTextWeightPip : this.lyricTextWeight,
  10679. min: 100,
  10680. max: 900,
  10681. step: 100,
  10682. style: SliderStyle.OutSet
  10683. })
  10684. .blockColor(this.themeColor)
  10685. .trackColor($r('app.color.speed_text_color'))
  10686. .selectedColor(Color.White)
  10687. .trackThickness(6)
  10688. .onChange((value: number) => {
  10689. if (isPip) {
  10690. this.lyricTextWeightPip = value
  10691. this.lyricControllerXF.setTextWeight(this.lyricTextWeightPip)
  10692. PreferencesUtil.putSync('lyricTextWeightPip', this.lyricTextWeightPip)
  10693. } else {
  10694. this.lyricTextWeight = value
  10695. this.lyricController.setTextWeight(this.lyricTextWeight)
  10696. PreferencesUtil.putSync('lyricTextWeight', this.lyricTextWeight)
  10697. }
  10698. })
  10699. .width('76%')
  10700. }
  10701. .margin({
  10702. left: 20,
  10703. right: 15,
  10704. top: 5,
  10705. bottom: 5
  10706. })
  10707. if (!isPip) {
  10708. Row() {
  10709. Text(`歌词模糊:`)
  10710. .fontSize(14)
  10711. .fontColor(Color.White)
  10712. Slider({
  10713. value: isPip ? this.blurDegreePip : this.blurDegree,
  10714. min: 0,
  10715. max: 5,
  10716. step: 0.1,
  10717. style: SliderStyle.OutSet
  10718. })
  10719. .blockColor(this.themeColor)
  10720. .trackColor($r('app.color.speed_text_color'))
  10721. .selectedColor(Color.White)
  10722. .trackThickness(6)
  10723. .onChange((value: number) => {
  10724. this.setBlurDegree(value, isPip)
  10725. })
  10726. .width('76%')
  10727. }
  10728. .margin({
  10729. left: 20,
  10730. right: 15,
  10731. top: 5,
  10732. bottom: 15
  10733. })
  10734. }
  10735. Row() {
  10736. this.pushLyricButton($r('app.media.cut_current'), 0, '本地歌词')
  10737. this.pushLyricButton($r('app.media.white_search'), 1, '获取歌词')
  10738. // this.pushLyricButton($r('app.media.white_search'), 1, '繁体转简体')
  10739. }
  10740. .justifyContent(FlexAlign.Center)
  10741. .margin({ top: 3, bottom: 10 })
  10742. }
  10743. }
  10744. private setBlurDegree(index: number, isPip: boolean) {
  10745. if (isPip) {
  10746. this.blurDegreePip = index
  10747. this.lyricControllerXF.setBlurDegree(this.blurDegreePip)
  10748. PreferencesUtil.putSync('setBlurDegreePip', this.blurDegreePip)
  10749. } else {
  10750. this.blurDegree = index
  10751. this.lyricController.setBlurDegree(this.blurDegree)
  10752. PreferencesUtil.putSync('setBlurDegree', this.blurDegree)
  10753. }
  10754. }
  10755. private setLyricAlignMode(index: number, isPip: boolean) {
  10756. if (isPip) {
  10757. this.currentLyricAlignModePip = index
  10758. if (this.currentLyricAlignModePip === 1) {
  10759. this.lyricControllerXF.setAlignMode("left")
  10760. } else {
  10761. this.lyricControllerXF.setAlignMode("center")
  10762. }
  10763. PreferencesUtil.putSync('LyricAlignModePip', this.currentLyricAlignModePip)
  10764. } else {
  10765. this.currentLyricAlignMode = index
  10766. if (this.currentLyricAlignMode === 1) {
  10767. this.lyricController.setAlignMode("left")
  10768. } else {
  10769. this.lyricController.setAlignMode("center")
  10770. }
  10771. PreferencesUtil.putSync('LyricAlignMode', this.currentLyricAlignMode)
  10772. }
  10773. }
  10774. private setLyricTextSize(index: number, isPip: boolean) {
  10775. if (isPip) {
  10776. this.currentLyricSizePip = index
  10777. this.lyricControllerXF.setTextSize(this.currentLyricSizePip)
  10778. PreferencesUtil.putSync('LyricTextSizePip', this.currentLyricSizePip)
  10779. } else {
  10780. this.currentLyricSize = index
  10781. this.lyricController.setTextSize(this.currentLyricSize)
  10782. PreferencesUtil.putSync('LyricTextSize', this.currentLyricSize)
  10783. }
  10784. }
  10785. private setHighLyricTextSize(scale: number, isPip: boolean) {
  10786. if (isPip) {
  10787. this.currentHightLyricSizePip = scale
  10788. this.lyricControllerXF
  10789. .setHighlightScale(this.currentHightLyricSizePip)
  10790. PreferencesUtil.putSync('HighLyricTextSizePip', scale)
  10791. } else {
  10792. this.currentHightLyricSize = scale
  10793. this.lyricController
  10794. .setHighlightScale(this.currentHightLyricSize)
  10795. PreferencesUtil.putSync('HighLyricTextSize', scale)
  10796. }
  10797. }
  10798. private setLyricLineSpace(index: number, isPip: boolean) {
  10799. if (isPip) {
  10800. this.currentLyricLineSpacePip = index
  10801. this.lyricControllerXF.setLineSpace(this.currentLyricLineSpacePip)
  10802. PreferencesUtil.putSync('LyricLineSpacePip', this.currentLyricLineSpacePip)
  10803. } else {
  10804. this.currentLyricLineSpace = index
  10805. this.lyricController.setLineSpace(this.currentLyricLineSpace)
  10806. PreferencesUtil.putSync('LyricLineSpace', this.currentLyricLineSpace)
  10807. }
  10808. }
  10809. private changeLyricColor(color: string, isPip: boolean, isBG?: boolean) {
  10810. LogUtil.info('onecold isBG = ' + isBG)
  10811. if (isBG) { //如果是设置悬浮背景
  10812. this.pipBg = color
  10813. PreferencesUtil.putSync('BGColorPip', this.pipBg)
  10814. this.nodeController.updateBgColor(this.pipBg, this.lyricControllerXF)
  10815. return
  10816. }
  10817. if (isPip) {
  10818. this.currentLyricColorPip = color
  10819. this.lyricControllerXF
  10820. .setTextColor(this.currentLyricColorPip)
  10821. PreferencesUtil.putSync('LyricColorPip', this.currentLyricColorPip)
  10822. } else {
  10823. this.currentLyricColor = color
  10824. this.lyricController
  10825. .setTextColor(this.currentLyricColor)
  10826. PreferencesUtil.putSync('LyricColor', this.currentLyricColor)
  10827. }
  10828. }
  10829. private changeLyricHightLightColor(color: string, isPip: boolean) {
  10830. if (isPip) {
  10831. this.currentHighLightLyricColorPip = color
  10832. this.lyricControllerXF
  10833. .setHighlightColor(this.currentHighLightLyricColorPip)
  10834. PreferencesUtil.putSync('LyricHighLightColorPip', this.currentHighLightLyricColorPip)
  10835. } else {
  10836. this.currentHighLightLyricColor = color
  10837. this.lyricController
  10838. .setHighlightColor(this.currentHighLightLyricColor)
  10839. PreferencesUtil.putSync('LyricHighLightColor', this.currentHighLightLyricColor)
  10840. }
  10841. }
  10842. // 构建时间控制器
  10843. @Builder
  10844. BuildTimeControls() {
  10845. Column() {
  10846. // 时间显示
  10847. Text(this.getTimeText())
  10848. .fontSize(18)
  10849. .fontColor(Color.White)
  10850. .margin({ bottom: 10 })
  10851. Row() {
  10852. this.PrecisionTimeButton($r('app.media.ic_previous'), -0.5, ' -0.5s ')
  10853. this.PrecisionTimeButton($r('app.media.loop'), 0, '重置')
  10854. this.PrecisionTimeButton($r('app.media.ic_next'), 0.5, ' +0.5s ')
  10855. }
  10856. .justifyContent(FlexAlign.Center)
  10857. }
  10858. .margin({ top: 12, bottom: 8 })
  10859. }
  10860. // 精度按钮组件
  10861. @Builder
  10862. PrecisionTimeButton(icon: Resource, step: number, label: string) {
  10863. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10864. Column() {
  10865. Image(icon)
  10866. .width(28)
  10867. .margin({ bottom: 5 })
  10868. .opacity(this.isButtonDisabled(step) ? 0.5 : 1)
  10869. Text(label)
  10870. .fontSize(12)
  10871. .fontColor('#FFFFFF')
  10872. }
  10873. }
  10874. .backgroundColor(Color.Transparent)
  10875. .enabled(!this.isButtonDisabled(step))
  10876. .onClick(() => this.handlePrecisionAdjust(step))
  10877. .padding(5)
  10878. .width(66)
  10879. .height(66)
  10880. .margin({ left: 18, right: 18 })
  10881. .border({
  10882. color: '#FFFFFF',
  10883. width: 1.8
  10884. })
  10885. }
  10886. private handlePrecisionAdjust(step: number) {
  10887. if (step === 0) {
  10888. this.timeOffset = 0
  10889. return
  10890. }
  10891. // 精度处理:保留1位小数
  10892. const newOffset = Number((this.timeOffset + step).toFixed(5))
  10893. // 边界保护(±15.0秒)
  10894. if (newOffset < -30.0 || newOffset > 30.0) {
  10895. // this.triggerEdgeFeedback(newOffset) // 触发边界反馈
  10896. return
  10897. }
  10898. // 状态更新
  10899. this.timeOffset = newOffset
  10900. }
  10901. // 按钮禁用逻辑
  10902. private isButtonDisabled(step: number): boolean {
  10903. const futureOffset = this.timeOffset + step
  10904. return (futureOffset < -30.0) || (futureOffset > 30.0)
  10905. }
  10906. // 时间显示文本升级
  10907. private getTimeText(): string {
  10908. const absValue = Math.abs(this.timeOffset)
  10909. return this.timeOffset === 0
  10910. ? '歌词时间已重置'
  10911. : `歌词已${this.timeOffset < 0 ? '延后' : '提前'} ${absValue.toFixed(1)} 秒`
  10912. }
  10913. // 导入 本地歌词 搜索歌词
  10914. @Builder
  10915. pushLyricButton(icon: Resource, step: number, label: string) {
  10916. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  10917. Row() {
  10918. Image(icon)
  10919. .width(14)
  10920. .margin({ left: 13 })
  10921. Text(label)
  10922. .fontSize(12)
  10923. .margin({ left: 6 })
  10924. .fontColor('#FFFFFF')
  10925. }
  10926. }
  10927. .onClick(() => {
  10928. switch (step) {
  10929. case 0:
  10930. this.callFilePickerSelectFileForLyric()
  10931. break;
  10932. case 1:
  10933. //判断有没有设置api
  10934. if (PreferencesUtil.getStringSync('LRC_API', '') === '') {
  10935. this.isLyricSetting = false
  10936. this.showTipsDialog()
  10937. return
  10938. }
  10939. if (StrUtil.isNotEmpty(this.videoUrl)) {
  10940. ToastUtil.showToast('正在获取')
  10941. this.isLyricSetting = false
  10942. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  10943. this.initLyric(lyricPath, true);
  10944. }
  10945. break;
  10946. }
  10947. })
  10948. .padding(5)
  10949. .width(110)
  10950. .backgroundColor(Color.Transparent)
  10951. .height(40)
  10952. .margin({ left: 6, right: 6 })
  10953. .border({
  10954. color: '#FFFFFF',
  10955. radius: 20,
  10956. width: 1.8
  10957. })
  10958. }
  10959. showVipDialog() {
  10960. DialogHelper.showCustomContentDialog({
  10961. dialogId: 'vip',
  10962. title: "友情提示",
  10963. autoCancel: false, //点击遮障层时,不关闭弹窗
  10964. backCancel: true, //点击返回键,不关闭弹窗
  10965. contentBuilder: () => {
  10966. this.customVipBuilder("该功能需开通会员,非常感谢您的支持!")
  10967. },
  10968. buttons: [],
  10969. })
  10970. }
  10971. //去赞助的自定义内容
  10972. @Builder
  10973. customVipBuilder(content: string) {
  10974. Column() {
  10975. Text(content)
  10976. .fontColor(Color.Gray)
  10977. .fontSize(16)
  10978. .alignSelf(ItemAlign.Start)
  10979. .margin({ bottom: 15 })
  10980. .fontSize(16)
  10981. Row() {
  10982. Button('取消')
  10983. .fontColor(Color.White)
  10984. .backgroundColor(this.themeColor)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  10985. .height(50)
  10986. .layoutWeight(1)
  10987. .stateEffect(true)
  10988. .margin({ right: 6 })
  10989. .onClick(() => {
  10990. DialogHelper.closeDialog('vip'); //关闭弹框
  10991. })
  10992. Button('开通')
  10993. .fontColor(Color.White)//.linearGradient( { direction: GradientDirection.Right, colors:[['#ff37a0fc',0.0],['#67e667',0.5],['#f5856e',1.0]]})
  10994. .layoutWeight(1)
  10995. .height(50)
  10996. .backgroundColor(this.themeColor)
  10997. .stateEffect(true)
  10998. .margin({ left: 6 })
  10999. .onClick(() => {
  11000. DialogHelper.closeDialog('vip'); //关闭弹框
  11001. this.isShowPlay = false
  11002. this.mType = 1 //跳转到用户中心
  11003. // router.pushUrl({
  11004. // url: 'pages/VipPage'
  11005. // }, router.RouterMode.Single);
  11006. })
  11007. }
  11008. }
  11009. .width("100%")
  11010. .padding(10)
  11011. }
  11012. showTipsDialog() {
  11013. DialogHelper.showCustomContentDialog({
  11014. dialogId: 'tips',
  11015. title: "友情提示",
  11016. autoCancel: false, //点击遮障层时,不关闭弹窗
  11017. backCancel: true, //点击返回键,不关闭弹窗
  11018. contentBuilder: () => {
  11019. this.customTipsBuilder("请到设置界面配置API服务器地址!")
  11020. },
  11021. buttons: [],
  11022. })
  11023. }
  11024. @Builder
  11025. customTipsBuilder(content: string) {
  11026. Column() {
  11027. Text(content)
  11028. .fontColor(Color.Gray)
  11029. .fontSize(16)
  11030. .alignSelf(ItemAlign.Start)
  11031. .margin({ bottom: 15 })
  11032. .fontSize(16)
  11033. Row() {
  11034. Button('取消')
  11035. .fontColor(Color.White)
  11036. .backgroundColor(this.themeColor)
  11037. .height(50)
  11038. .layoutWeight(1)
  11039. .stateEffect(true)
  11040. .margin({ right: 6 })
  11041. .onClick(() => {
  11042. DialogHelper.closeDialog('tips'); //关闭弹框
  11043. })
  11044. Button('跳转')
  11045. .fontColor(Color.White)//
  11046. .layoutWeight(1)
  11047. .height(50)
  11048. .backgroundColor(this.themeColor)
  11049. .stateEffect(true)
  11050. .margin({ left: 6 })
  11051. .onClick(() => {
  11052. DialogHelper.closeDialog('tips'); //关闭弹框
  11053. this.isShowEdit = false
  11054. this.longItemFilePath = ''
  11055. // if(this.isGridMusic&&!this.isShowPlay){
  11056. // this.longItemFilePath== ''
  11057. // }else{
  11058. // this.isShowEdit = false
  11059. // }
  11060. this.isShowMoreView = false;
  11061. this.isShowPlay = false
  11062. this.mType = 4
  11063. // router.pushUrl({
  11064. // url: 'pages/SettingPage'
  11065. // }, router.RouterMode.Single);
  11066. })
  11067. }
  11068. }
  11069. .width("100%")
  11070. .padding(10)
  11071. }
  11072. @Builder
  11073. PlayMoreSheet() {
  11074. Column() {
  11075. this.MoreList()
  11076. }
  11077. .width('100%')
  11078. .height('100%')
  11079. }
  11080. @Builder
  11081. MoreList() {
  11082. Scroll() {
  11083. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
  11084. ForEach(this.moreItems, (more: MoreItem, index: number) => {
  11085. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  11086. Row() {
  11087. if (more.id === 3&&this.currentSong) {
  11088. Image(more.image)
  11089. .width(24)
  11090. .height(24)
  11091. .margin({ left: 10, right: 10 })
  11092. Text(more.title)
  11093. .fontSize(16)
  11094. .fontColor(Color.White)
  11095. .bindSheet($$this.isShowDetailMore, this.detailSheet(this.currentSong), {
  11096. height: this.isCoverOpacity() ? '95%' : '95%',
  11097. dragBar: true,
  11098. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11099. showClose: true,
  11100. blurStyle: BlurStyle.Thin,
  11101. backgroundColor: Color.Transparent,
  11102. title: { title: '歌曲信息' }
  11103. })
  11104. } else if (more.id === 15 && this.currentSong) { //编辑标签
  11105. Image(more.image)
  11106. .width(24)
  11107. .height(24)
  11108. .margin({ left: 10, right: 10 })
  11109. Text(more.title)
  11110. .fontSize(16)
  11111. .fontColor(Color.White)
  11112. } else if (more.id === 5) { //定时关闭
  11113. Image(more.image)
  11114. .width(24)
  11115. .height(24)
  11116. .margin({ left: 10, right: 10 })
  11117. Text(more.title)
  11118. .fontSize(16)
  11119. .fontColor(Color.White)
  11120. .onClick(() => {
  11121. this.doMore(more.id)
  11122. })
  11123. .bindSheet($$this.isShowTimeCloseMore, this.TimeCloseSheet(), {
  11124. height: this.isCoverOpacity() ? '95%' : '95%',
  11125. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11126. dragBar: true,
  11127. showClose: true,
  11128. title: { title: $r('app.string.time_close') }
  11129. })
  11130. } else if (more.id === 2) { //歌词设置
  11131. Image(more.image)
  11132. .width(24)
  11133. .height(24)
  11134. .margin({ left: 10, right: 10 })
  11135. Text(more.title)
  11136. .fontSize(16)
  11137. .fontColor(Color.White)
  11138. } else if (more.id === 16) { //悬浮歌词设置
  11139. Image(more.image)
  11140. .width(24)
  11141. .height(24)
  11142. .margin({ left: 10, right: 10 })
  11143. Text(more.title)
  11144. .fontSize(16)
  11145. .fontColor(Color.White)
  11146. .bindSheet($$this.showPipLyric, this.lyricSettingSheet(true), {
  11147. height: this.isCoverOpacity() ? '95%' : '95%',
  11148. dragBar: true,
  11149. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11150. showClose: true,
  11151. blurStyle: BlurStyle.Thin,
  11152. backgroundColor: Color.Transparent,
  11153. title: { title: '悬浮歌词' }
  11154. })
  11155. } else if (more.id === 11) {
  11156. Image(more.image)
  11157. .width(24)
  11158. .height(24)
  11159. .margin({ left: 10, right: 10 })
  11160. Text(more.title)
  11161. .fontSize(16)
  11162. .fontColor(Color.White)
  11163. .bindSheet($$this.isJumpSetting, this.JumpTopEndSheet(), {
  11164. height: this.isCoverOpacity() ? '95%' : '60%',
  11165. dragBar: true,
  11166. preferType: this.currentBreakpoint !== BreakpointTypeEnum.SM ? SheetType.CENTER : SheetType.BOTTOM,
  11167. showClose: true,
  11168. blurStyle: BlurStyle.Thin,
  11169. backgroundColor: Color.Transparent,
  11170. title: { title: '跳过头尾' }
  11171. })
  11172. } else if (more.id === 12) { //投播
  11173. AVCastPicker({
  11174. customPicker: (): void => this.TPImageBuilder(more),
  11175. onStateChange: (state) => {
  11176. if (state == AVCastPickerState.STATE_APPEARING) {
  11177. console.log(' The picker starts showing.');
  11178. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  11179. console.log(' The picker finishes presenting.');
  11180. }
  11181. },
  11182. pickerStyle: AVCastPickerStyle.STYLE_PANEL,
  11183. sessionType: 'video'
  11184. })
  11185. .id('AVCastPicker')
  11186. } else {
  11187. Image(more.image)
  11188. .width(24)
  11189. .height(24)
  11190. .fillColor(Color.White)
  11191. .margin({ left: 10, right: 10 })
  11192. .onClick(() => {
  11193. this.doMore(more.id)
  11194. })
  11195. Text(more.id == 17 ? (this.isLandscape ? '竖屏模式' : '横屏模式') : more.title)
  11196. .fontSize(16)
  11197. .fontColor(Color.White)
  11198. .onClick(() => {
  11199. this.doMore(more.id)
  11200. })
  11201. Select([//倍速
  11202. { value: '0.25x' },
  11203. { value: '0.5x' },
  11204. { value: '0.75x' },
  11205. { value: '1x' },
  11206. { value: '1.25x' },
  11207. { value: '1.5x' },
  11208. { value: '1.75x' },
  11209. { value: '2x' },
  11210. { value: '3x' }])
  11211. .font({ size: 16, weight: FontWeight.Medium })
  11212. .fontColor($r('sys.color.white'))
  11213. .margin({ left: 25 })
  11214. .visibility(more.id === 1 ? Visibility.Visible : Visibility.None)
  11215. .selected(CommonConstants.video_speed_list.indexOf(this.playSpeed))
  11216. .value(Utility.optimizedFormat(this.playSpeed))
  11217. .onSelect(async (_index: number, text?: string | undefined) => {
  11218. let speed = parseFloat(text?.replace('x', '') || '1');
  11219. if (!CommonConstants.video_speed_list.includes(speed)) {
  11220. speed = 1;
  11221. }
  11222. this.playSpeed = speed
  11223. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  11224. })
  11225. Slider({
  11226. value: this.volume,
  11227. min: 0,
  11228. max: 1,
  11229. step: 0.1,
  11230. style: SliderStyle.OutSet
  11231. })
  11232. .margin({ left: 18, right: 8 })
  11233. .blockColor(this.themeColor)
  11234. .trackColor($r('app.color.speed_text_color'))
  11235. .selectedColor(Color.White)
  11236. .trackThickness(9)
  11237. .visibility(more.id === 9 ? Visibility.Visible : Visibility.None)
  11238. .onChange((value: number) => {
  11239. this.volume = value;
  11240. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  11241. PreferencesUtil.putSync('DefalutVolume',this.volume)
  11242. })
  11243. .layoutWeight(1)
  11244. Blank()
  11245. Toggle({ type: ToggleType.Switch, isOn: this.isMusicMemoryPlay })
  11246. .selectedColor(this.themeColor)
  11247. .switchPointColor(Color.White)
  11248. .margin({ right: 15 })
  11249. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11250. .visibility(more.id == 6 ? Visibility.Visible : Visibility.None)
  11251. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11252. if (more.id == 6) {
  11253. this.isMusicMemoryPlay = checked;
  11254. PreferencesUtil.put(SettingPage.iS_MUSIC_MEMORY_PLAY, this.isMusicMemoryPlay)
  11255. if (this.isMusicMemoryPlay) {
  11256. ToastUtil.showToast('记忆播放已开启')
  11257. } else {
  11258. ToastUtil.showToast('记忆播放已关闭')
  11259. }
  11260. }
  11261. })
  11262. .width(48)
  11263. .height(24);
  11264. Toggle({ type: ToggleType.Switch, isOn: this.isMusicBGCover })
  11265. .selectedColor(this.themeColor)
  11266. .switchPointColor(Color.White)
  11267. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11268. .margin({ right: 15 })
  11269. .visibility(more.id == 7 ? Visibility.Visible : Visibility.None)
  11270. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11271. if (more.id == 7) {
  11272. this.isMusicBGCover = checked;
  11273. PreferencesUtil.put(SettingPage.iS_MUSIC_BG_COVER, this.isMusicBGCover)
  11274. if (this.isMusicBGCover) {
  11275. ToastUtil.showToast('播放背景随音乐封面已开启')
  11276. } else {
  11277. ToastUtil.showToast('播放背景随音乐封面已关闭')
  11278. }
  11279. }
  11280. })
  11281. .width(48)
  11282. .height(24);
  11283. Toggle({ type: ToggleType.Switch, isOn: this.isSavePlayMode })
  11284. .selectedColor(this.themeColor)
  11285. .switchPointColor(Color.White)
  11286. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11287. .margin({ right: 15 })
  11288. .visibility(more.id == 8 ? Visibility.Visible : Visibility.None)
  11289. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11290. if (more.id == 8) {
  11291. this.isSavePlayMode = checked;
  11292. PreferencesUtil.put(SettingPage.iS_SAVE_PLAY_MODE, this.isSavePlayMode)
  11293. if (this.isSavePlayMode) {
  11294. ToastUtil.showToast('保存播放模式已开启')
  11295. } else {
  11296. ToastUtil.showToast('保存播放模式已关闭')
  11297. }
  11298. }
  11299. })
  11300. .width(48)
  11301. .height(24);
  11302. Toggle({ type: ToggleType.Switch, isOn: this.isCoverRectangle })
  11303. .selectedColor(this.themeColor)
  11304. .switchPointColor(Color.White)
  11305. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11306. .margin({ right: 15 })
  11307. .visibility(more.id == 13 ? Visibility.Visible : Visibility.None)
  11308. .onChange((checked: boolean) => { // 选择开关状态变化时触发事件
  11309. if (more.id == 13) {
  11310. this.isCoverRectangle = checked;
  11311. PreferencesUtil.put(SettingPage.IS_COVER_RECTANGLE, this.isCoverRectangle)
  11312. if (this.isCoverRectangle) {
  11313. ToastUtil.showToast('封面方形已开启')
  11314. this.animationRoFun()
  11315. } else {
  11316. ToastUtil.showToast('封面圆形已开启')
  11317. this.animationRoFun()
  11318. }
  11319. }
  11320. })
  11321. .width(48)
  11322. .height(24);
  11323. Toggle({ type: ToggleType.Switch, isOn: this.isShowBgLiuGUANG })
  11324. .selectedColor(this.themeColor)
  11325. .switchPointColor(Color.White)
  11326. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.5 })
  11327. .margin({ right: 15 })
  11328. .visibility(more.id == 21 ? Visibility.Visible : Visibility.None)
  11329. .onChange((checked: boolean) => { // 是否开启背景流光效果
  11330. if (more.id == 21) {
  11331. this.isShowBgLiuGUANG = checked;
  11332. PreferencesUtil.putSync('isShowBgLiuGUANG',this.isShowBgLiuGUANG)
  11333. }
  11334. })
  11335. .width(48)
  11336. .height(24);
  11337. }
  11338. }
  11339. .width('100%')
  11340. .height(45)
  11341. .padding(15)
  11342. .backgroundColor(Color.Transparent)
  11343. .borderRadius(12)
  11344. .margin({ bottom: 6 })
  11345. }
  11346. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.9 })
  11347. .transition(TransitionEffect.move(TransitionEdge.BOTTOM)
  11348. .animation({ duration: 600, curve: Curve.Ease, delay: 60 * index }))
  11349. .backgroundColor(Color.Transparent)
  11350. .onClick(() => {
  11351. this.doMore(more.id)
  11352. })
  11353. });
  11354. }
  11355. .width('100%')
  11356. .padding(16)
  11357. }.margin({ bottom: 18 })
  11358. }
  11359. @Builder
  11360. TPImageBuilder(more: MoreItem): void {
  11361. Row() {
  11362. Image($r('app.media.tuoping'))
  11363. .width(22)
  11364. .height(22)
  11365. .margin({ left: 10, right: 10 })
  11366. Text(more.title)
  11367. .fontSize(16)
  11368. .fontColor(Color.White)
  11369. }
  11370. .width('100%')
  11371. .layoutWeight(1)
  11372. .alignItems(VerticalAlign.Center)
  11373. .justifyContent(FlexAlign.Start)
  11374. }
  11375. private moreItems: MoreItem[] = [
  11376. { id: 1, image: $r('app.media.speed'), title: '倍速' },
  11377. { id: 2, image: $r('app.media.lyric'), title: '歌词' },
  11378. { id: 17, image: $r('app.media.full_4'), title: '横屏模式' },
  11379. { id: 16, image: $r('app.media.hua_zhong_hua'), title: '悬浮歌词' },
  11380. { id: 14, image: $r('app.media.cover_online'), title: '获取封面' },
  11381. { id: 15, image: $r('app.media.rename2'), title: '编辑标签' },
  11382. { id: 5, image: $r('app.media.time_close'), title: '定时关闭' },
  11383. { id: 10, image: $r('app.media.ring_tone'), title: '设为铃声' },
  11384. { id: 11, image: $r('app.media.time_close'), title: '跳过头尾' },
  11385. { id:20,image: $r("app.media.a_b"), title: 'AB循环' },
  11386. { id: 12, image: $r('app.media.toubo'), title: '投播' },
  11387. { id: 3, image: $r('app.media.hua_zhong_hua'), title: '详情' },
  11388. { id: 4, image: $r('app.media.share2'), title: '分享' },
  11389. { id: 9, image: $r('app.media.volume_white'), title: '调整音量' },
  11390. // { id: 6, image: $r('app.media.memory'), title: '记忆播放' },
  11391. { id: 13, image: $r('app.media.rectangle'), title: '封面方形' },
  11392. { id : 21, image: $r('app.media.music_red'), title: '开启背景流光' },
  11393. { id: 8, image: $r('app.media.cut_current'), title: '保存播放模式' },
  11394. { id: 7, image: $r('app.media.playlist2'), title: '播放背景随音乐封面' },
  11395. ];
  11396. @State isShowBgLiuGUANG: boolean = true;
  11397. @State isShowMoreView: boolean = false;
  11398. @State isMusicMemoryPlay: boolean = false //是否启用记忆播放
  11399. @State isShowTimeCloseMore: boolean = false
  11400. @State isShowDetailMore: boolean = false
  11401. @State isMusicBGCover: boolean = true
  11402. @State isSavePlayMode: boolean = true
  11403. @State isLyricSetting: boolean = false
  11404. @State isJumpSetting: boolean = false
  11405. @State isShowEdit: boolean = false
  11406. @State showPipLyric: boolean = false
  11407. async setRingTone() {
  11408. if (StrUtil.isEmpty(this.videoUrl) || StrUtil.isEmpty(this.name)) {
  11409. return
  11410. }
  11411. // 确定后的逻辑
  11412. let ringtoneTypeList: Array<ringtone.RingtoneType> = ringtone.getSupportedRingtoneTypes();
  11413. LogUtil.info('onecold getSupportedRingtoneTypes : ' + JSON.stringify(ringtoneTypeList));
  11414. let dataTypeList: Array<uniformTypeDescriptor.UniformDataType> =
  11415. ringtone.getSupportedDataTypes(ringtone.RingtoneType.NOTIFICATION);
  11416. LogUtil.info('onecold getSupportedDataTypes: ' + JSON.stringify(dataTypeList));
  11417. //let fileName: string = audioPath.substring(audioPath.lastIndexOf('/') + 1, audioPath.lastIndexOf('.'));
  11418. await ringtone.startRingtoneSetting(getContext(this) as common.UIAbilityContext
  11419. , this.videoUrl, this.name).then(res => {
  11420. LogUtil.info('onecold setFlag :' + res);
  11421. });
  11422. }
  11423. doMore(moreId: number) {
  11424. switch (moreId) {
  11425. case 2: //歌词
  11426. this.isLyricSetting = !this.isLyricSetting;
  11427. this.isShowMoreView = false
  11428. break;
  11429. case 3: //详情
  11430. this.isShowDetailMore = !this.isShowDetailMore;
  11431. break;
  11432. case 4: //分享
  11433. if (this.currentSong !== undefined) {
  11434. Utility.doShareMusic(this.currentSong, getContext(this) as common.UIAbilityContext)
  11435. }
  11436. this.isShowMoreView = false
  11437. break;
  11438. case 5: //定时关闭
  11439. this.isShowTimeCloseMore = !this.isShowTimeCloseMore;
  11440. break;
  11441. case 10: //设为铃声
  11442. this.setRingTone()
  11443. this.isShowMoreView = false
  11444. break;
  11445. case 11: //跳过头尾
  11446. this.isJumpSetting = !this.isJumpSetting;
  11447. break;
  11448. case 13: //倍速
  11449. break;
  11450. case 14: //搜索封面
  11451. if (this.currentSong !== undefined) {
  11452. this.doSearchCover(this.currentSong)
  11453. }
  11454. this.isShowMoreView = false
  11455. break;
  11456. case 15: //编辑标签
  11457. this.initEditFields(this.currentSong)
  11458. this.tempLyricContent = this.lyricContent
  11459. if (StrUtil.isNotEmpty(this.tempLyricContent)) {
  11460. this.lyricConStr = this.tempLyricContent
  11461. }
  11462. this.isShowEdit = !this.isShowEdit;
  11463. break;
  11464. case 16: //悬浮歌词
  11465. this.showPipLyric = !this.showPipLyric;
  11466. break;
  11467. case 17: //横屏模式
  11468. if (this.isLandscape) {
  11469. this.setOrientation(window.Orientation.USER_ROTATION_PORTRAIT);
  11470. } else {
  11471. this.setOrientation(window.Orientation.USER_ROTATION_LANDSCAPE);
  11472. }
  11473. this.isShowMoreView = false
  11474. break;
  11475. case 20://AB循环
  11476. this.isABSheet = !this.isABSheet
  11477. break;
  11478. }
  11479. }
  11480. //AB循环
  11481. @State isOpenAB:boolean = false
  11482. @State jumpATime:number = 0
  11483. @State jumpBTime:number = 0
  11484. @State isABSheet:boolean = false
  11485. @Builder
  11486. ABLoopSheet() {
  11487. ABLoopComptent({
  11488. jumpATime:this.jumpATime,
  11489. jumpBTime:this.jumpBTime,
  11490. onClickAItem: async ()=>{
  11491. if(this.mIjkMediaPlayer){
  11492. this.jumpATime = await this.mIjkMediaPlayer.getCurrentPosition()
  11493. }
  11494. },
  11495. onClickBItem: async ()=>{
  11496. if(this.mIjkMediaPlayer){
  11497. this.jumpBTime = await this.mIjkMediaPlayer.getCurrentPosition()
  11498. if(this.jumpBTime<=this.jumpATime){
  11499. ToastUtil.showToast('设置B点时间不能小于A点时间')
  11500. this.jumpBTime = 0
  11501. }
  11502. }
  11503. },
  11504. onCancleButtonClick: async ()=>{
  11505. this.isOpenAB = false
  11506. this.isABSheet = false
  11507. },
  11508. onStartButtonClick: async ()=>{
  11509. if(this.jumpBTime<=this.jumpATime||this.stringForTime(this.jumpATime)==this.stringForTime(this.jumpBTime)){
  11510. ToastUtil.showToast('设置B点时间不能小于或等于A点时间')
  11511. return
  11512. }
  11513. this.isABSheet = false
  11514. this.startABLoop()
  11515. },
  11516. })
  11517. }
  11518. //开始AB循环
  11519. startABLoop(){
  11520. if(this.mIjkMediaPlayer){
  11521. this.seekTo(this.jumpATime+'')
  11522. this.isOpenAB = true
  11523. }
  11524. }
  11525. /**
  11526. * 切换横竖屏
  11527. *
  11528. */
  11529. setOrientation(orientation: number) {
  11530. this.windowClass.setPreferredOrientation(orientation).then(() => {
  11531. Logger.info('setWindowOrientation: ' + orientation + ' Succeeded.');
  11532. }).catch((err: BusinessError) => {
  11533. Logger.info('setWindowOrientation: ' + orientation + ' Failed. Cause: ' + JSON.stringify(err));
  11534. });
  11535. }
  11536. /**
  11537. * 画中画功能(悬浮歌词功能)
  11538. *
  11539. */
  11540. private nodeController: TextNodeController = new TextNodeController('#000000', this.lyricControllerXF);
  11541. pipController?: PiPWindow.PiPController;
  11542. navigationId: string = '';
  11543. @State curState: string = '';
  11544. @State curError: ResourceStr = '';
  11545. @State pipBg: string = '#E8E8E8'
  11546. @State buttonAction: string = '';
  11547. //开启画中画功能
  11548. async startPip() {
  11549. this.nodeController = new TextNodeController(this.pipBg, this.lyricControllerXF);
  11550. if (!this.pipController) {
  11551. await this.createPipController();
  11552. }
  11553. if (!this.pipController) {
  11554. Logger.info(`[${TAG}] pipController create error`);
  11555. return;
  11556. }
  11557. await this.pipController.startPiP();
  11558. }
  11559. async stopPip() {
  11560. if (!this.pipController) {
  11561. Logger.info(`[${TAG}] pipController is not exist`);
  11562. return;
  11563. }
  11564. this.isOpenPip = false
  11565. await this.pipController.stopPiP();
  11566. }
  11567. async createPipController() {
  11568. this.pipController = await PiPWindow.create({
  11569. context: getContext(this),
  11570. componentController: this.xcomponentController,
  11571. navigationId: this.navigationId,
  11572. templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
  11573. controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
  11574. customUIController: this.nodeController,
  11575. });
  11576. this.pipLyWidth = PreferencesUtil.getNumberSync('pipLyWidth', 330)
  11577. this.pipLyHeight = PreferencesUtil.getNumberSync('pipLyHeight', 120)
  11578. this.pipController.updateContentSize(this.pipLyWidth, this.pipLyHeight);
  11579. this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
  11580. this.onStateChange(state, reason);
  11581. });
  11582. this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
  11583. this.onActionEvent(event, status);
  11584. });
  11585. }
  11586. destroyPipController() {
  11587. if (!this.pipController) {
  11588. return;
  11589. }
  11590. this.pipController.off('stateChange');
  11591. this.pipController.off('controlPanelActionEvent');
  11592. this.pipController = undefined;
  11593. }
  11594. onStateChange(state: PiPWindow.PiPState, reason: string) {
  11595. switch (state) {
  11596. case PiPWindow.PiPState.ABOUT_TO_START:
  11597. this.curState = 'ABOUT_TO_START';
  11598. this.curError = $r('app.string.current_error_hint');
  11599. break;
  11600. case PiPWindow.PiPState.STARTED:
  11601. this.curState = 'STARTED';
  11602. this.curError = $r('app.string.current_error_hint');
  11603. break;
  11604. case PiPWindow.PiPState.ABOUT_TO_STOP:
  11605. this.curState = 'ABOUT_TO_STOP';
  11606. this.curError = $r('app.string.current_error_hint');
  11607. break;
  11608. case PiPWindow.PiPState.STOPPED:
  11609. this.curState = 'STOPPED';
  11610. this.curError = $r('app.string.current_error_hint');
  11611. this.stopPip()
  11612. this.destroyPipController()
  11613. break;
  11614. case PiPWindow.PiPState.ABOUT_TO_RESTORE:
  11615. this.curState = 'ABOUT_TO_RESTORE';
  11616. this.curError = $r('app.string.current_error_hint');
  11617. break;
  11618. case PiPWindow.PiPState.ERROR:
  11619. this.curState = 'ERROR';
  11620. this.curError = reason;
  11621. break;
  11622. default:
  11623. break;
  11624. }
  11625. Logger.info(`[${TAG}] onecold onStateChange: ${this.curState}, reason: ${reason}`);
  11626. }
  11627. onActionEvent(event: PiPWindow.PiPActionEventType, status: number | undefined) {
  11628. LogUtil.info('onecold onActionEvent = ' + event + ' status=' + status)
  11629. switch (event) {
  11630. case 'playbackStateChanged':
  11631. if (status === 0) {
  11632. this.pause();
  11633. } else {
  11634. console.info('onecold startPlayOrResumePlay 9869')
  11635. this.startPlayOrResumePlay();
  11636. }
  11637. break;
  11638. case 'nextVideo':
  11639. // 切换到下一个视频
  11640. this.playNext().catch(() => {
  11641. Logger.error('heanup onActionEvent playNext', `播放下一首失败`);
  11642. });
  11643. break;
  11644. case 'previousVideo':
  11645. // 切换到上一个视频
  11646. this.playPrevious().catch(() => {
  11647. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败`);
  11648. });
  11649. break;
  11650. case 'previousVideo':
  11651. // 切换到上一个视频
  11652. this.playPrevious().catch(() => {
  11653. Logger.error('heanup onActionEvent playPrevious', `播放上一首失败:`);
  11654. });
  11655. break;
  11656. default:
  11657. }
  11658. this.buttonAction = event + `-status:${status}`;
  11659. Logger.info(`[${TAG}] onActionEvent: ${this.buttonAction} status:${status}}`);
  11660. }
  11661. /**
  11662. * 画中画功能(悬浮歌词功能)结束
  11663. *
  11664. */
  11665. async doSearchCover(item: VideoItem,title?:string,artist?:string): Promise<string> {
  11666. if (PreferencesUtil.getStringSync('COVER_API', '') === '') {
  11667. this.isShowMoreView = false;
  11668. this.showTipsDialog();
  11669. return ''; // Return empty string when no API is configured
  11670. }
  11671. if (!item) {
  11672. return ''; // Return empty string if item is undefined
  11673. }
  11674. const titleS = title||item?.name || '';
  11675. const artistS = artist||item?.artist || ''; // Use empty string if artist is missing
  11676. return this.searchCover(item, titleS, artistS); // Await is not needed here as we return the promise directly
  11677. }
  11678. /**
  11679. *api搜索封面
  11680. *item,根据title和artist
  11681. */
  11682. searchCover(item: VideoItem, title: string, artist: string): Promise<string> {
  11683. return NetAxiosUtil.getLyricCover(title, artist, PreferencesUtil.getStringSync('COVER_API', '')).then(async (res) => {
  11684. LogUtil.debug("onecold res =" + res);
  11685. if (StrUtil.isNotEmpty(res) && res !== 'unknown' && res !== 'Timeout was reached') {
  11686. if (item.filePath == this.currentSong?.filePath) {
  11687. this.cover = res;
  11688. if (this.currentSong) {
  11689. this.currentSong.pixelMapPath = res;
  11690. }
  11691. }
  11692. // Update pixel map path but always return res regardless of success
  11693. this.table.updatePixelMapPath(item.filePath, res, (success: boolean, error?: string) => {
  11694. if (success) {
  11695. this.doUpdateData();
  11696. console.log("onecold 更新音乐封面成功,数据库已同步");
  11697. } else {
  11698. console.error("onecold 更新音乐封面数据库失败原因: " + error);
  11699. }
  11700. // Note: We don't resolve/reject here because we already returned res
  11701. });
  11702. LogUtil.debug("onecold this.cover =" + this.cover);
  11703. }
  11704. return res; // Always return res regardless of updatePixelMapPath result
  11705. });
  11706. }
  11707. @State jumpTopTime: number = 0
  11708. @State jumpEndTime: number = 0
  11709. @State isOpenJump: boolean = false
  11710. @Builder
  11711. JumpTopEndSheet() {
  11712. Scroll() {
  11713. Column() {
  11714. Column() {
  11715. Text('仅对本播放列表有效')
  11716. .fontSize(16)
  11717. .fontColor($r('app.color.text_color'))
  11718. // 跳过头尾
  11719. Column() {
  11720. Row() {
  11721. Text('跳过片头:')
  11722. .fontSize(16)
  11723. .fontColor($r('app.color.text_color'))
  11724. Text(this.jumpTopTime + 's')
  11725. .fontSize(16)
  11726. .fontColor($r('app.color.text_color'))
  11727. }
  11728. .margin({ bottom: 5 })
  11729. Row() {
  11730. Slider({
  11731. value: this.jumpTopTime,
  11732. min: 0,
  11733. max: 120,
  11734. step: 1,
  11735. style: SliderStyle.OutSet
  11736. })
  11737. .blockColor(this.themeColor)
  11738. .trackColor($r('app.color.speed_text_color'))
  11739. .selectedColor(Color.White)
  11740. .trackThickness(8)
  11741. .onChange((value: number) => {
  11742. this.jumpTopTime = value;
  11743. })
  11744. .width('85%')
  11745. }
  11746. .alignItems(VerticalAlign.Top)
  11747. }
  11748. .margin({ top: 10, bottom: 10 })
  11749. // 跳过头尾
  11750. Column() {
  11751. Row() {
  11752. Text('跳过片尾:')
  11753. .fontSize(16)
  11754. .fontColor($r('app.color.text_color'))
  11755. Text(this.jumpEndTime + 's')
  11756. .fontSize(16)
  11757. .fontColor($r('app.color.text_color'))
  11758. }
  11759. .margin({ bottom: 5 })
  11760. Row() {
  11761. Slider({
  11762. value: this.jumpEndTime,
  11763. min: 0,
  11764. max: 120,
  11765. step: 1,
  11766. style: SliderStyle.OutSet
  11767. })
  11768. .blockColor(this.themeColor)
  11769. .trackColor($r('app.color.speed_text_color'))
  11770. .selectedColor(Color.White)
  11771. .trackThickness(8)
  11772. .onChange((value: number) => {
  11773. this.jumpEndTime = value;
  11774. })
  11775. .width('85%')
  11776. }
  11777. .alignItems(VerticalAlign.Top)
  11778. }
  11779. .margin({ top: 10, bottom: 10 })
  11780. Row() {
  11781. Button('保存设置')
  11782. .fontColor(Color.White)
  11783. .layoutWeight(1)
  11784. .height(40)
  11785. .width(80)
  11786. .backgroundColor(this.themeColor)
  11787. .stateEffect(true)
  11788. .margin({ left: 0, bottom: 20 })
  11789. .onClick(async () => {
  11790. if (!Utility.isNoble()) {
  11791. this.isJumpSetting = false
  11792. this.isShowMoreView = false
  11793. this.showVipDialog()
  11794. return
  11795. }
  11796. if (this.currentSong === undefined) {
  11797. return
  11798. }
  11799. if (this.modeType === 0) {
  11800. let parentPath = FileUtil.getParentPath(this.videoUrl)
  11801. PreferencesUtil.putSync(parentPath + 'isOpenJump', true)
  11802. PreferencesUtil.putSync(parentPath + 'jumpEndTime', this.jumpEndTime)
  11803. PreferencesUtil.putSync(parentPath + 'jumpTopTime', this.jumpTopTime)
  11804. } else if (this.modeType === 1) { //媒体库
  11805. PreferencesUtil.putSync(1 + 'isOpenJump', true)
  11806. PreferencesUtil.putSync(1 + 'jumpEndTime', this.jumpEndTime)
  11807. PreferencesUtil.putSync(1 + 'jumpTopTime', this.jumpTopTime)
  11808. } else if (this.modeType === 2) { //艺术家
  11809. if (this.currentSong?.artist) {
  11810. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'isOpenJump', true)
  11811. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpEndTime', this.jumpEndTime)
  11812. PreferencesUtil.putSync(this.currentSong?.artist + 2 + 'jumpTopTime', this.jumpTopTime)
  11813. }
  11814. } else if (this.modeType === 3) { //专辑
  11815. if (this.currentSong?.album) {
  11816. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'isOpenJump', true)
  11817. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpEndTime', this.jumpEndTime)
  11818. PreferencesUtil.putSync(this.currentSong?.album + 3 + 'jumpTopTime', this.jumpTopTime)
  11819. }
  11820. }
  11821. ToastUtil.showShort("保存成功")
  11822. this.isJumpSetting = false
  11823. })
  11824. }
  11825. .margin({
  11826. left: 38,
  11827. right: 38,
  11828. top: 10,
  11829. bottom: 10
  11830. })
  11831. .width(120)
  11832. .height(50)
  11833. }
  11834. }
  11835. }
  11836. .width('100%')
  11837. .height('100%')
  11838. }
  11839. // 应用可以通过onStateChange接口监听组件显示/消失状态,当组件显示时建议不要销毁AVCastPicker的显示;当组件消失时,再根据业务隐藏AVCastPicker。
  11840. private onStateVastChange(state: AVCastPickerState) {
  11841. if (state == AVCastPickerState.STATE_APPEARING) {
  11842. console.log('The picker starts showing.');
  11843. } else if (state == AVCastPickerState.STATE_DISAPPEARING) {
  11844. console.log('The picker finishes presenting.');
  11845. }
  11846. }
  11847. private showSelectLyric() {
  11848. DialogHelper.showActionSheetDialog({
  11849. title: '温馨提醒:\n1.歌词文件名必须和目标歌曲文件名相同\n2.歌词文件和目标歌曲要同个歌单路径。',
  11850. // sheets: ["本地歌词", "搜索歌词"],
  11851. sheets: [
  11852. { value: "本地歌词", fontColor: $r('app.color.text_color') },
  11853. { value: "搜索歌词", fontColor: $r('app.color.text_color') },
  11854. ],
  11855. maskColor: Color.Transparent,
  11856. backgroundColor: $r('app.color.bg_card'),
  11857. transition: AnimationHelper.transitionInDown(666),
  11858. onAction: (index) => {
  11859. switch (index) {
  11860. case 0:
  11861. this.callFilePickerSelectFileForLyric()
  11862. break;
  11863. case 1:
  11864. if (StrUtil.isNotEmpty(this.videoUrl)) {
  11865. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  11866. this.initLyric(lyricPath);
  11867. }
  11868. break;
  11869. }
  11870. }
  11871. })
  11872. }
  11873. // 拉起picker选择文件管理器
  11874. async callFilePickerSelectFileForLyric(): Promise<void> {
  11875. try {
  11876. let DocumentSelectOptions = new picker.DocumentSelectOptions();
  11877. DocumentSelectOptions.maxSelectNumber = 1
  11878. DocumentSelectOptions.fileSuffixFilters = CommonConstants.LYRIC_FORMAT
  11879. let documentPicker = new picker.DocumentViewPicker();
  11880. documentPicker.select(DocumentSelectOptions).then((DocumentSelectResult) => {
  11881. Logger.info(TAG,
  11882. 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(DocumentSelectResult));
  11883. if (DocumentSelectResult !== null && DocumentSelectResult !== undefined) {
  11884. this.saveVideoDatasLyric(DocumentSelectResult)
  11885. }
  11886. }).catch((err: BusinessError) => {
  11887. Logger.error(TAG, 'DocumentViewPicker.select failed with err: ' + JSON.stringify(err));
  11888. });
  11889. } catch (err) {
  11890. Logger.error(TAG, 'DocumentViewPicker failed with err: ' + JSON.stringify(err));
  11891. }
  11892. }
  11893. async saveVideoDatasLyric(uris: string[]) {
  11894. if (ArrayUtil.isEmpty(uris)) {
  11895. return
  11896. }
  11897. let newUris: string[] = [];
  11898. for (let i = 0; i < uris.length; i++) {
  11899. let filePath = getContext(this).filesDir + '/' + Utility.getMediaNameByUri(uris[i])
  11900. Logger.info(TAG, 'filePath uri: ' + filePath);
  11901. newUris.push(filePath)
  11902. let file = fileIo.openSync(uris[i], fileIo.OpenMode.READ_ONLY)
  11903. let file2 = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
  11904. fileIo.copyFileSync(file.fd, file2.fd)
  11905. fileIo.closeSync(file);
  11906. fileIo.closeSync(file2);
  11907. this.initLyric(filePath,false,false,true)
  11908. }
  11909. }
  11910. private initDelayPlay(context: object) {
  11911. this.mContext = context;
  11912. }
  11913. startPipLyric() {
  11914. if (this.pipController) {
  11915. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  11916. PiPWindow.PiPControlStatus.PLAY);
  11917. }
  11918. this.isOpenPip = PreferencesUtil.getBooleanSync('isOpenPip', false)
  11919. if (this.isOpenPip) {
  11920. this.startPip()
  11921. } else {
  11922. this.stopPip()
  11923. }
  11924. }
  11925. //startOffset 从cue分轨时间开始播
  11926. private startPlayOrResumePlay(startOffset?:number) {
  11927. //针对dsf文件高采样率,统一转wav播放
  11928. const sampleRate = this.currentSong?.sampleRate||0
  11929. if(this.videoUrl.toLowerCase().endsWith('.dsf')&&sampleRate>=441000){
  11930. console.info('onecold 采样率 ='+sampleRate)
  11931. let newDsfPath = this.context.filesDir + '/'+FileUtil.getFileName(this.videoUrl)+'.wav'
  11932. console.info('onecold newDsfPath ='+newDsfPath)
  11933. if(!FileUtil.accessSync(newDsfPath)){
  11934. const task = new taskpool.Task(convertDsfToWav,this.videoUrl,newDsfPath);
  11935. taskpool.execute(task, taskpool.Priority.HIGH).then((data)=>{
  11936. this.videoUrl = newDsfPath
  11937. this.startPlay(startOffset)
  11938. }).catch((e:object)=>{
  11939. console.info("task1 catch e: " + e);
  11940. })
  11941. }else{
  11942. this.videoUrl = newDsfPath
  11943. this.startPlay(startOffset)
  11944. }
  11945. }else{
  11946. this.startPlay(startOffset)
  11947. }
  11948. }
  11949. startPlay(startOffset?:number) {
  11950. this.startPipLyric()
  11951. this.mDestroyPage = false;
  11952. this.animationState = AnimationStatus.Running
  11953. LogUtils.getInstance().LOGI("onecold startPlayOrResumePlay start this.CONTROL_PlayStatus:" + this.CONTROL_PlayStatus)
  11954. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  11955. this.stopProgressTask();
  11956. this.startProgressTask();
  11957. this.play(this.videoUrl.toString(),startOffset);
  11958. }
  11959. if (this.CONTROL_PlayStatus == PlayStatus.PAUSE) {
  11960. this.mIjkMediaPlayer.start();
  11961. this.setProgress()
  11962. this.CONTROL_PlayStatus = PlayStatus.PLAY
  11963. }
  11964. this.setIsPlaying(true)
  11965. this.updateSessionPlayState(true)
  11966. this.watchStatus();
  11967. this.updateLastPlayTimeStr(this.videoUrl)
  11968. }
  11969. updateLastPlayTimeStr(filePath: string) {
  11970. // 检查是否为网络音频(WebDAV),如果是则不更新本地数据库
  11971. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  11972. Logger.info(`heanup 检测到网络音频播放,跳过数据库更新: ${filePath}`)
  11973. return;
  11974. }
  11975. let lastPlayTime = DateUtil.getTodayStr('yyyy-MM-dd HH:mm:ss')
  11976. this.table.updateLastPlayedStrByFilePath(filePath, lastPlayTime, (success: boolean, error?: string) => {
  11977. if (success) {
  11978. this.getHistoryList(false)
  11979. console.log(" onecold 更新最近播放时间成功,数据库已同步");
  11980. } else {
  11981. console.error(" onecold 更新最近播放时间数据库失败原因: " + error);
  11982. }
  11983. });
  11984. }
  11985. private completionNum(num: number): string | number {
  11986. if (num < 10) {
  11987. return '0' + num;
  11988. } else {
  11989. return num;
  11990. }
  11991. }
  11992. private stringForTime(timeMs: number): string {
  11993. let totalSeconds: number | string = (timeMs / 1000);
  11994. let newSeconds: number | string = totalSeconds % 60;
  11995. let minutes: number | string = (totalSeconds / 60) % 60;
  11996. let hours: number | string = totalSeconds / 3600;
  11997. //LogUtils.getInstance().LOGI("stringForTime hours:" + hours + ",minutes:" + minutes + ",seconds:" + newSeconds);
  11998. hours = this.completionNum(Math.floor(Math.floor(hours * 100) / 100));
  11999. minutes = this.completionNum(Math.floor(Math.floor(minutes * 100) / 100));
  12000. newSeconds = Math.floor(Math.floor(newSeconds * 100) / 100)
  12001. if (this.isCurrentTime) {
  12002. if (this.oldSeconds < newSeconds || newSeconds === 0 || this.isSeekTo) {
  12003. this.oldSeconds = newSeconds
  12004. } else {
  12005. newSeconds = this.oldSeconds
  12006. }
  12007. }
  12008. newSeconds = this.completionNum(newSeconds);
  12009. if (hours > 0) {
  12010. return hours + ":" + minutes + ":" + newSeconds;
  12011. } else {
  12012. return minutes + ":" + newSeconds;
  12013. }
  12014. }
  12015. private setProgress() {
  12016. let position = this.mIjkMediaPlayer.getCurrentPosition();
  12017. let duration = this.mIjkMediaPlayer.getDuration();
  12018. let pos = 0;
  12019. if (duration > 0) {
  12020. this.slideEnable = true;
  12021. let curPercent = position / duration;
  12022. pos = curPercent * 100;
  12023. if (pos > this.PROGRESS_MAX_VALUE) {
  12024. this.progressValue = this.PROGRESS_MAX_VALUE
  12025. } else {
  12026. this.progressValue = pos;
  12027. }
  12028. }
  12029. // LogUtils.getInstance()
  12030. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  12031. this.totalTime = this.stringForTime(duration);
  12032. if (position > duration) {
  12033. position = duration;
  12034. }
  12035. this.isCurrentTime = true;
  12036. this.lyricController.updatePosition(position + this.timeOffset * 1000)
  12037. this.lyricControllerXF.updatePosition(position + this.timeOffset * 1000)
  12038. this.lyricControllerSingle.updatePosition(position + this.timeOffset * 1000)
  12039. this.currentTime = this.stringForTime(position);
  12040. this.isCurrentTime = false
  12041. if (this.mIjkMediaPlayer.isPlaying()) {
  12042. this.randomColor =
  12043. `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
  12044. //如果是开启AB循环
  12045. if(this.isOpenAB){
  12046. if(position >=this.jumpBTime){
  12047. this.seekTo(this.jumpATime+'')
  12048. return
  12049. }
  12050. }
  12051. // 判断是否播放到结束时间
  12052. if (this.isOpenJump && duration > this.jumpEndTime * 1000) {
  12053. if (position >= duration - this.jumpEndTime * 1000) {
  12054. if(this.playType == 1){//跳过尾部如果是单曲循环就选择单曲循环
  12055. this.CONTROL_PlayStatus = PlayStatus.INIT
  12056. this.startPlayOrResumePlay();
  12057. }else if (this.playType == 2) { //2:正常播放,单曲播完
  12058. this.showRePlay();
  12059. this.currentTime = this.stringForTime(this.mIjkMediaPlayer.getDuration());
  12060. this.progressValue = this.PROGRESS_MAX_VALUE;
  12061. this.slideEnable = false;
  12062. this.stop();
  12063. // ToastUtil.showToast('开始重新播放')
  12064. }else{
  12065. this.playNext().catch(() => {
  12066. Logger.error('heanup setProgress playNext', `播放下一首失败`);
  12067. });
  12068. }
  12069. }
  12070. }
  12071. } else {
  12072. this.randomColor = 'rbg(0,0,0)'
  12073. }
  12074. }
  12075. private startProgressTask() {
  12076. let that = this;
  12077. this.updateProgressTimer = setInterval(() => {
  12078. //LogUtils.getInstance().LOGI("startProgressTask");
  12079. if (!that.mDestroyPage) {
  12080. that.setProgress();
  12081. }
  12082. }, 300);
  12083. }
  12084. private stopProgressTask() {
  12085. LogUtils.getInstance().LOGI("stopProgressTask");
  12086. clearInterval(this.updateProgressTimer);
  12087. }
  12088. private showLoadIng() {
  12089. this.loadingVisible = Visibility.Visible;
  12090. this.replayVisible = Visibility.None;
  12091. }
  12092. private hideLoadIng() {
  12093. this.loadingVisible = Visibility.None;
  12094. this.replayVisible = Visibility.None;
  12095. }
  12096. private showRePlay() {
  12097. this.loadingVisible = Visibility.None;
  12098. this.replayVisible = Visibility.Visible;
  12099. }
  12100. private async play(url: string,startOffset?:number) {
  12101. this.isShowBgLiuGUANG = PreferencesUtil.getBooleanSync('isShowBgLiuGUANG', true)
  12102. console.info('onecold this.url 1= '+url)
  12103. if(!url.toLowerCase().startsWith('http')){
  12104. let hasPermission = await PermissionUtil.activatePermission(url)
  12105. console.info('onecold this.hasPermission 1= '+hasPermission)
  12106. if(!url.includes(this.packName)){
  12107. const file = fs.openSync(url)
  12108. this.videoUrl = file.path
  12109. url= this.videoUrl
  12110. }
  12111. console.info('onecold this.hasPermission 1= '+hasPermission)
  12112. console.info('onecold this.videoUrl 1= '+this.videoUrl)
  12113. }
  12114. let that = this;
  12115. that.showLoadIng();
  12116. this.isOpenAB = false
  12117. //设置XComponent回调的context
  12118. if (!!this.mContext) {
  12119. this.mIjkMediaPlayer.setContext(this.mContext, 'xcomponentId');
  12120. }
  12121. if (this.CONTROL_PlayStatus == PlayStatus.INIT) {
  12122. this.mIjkMediaPlayer.reset();
  12123. }
  12124. this.CONTROL_PlayStatus = PlayStatus.PLAY;
  12125. //设置debug模式
  12126. this.mIjkMediaPlayer.setDebug(false);
  12127. //初始化配置
  12128. this.mIjkMediaPlayer.native_setup();
  12129. // 初始化配置后需要重新设置音频流音量,否则音量为默认值1.0 针对dsf格式设置最大值1.0
  12130. if(this.volumeSmall){
  12131. if(this.videoUrl.toLowerCase().endsWith('.dsf')){
  12132. this.mIjkMediaPlayer.setVolume('1', '1');
  12133. }else{
  12134. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  12135. }
  12136. }else{
  12137. this.mIjkMediaPlayer.setVolume(this.volume.toString(), this.volume.toString());
  12138. }
  12139. //设置视频源
  12140. this.mIjkMediaPlayer.setDataSource(url);
  12141. // 构建规范的HTTP请求头(统一一次性设置,避免未带认证提前发起连接)
  12142. const headers = new Map<string, string>();
  12143. headers.set("User-Agent", "TTMusic-WebDAV/1.0");
  12144. headers.set("Accept", "*/*");
  12145. if (this.currentSong&&StrUtil.isEmpty(this.currentSong.pixelMapPath)
  12146. &&PreferencesUtil.getStringSync('COVER_API', '') != '') {
  12147. //如果封面为空,则搜索封面
  12148. this.searchCover(this.currentSong, this.currentSong.name, this.currentSong.artist||'')
  12149. }
  12150. // 如果是WebDAV网络音频,使用webdav_account_id获取认证信息(等待完成后再设置一次性头部)
  12151. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  12152. Logger.info(`heanup WebDAV歌曲认证 - 歌曲名: ${this.currentSong.name}, webdav_account_id: ${this.currentSong.webdav_account_id || '未设置'}`);
  12153. if (this.currentSong.webdav_account_id) {
  12154. try {
  12155. const webdavManager = RemoteDriveManager.getInstance();
  12156. const webDavHeaders = await webdavManager.buildHttpHeadersWithAccountId(this.currentSong, this.videoUrl);
  12157. if (webDavHeaders && webDavHeaders.size > 0) {
  12158. webDavHeaders.forEach((value, key) => headers.set(key, value));
  12159. Logger.info(`heanup 成功通过webdav_account_id获取并合并WebDAV认证头`);
  12160. } else {
  12161. Logger.warn(`heanup 通过webdav_account_id获取认证头失败,播放可能无法继续`);
  12162. }
  12163. } catch (error) {
  12164. const err = error as Error;
  12165. Logger.error(`heanup 获取WebDAV认证头时出错: ${err.message}`);
  12166. }
  12167. } else {
  12168. Logger.error(`heanup WebDAV歌曲 "${this.currentSong.name}" 缺少webdav_account_id,无法进行认证`);
  12169. }
  12170. }
  12171. // 统一设置带认证的请求头
  12172. this.mIjkMediaPlayer.setDataSourceHeader(headers);
  12173. if (this.currentSong && isRemoteCloudType(this.currentSong.type)) {
  12174. console.log(`heanup 为WebDAV播放设置IjkPlayer选项`);
  12175. // 网络超时设置(单位:微秒,文档显示应该是字符串格式)
  12176. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "30000000"); // 30秒
  12177. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "30000000"); // 连接超时30秒
  12178. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "listen_timeout", "30000000"); // 监听超时30秒
  12179. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "30000000"); // DNS缓存超时30秒
  12180. // 缓冲和播放优化设置
  12181. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", "1024000"); // 增大缓冲区
  12182. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "50"); // 减少最小帧数
  12183. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1"); // 预加载启动
  12184. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0"); // 无缓冲播放
  12185. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "30000"); // 最大缓存30秒
  12186. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1"); // 无限制收流
  12187. // 网络相关设置
  12188. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http_redirect", "1"); // 启用HTTP重定向
  12189. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "user_agent", "TTMusic-WebDAV/1.0"); // 用户代理
  12190. // 重连设置
  12191. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "reconnect", "3"); // 重连3次
  12192. console.log(`heanup WebDAV IjkPlayer选项设置完成`);
  12193. }
  12194. // if(PreferencesUtil.getBooleanSync(SettingPage.IS_MIDIACODEC_OPEN,false)){
  12195. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", "1"); // 启用硬件解码,会导致无法顺序播放
  12196. // }
  12197. this.isMusicBGCover = PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_BG_COVER, true)
  12198. //使用精确寻帧 例如,拖动播放后,会寻找最近的关键帧进行播放,很有可能关键帧的位置不是拖动后的位置,而是较前的位置.可以设置这个参数来解决问题
  12199. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", "1");
  12200. const fileSize = await this.getFileSize(this.videoUrl);
  12201. let bufferSize = 1 * 1024 ; // 默认缓冲区大小为1MB
  12202. if (fileSize > 3 * 1024 * 1024 * 1024) { // 文件大于3GB
  12203. bufferSize = 25 * 1024 * 1024; // 设置缓冲区大小为25MB
  12204. }
  12205. // 使用软件解码(通常比硬件解码更节省内存)
  12206. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", '0');
  12207. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", '0');
  12208. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "probesize", '1024');
  12209. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzeduration", '500000');
  12210. //预读数据的缓冲区大小.修复大文件播放前几秒挂掉的bug,太大了会导致倍数播放失效
  12211. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-buffer-size", bufferSize + '');
  12212. //停止预读的最小帧数
  12213. // this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100");
  12214. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "reconnect", '1'); ////重连模式,如果中途服务器断开了连接,让它重新连接
  12215. // 设置其他缓冲相关选项
  12216. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "min-frames", "100"); // 设置最小缓冲帧数
  12217. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max-frames", "1000"); // 设置最大缓冲
  12218. //启动预加载
  12219. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", "1");
  12220. // 设置无缓冲,这是播放器的缓冲区,有数据就播放
  12221. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", "0");
  12222. //跳帧处理,放CPU处理较慢时,进行跳帧处理,保证播放流程,画面和声音同步
  12223. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", "5");
  12224. // 最大缓冲cache是3s, 有时候网络波动,会突然在短时间内收到好几秒的数据
  12225. // 因此需要播放器丢包,才不会累积延时
  12226. // 这个和第三个参数packet-buffering无关。
  12227. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "max_cached_duration", "3000");
  12228. // 无限制收流
  12229. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1");
  12230. this.mIjkMediaPlayer.setOptionLong(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", "1")
  12231. // 屏幕常亮
  12232. this.mIjkMediaPlayer.setScreenOnWhilePlaying(true);
  12233. // 设置超时
  12234. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", "10000000");
  12235. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "connect_timeout", "10000000");
  12236. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "addrinfo_timeout", "10000000");
  12237. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", "10000000");
  12238. // 变速播放
  12239. this.mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", "1");
  12240. this.mIjkMediaPlayer.setSpeed(this.playSpeed + 'f');
  12241. let Speed = this.mIjkMediaPlayer.getSpeed()
  12242. LogUtils.getInstance().LOGI('getSpeed--' + Speed)
  12243. //是否开启循环播放
  12244. // this.mIjkMediaPlayer.setLoopCount(this.loop);
  12245. let mOnVideoSizeChangedListener: OnVideoSizeChangedListener = {
  12246. onVideoSizeChanged: (width: number, height: number, sar_num: number, sar_den: number) => {
  12247. if (height === 0) {
  12248. return;
  12249. }
  12250. const va = width / height;
  12251. const vpa = that.videoParentAspectRatio;
  12252. if (vpa > va) {
  12253. that.videoWidth = (width / (height * vpa)) * 100 + '%';
  12254. } else {
  12255. that.videoWidth = '100%';
  12256. }
  12257. if (width && height) {
  12258. that.videoAspectRatio = width / height;
  12259. }
  12260. LogUtils.getInstance()
  12261. .LOGI("setOnVideoSizeChangedListener-->go:" + width + "," + height + "," + sar_num + "," + sar_den);
  12262. that.hideLoadIng();
  12263. }
  12264. }
  12265. this.mIjkMediaPlayer.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
  12266. let mOnPreparedListener: OnPreparedListener = {
  12267. onPrepared: async () => {
  12268. LogUtils.getInstance().LOGI("setOnPreparedListener-->go");
  12269. try {
  12270. //保存碰一碰分享的当前的歌曲
  12271. AppStorage.setOrCreate('currentSong',this.currentSong) ;
  12272. let lyricPath = this.videoUrl.substring(0, this.videoUrl.lastIndexOf('.')) + '.lrc'
  12273. await this.initLyric(lyricPath);
  12274. setTimeout(() => {
  12275. this.avSessionController.initAvSession(false);
  12276. this.avSessionController.setAVMetadataMusic(this.songList[this.curIndex], this.duration, this.lyricContent);
  12277. this.setAvSessionListener();
  12278. this.updateSessionPlayState(true)
  12279. this.setCurrentPlayMode()
  12280. }, 500)
  12281. if(startOffset&&startOffset>0){//cue分轨播放
  12282. this.seekTo(startOffset + "");
  12283. this.saveLastPlayList()
  12284. return
  12285. }
  12286. //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12287. let timeoutPlay = 0
  12288. if (StrUtil.isNotEmpty(this.videoUrl) &&
  12289. (this.videoUrl.toLowerCase().endsWith('.rmvb') || this.videoUrl.toLowerCase().endsWith('.flac'))) {
  12290. timeoutPlay = 1000
  12291. }
  12292. //跳过片头片尾关键代码,以下是跳过片头的关键代码
  12293. if (this.modeType === 0) { //文件夹
  12294. let parentPath = FileUtil.getParentPath(this.videoUrl)
  12295. this.jumpTopTime = PreferencesUtil.getNumberSync(parentPath + 'jumpTopTime')
  12296. this.jumpEndTime = PreferencesUtil.getNumberSync(parentPath + 'jumpEndTime')
  12297. this.isOpenJump = PreferencesUtil.getBooleanSync(parentPath + 'isOpenJump', false)
  12298. } else if (this.modeType === 1) { //媒体库
  12299. this.jumpTopTime = PreferencesUtil.getNumberSync(1 + 'jumpTopTime')
  12300. this.jumpEndTime = PreferencesUtil.getNumberSync(1 + 'jumpEndTime')
  12301. this.isOpenJump = PreferencesUtil.getBooleanSync(1 + 'isOpenJump', false)
  12302. } else if (this.modeType === 2) { //艺术家
  12303. if (this.currentSong?.artist) {
  12304. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpTopTime')
  12305. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.artist + 2 + 'jumpEndTime')
  12306. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.artist + 2 + 'isOpenJump', false)
  12307. }
  12308. } else if (this.modeType === 3) { //专辑
  12309. if (this.currentSong?.album) {
  12310. this.jumpTopTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpTopTime')
  12311. this.jumpEndTime = PreferencesUtil.getNumberSync(this.currentSong?.album + 3 + 'jumpEndTime')
  12312. this.isOpenJump = PreferencesUtil.getBooleanSync(this.currentSong?.album + 3 + 'isOpenJump', false)
  12313. }
  12314. }
  12315. this.duration = this.mIjkMediaPlayer.getDuration()
  12316. if (this.isOpenJump) { //用户是否设置跳过片头片尾
  12317. if (this.mIjkMediaPlayer != null) {
  12318. let jumpTopTimeMs = this.jumpTopTime*1000;
  12319. if (jumpTopTimeMs <= this.duration) {
  12320. // 调用 seekTo 方法,跳到指定时间
  12321. if(PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY,true)){
  12322. console.log('onecold jumpTopTime = '+jumpTopTimeMs);
  12323. const position:number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  12324. console.log('onecold position = '+position);
  12325. if (position > jumpTopTimeMs) {
  12326. jumpTopTimeMs = position
  12327. }
  12328. }
  12329. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12330. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  12331. this.seekTo(this.jumpTopTime * 1000 + ""); // 跳到开头
  12332. }
  12333. }, timeoutPlay)
  12334. } else {
  12335. // 提示用户无法跳过
  12336. ToastUtil.showToast('跳过时间超过视频时长');
  12337. }
  12338. }
  12339. } else {
  12340. this.jumpTopTime = 0
  12341. this.jumpEndTime = 0
  12342. console.error('onecold 最后一首: isFirstStartPlay = ' + this.isFirstStartPlay);
  12343. console.error('onecold 最后一首: isMemoryLastPlay = ' + this.isMemoryLastPlay);
  12344. console.error('onecold 最后一首: PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false) = ' +
  12345. PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false));
  12346. //记忆播放(每一首都会记忆播放)
  12347. if (StrUtil.isNotEmpty(this.videoUrl) && !this.videoUrl.toLowerCase().endsWith('.ts')) {
  12348. setTimeout(() => { //rmvb和flac格式马上记忆播放会报错,会延迟1s在读取记忆播放。
  12349. if (PreferencesUtil.getBooleanSync(SettingPage.iS_MUSIC_MEMORY_PLAY, false)) {
  12350. this.restorePlaybackPosition() //读取播放记忆功能
  12351. } else if (this.isMemoryLastPlay && this.isFirstStartPlay) {
  12352. console.error('onecold 最后一首:读取播放记忆功能 = ' + this.isFirstStartPlay);
  12353. this.restorePlaybackPosition() //读取播放记忆功能
  12354. }
  12355. this.isFirstStartPlay = false
  12356. }, timeoutPlay)
  12357. } else {
  12358. this.isFirstStartPlay = false
  12359. }
  12360. }
  12361. this.saveLastPlayList()
  12362. } catch (error) {
  12363. let err: BusinessError = error as BusinessError;
  12364. console.error('onecold failed with err: ' + JSON.stringify(err));
  12365. }
  12366. }
  12367. }
  12368. this.mIjkMediaPlayer.setOnPreparedListener(mOnPreparedListener);
  12369. let mOnTimedTextListener: OnTimedTextListener = {
  12370. onTimedText: () => {
  12371. }
  12372. }
  12373. this.mIjkMediaPlayer.setOnTimedTextListener(mOnTimedTextListener)
  12374. let mOnCompletionListener: OnCompletionListener = {
  12375. onCompletion: () => {
  12376. LogUtils.getInstance().LOGI("OnCompletionListener-->go")
  12377. if (this.playType == 0) { //0:连续播放 1:单片重复播放 2:正常播放
  12378. // 异步调用playNext
  12379. this.playNext().catch(() => {
  12380. Logger.error('heanup OnCompletionListener playNext', `播放下一首失败`);
  12381. });
  12382. } else if (this.playType == 1) { //1:单片重复播放
  12383. this.CONTROL_PlayStatus = PlayStatus.INIT
  12384. that.startPlayOrResumePlay();
  12385. } else if (this.playType == 2) { //2:正常播放,单曲播完
  12386. that.showRePlay();
  12387. that.currentTime = that.stringForTime(this.mIjkMediaPlayer.getDuration());
  12388. that.progressValue = this.PROGRESS_MAX_VALUE;
  12389. that.slideEnable = false;
  12390. that.stop();
  12391. // ToastUtil.showToast('开始重新播放')
  12392. } else if (this.playType == 3) { //3:随机播放
  12393. // 异步调用randomPlay
  12394. this.randomPlay().catch(() => {
  12395. Logger.error('heanup OnCompletionListener randomPlay', `随机播放失败`);
  12396. });
  12397. }
  12398. }
  12399. }
  12400. this.mIjkMediaPlayer.setOnCompletionListener(mOnCompletionListener);
  12401. let mOnBufferingUpdateListener: OnBufferingUpdateListener = {
  12402. onBufferingUpdate: (percent: number) => {
  12403. LogUtils.getInstance().LOGI("OnBufferingUpdateListener-->go:" + percent);
  12404. let MediaInfo = this.mIjkMediaPlayer.getMediaInfo()
  12405. LogUtils.getInstance().LOGI('getMediaInfo---' + MediaInfo);
  12406. let VideoWidth = this.mIjkMediaPlayer.getVideoWidth()
  12407. LogUtils.getInstance().LOGI('getVideoWidth---' + VideoWidth);
  12408. let VideoHeight = this.mIjkMediaPlayer.getVideoHeight()
  12409. LogUtils.getInstance().LOGI('getVideoHeight---' + VideoHeight);
  12410. let VideoSarNum = this.mIjkMediaPlayer.getVideoSarNum()
  12411. LogUtils.getInstance().LOGI('getVideoSarNum---' + VideoSarNum);
  12412. let VideoSarDen = this.mIjkMediaPlayer.getVideoSarDen()
  12413. LogUtils.getInstance().LOGI('getVideoSarDen---' + VideoSarDen);
  12414. let AudioSessionId = this.mIjkMediaPlayer.getAudioSessionId()
  12415. LogUtils.getInstance().LOGI('getAudioSessionId---' + AudioSessionId);
  12416. let Looping = this.mIjkMediaPlayer.isLooping()
  12417. LogUtils.getInstance().LOGI('isLooping---' + Looping);
  12418. }
  12419. }
  12420. this.mIjkMediaPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
  12421. let mOnSeekCompleteListener: OnSeekCompleteListener = {
  12422. onSeekComplete: () => {
  12423. LogUtils.getInstance().LOGI("OnSeekCompleteListener-->go");
  12424. console.info('onecold startPlayOrResumePlay 10643')
  12425. that.startPlayOrResumePlay();
  12426. }
  12427. }
  12428. this.mIjkMediaPlayer.setOnSeekCompleteListener(mOnSeekCompleteListener);
  12429. let mOnInfoListener: OnInfoListener = {
  12430. onInfo: (what: number, extra: number) => {
  12431. LogUtils.getInstance().LOGI("OnInfoListener-->go:" + what + "===" + extra);
  12432. that.hideLoadIng();
  12433. }
  12434. }
  12435. this.mIjkMediaPlayer.setOnInfoListener(mOnInfoListener);
  12436. let mOnErrorListener: OnErrorListener = {
  12437. onError: (what: number, extra: number) => {
  12438. this.stopProgressTask();
  12439. LogUtils.getInstance().LOGI("heanup OnErrorListener-->go:" + what + "===" + extra + " this.videoUrl=" + this.videoUrl)
  12440. LogUtils.getInstance().LOGI('heanup 播放错误,歌曲详情:' + JSON.stringify(this.currentSong))
  12441. // 检查是否为WebDAV播放错误
  12442. let isWebDavError = false;
  12443. if (this.currentSong && isRemoteCloudType(this.currentSong.type) && this.currentSong.filePath) {
  12444. try {
  12445. const globalContext = GlobalContext.getContext();
  12446. const webDavAuthInfo = globalContext.getObject('webDavAuthInfo') as WebDavAuthItem;
  12447. if (webDavAuthInfo) {
  12448. isWebDavError = true;
  12449. }
  12450. } catch (error) {
  12451. console.error('OnErrorListener-->go: 获取WebDAV认证信息失败');
  12452. }
  12453. }
  12454. if (isWebDavError) {
  12455. Logger.error(`heanup WebDAV播放错误 - what: ${what}, extra: ${extra}, URL: ${this.videoUrl}`);
  12456. // 播放失败时清空实例变量中的WebDAV认证信息,防止错误账户持续使用
  12457. // this.currentWebDavAuthInfo = null;
  12458. Logger.info('heanup WebDAV播放失败,保留认证信息用于后续歌曲切换');
  12459. // 根据错误代码提供更具体的错误信息
  12460. let errorMessage = "WebDAV播放失败";
  12461. if (what === -1) { // 网络错误
  12462. errorMessage = "网络连接失败,请检查WebDAV服务器连接";
  12463. } else if (what === -1004) { // HTTP 404
  12464. errorMessage = "文件未找到,请检查WebDAV服务器上的文件";
  12465. } else if (what === -1001) { // 超时
  12466. errorMessage = "连接超时,请检查网络或WebDAV服务器状态";
  12467. } else if (what === -1003) { // 无法解析主机
  12468. errorMessage = "无法连接到WebDAV服务器";
  12469. }
  12470. ToastUtil.showToast(errorMessage);
  12471. } else {
  12472. if (StrUtil.isNotEmpty(this.videoUrl) &&
  12473. !this.videoUrl.startsWith('http://') &&
  12474. !this.videoUrl.startsWith('https://') &&
  12475. !FileUtil.accessSync(this.videoUrl)) {
  12476. ToastUtil.showToast(Utility.resourceToString(getContext(), $r('app.string.file_not_exist')))
  12477. } else {
  12478. ToastUtil.showToast(getContext()
  12479. .resourceManager
  12480. .getStringByNameSync("Honey_the_video_is_playing_errant_The_system_is_wandering"))
  12481. }
  12482. }
  12483. that.hideLoadIng();
  12484. }
  12485. }
  12486. this.mIjkMediaPlayer.setOnErrorListener(mOnErrorListener);
  12487. this.mIjkMediaPlayer.setMessageListener();
  12488. this.mIjkMediaPlayer.prepareAsync();
  12489. this.mIjkMediaPlayer.start();
  12490. }
  12491. //保存最后播放的那首歌和已经对应的播放列表
  12492. saveLastPlayList() {
  12493. PreferencesUtil.putSync('LastMusicInfo', this.currentSong)
  12494. PreferencesUtil.putSync('LastMusicList', this.songList)
  12495. }
  12496. // 清空播放记录
  12497. clearVideoHistory() {
  12498. this.table.clearPlayHistory((success: boolean, error?: string) => {
  12499. if (success) {
  12500. this.historyList = [];
  12501. this.updateListData(this.historyList)
  12502. // PreferencesUtil.putSync(LocalMusic.HISTORY_MUSIC, this.historyList)
  12503. ToastUtil.showToast('清空播放记录成功')
  12504. } else {
  12505. console.error(" onecold 清空播放记录数据库失败原因: " + error);
  12506. }
  12507. });
  12508. }
  12509. public async setAvSessionListener() {
  12510. if (!this.avSessionController) {
  12511. return;
  12512. }
  12513. this.avSessionController.getAvSession()?.on('play', this.sessionPlayCallback);
  12514. this.avSessionController.getAvSession()?.on('pause', this.sessionPauseCallback);
  12515. this.avSessionController.getAvSession()?.on('stop', this.sessionStopCallback);
  12516. this.avSessionController.getAvSession()?.on('playNext', this.sessionPlayNextCallback);
  12517. this.avSessionController.getAvSession()?.on('playPrevious', this.sessionPlayPreviousCallback);
  12518. this.avSessionController.getAvSession()?.on('fastForward', this.sessionFastForwardCallback);
  12519. this.avSessionController.getAvSession()?.on('rewind', this.sessionRewindCallback);
  12520. this.avSessionController.getAvSession()?.on('seek', this.sessionSeekCallback);
  12521. this.avSessionController.getAvSession()?.on('setLoopMode', this.sessionSetLoopModeCallback);
  12522. this.avSessionController.getAvSession()?.on('toggleFavorite', this.sessionToggleFavoriteCallback);
  12523. this.avSessionController.getAvSession()?.on('outputDeviceChange', this.sessionOutputDeviceChange)
  12524. }
  12525. setLoopMode() {
  12526. let itype = this.playType + 1
  12527. if (itype >= 4) {
  12528. this.playType = 0
  12529. ToastUtil.showToast('连续播放')
  12530. } else if (itype === 1) {
  12531. this.playType = 1
  12532. ToastUtil.showToast('单曲循环')
  12533. } else if (itype === 2) {
  12534. this.playType = 2
  12535. ToastUtil.showToast('单曲播完')
  12536. } else if (itype === 3) {
  12537. this.playType = 3
  12538. ToastUtil.showToast('随机播放')
  12539. } else if (itype === 0) {
  12540. this.playType = 0
  12541. ToastUtil.showToast('连续播放')
  12542. }
  12543. PreferencesUtil.putSync('musicPlayType', this.playType)
  12544. this.setCurrentPlayMode()
  12545. }
  12546. private sessionSetLoopModeCallback = (mode: number) => {
  12547. if (this.mIjkMediaPlayer != null) {
  12548. ToastUtil.showToast('当前播放模式:' + mode)
  12549. Logger.info('onecold 当前播放模式= ' + mode)
  12550. let hmPlayMode = mode + 1
  12551. if (hmPlayMode >= 4) {
  12552. hmPlayMode = 0
  12553. }
  12554. if (hmPlayMode === 1) {
  12555. this.playType = 1
  12556. ToastUtil.showToast('单曲循环')
  12557. } else if (hmPlayMode === 0) {
  12558. this.playType = 2
  12559. ToastUtil.showToast('单曲播完')
  12560. } else if (hmPlayMode === 3) {
  12561. this.playType = 3
  12562. ToastUtil.showToast('随机播放')
  12563. } else if (hmPlayMode === 2) {
  12564. this.playType = 0
  12565. ToastUtil.showToast('连续播放')
  12566. }
  12567. PreferencesUtil.putSync('musicPlayType', this.playType)
  12568. // 应用收到设置循环模式的指令后,应用自定下一个模式,切换完毕后通过AVPlaybackState上报切换后的LoopMode。
  12569. let playBackState: avSession.AVPlaybackState = {
  12570. loopMode: hmPlayMode,
  12571. };
  12572. this.avSessionController.getAvSession()?.setAVPlaybackState(playBackState).then(() => {
  12573. console.info(`set setLoopMode AVPlaybackState successfully`);
  12574. }).catch((err: BusinessError) => {
  12575. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  12576. });
  12577. }
  12578. }
  12579. setCurrentPlayMode() {
  12580. if (!this.avSessionController) {
  12581. return;
  12582. }
  12583. let mLoopMode = 0
  12584. switch (this.playType) {
  12585. case 0:
  12586. mLoopMode = avSession.LoopMode.LOOP_MODE_LIST //连续播放
  12587. break;
  12588. case 1:
  12589. mLoopMode = avSession.LoopMode.LOOP_MODE_SINGLE //单曲
  12590. break;
  12591. case 2:
  12592. mLoopMode = avSession.LoopMode.LOOP_MODE_SEQUENCE //正常播放
  12593. break;
  12594. case 3:
  12595. mLoopMode = avSession.LoopMode.LOOP_MODE_SHUFFLE //随机播放
  12596. break;
  12597. }
  12598. // 应用启动时/内部切换循环模式,需要把应用内的当前的循环模式设置给AVSession。
  12599. let playBState: avSession.AVPlaybackState = {
  12600. loopMode: mLoopMode,
  12601. isFavorite: Utility.getIsFav(this.favList, this.currentSong),
  12602. };
  12603. this.avSessionController.getAvSession()?.setAVPlaybackState(playBState).then(() => {
  12604. console.info(`set setLoopMode AVPlaybackState successfully`);
  12605. }).catch((err: BusinessError) => {
  12606. console.error(`Failed to setLoopMode set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
  12607. });
  12608. }
  12609. private sessionToggleFavoriteCallback = (assetId: string) => {
  12610. if (this.mIjkMediaPlayer != null && this.currentSong) {
  12611. console.info(`on toggleFavorite `);
  12612. // 应用收到收藏命令,进行收藏处理。
  12613. this.isFac = Utility.getIsFav(this.favList, this.currentSong)
  12614. this.doFav(this.currentSong)
  12615. // 应用内完成或者取消收藏,把新的收藏状态设置给AVSession。
  12616. let playbackState: avSession.AVPlaybackState = {
  12617. isFavorite: !this.isFac,
  12618. };
  12619. this.avSessionController.getAvSession()?.setAVPlaybackState(playbackState).then(() => {
  12620. console.info(`SetAVPlaybackState successfully`);
  12621. }).catch((err: BusinessError) => {
  12622. console.info(`SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  12623. });
  12624. }
  12625. }
  12626. private sessionOutputDeviceChange = async (connectState: avSession.ConnectionState,
  12627. device: avSession.OutputDeviceInfo) => {
  12628. let currentDevice: avSession.DeviceInfo = device?.devices?.[0];
  12629. if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  12630. connectState === avSession.ConnectionState.STATE_CONNECTED) {
  12631. await this.startCasting();
  12632. } else if ((currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE &&
  12633. connectState === avSession.ConnectionState.STATE_DISCONNECTED) ||
  12634. (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL &&
  12635. connectState === avSession.ConnectionState.STATE_CONNECTED)) {
  12636. if (device) {
  12637. this.endCasting();
  12638. }
  12639. }
  12640. };
  12641. private async startCasting() {
  12642. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  12643. this.setPlaybackStateChangeListener();
  12644. this.pause();
  12645. this.initQueueItem();
  12646. this.prepare();
  12647. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  12648. refToIsCasting?.set(true);
  12649. this.castSeek = true;
  12650. this.isCastPlaying = true;
  12651. }
  12652. async changeCasting() {
  12653. this.castController = await this.avSessionController.getAvSession()?.getAVCastController();
  12654. this.initQueueItem();
  12655. this.prepare();
  12656. this.setPlaybackStateChangeListener();
  12657. this.isCastPlaying = true;
  12658. this.castSeek = true;
  12659. }
  12660. public endCasting() {
  12661. this.avSessionController.getAvSession()?.stopCasting();
  12662. this.stopCast();
  12663. this.isCastPlaying = false;
  12664. let refToIsCasting: AbstractProperty<boolean> | undefined = AppStorage.ref('isCasting');
  12665. refToIsCasting?.set(false);
  12666. this.pause();
  12667. this.setIsPlaying(false);
  12668. // if (this.curIndex === this.curSource.index) {
  12669. // this.play
  12670. // this.seek(this.currentTime * 1000);
  12671. // this.setIsPlaying(true);
  12672. // } else {
  12673. // this.pauseVideo();
  12674. // this.setIsPlaying(false);
  12675. // }
  12676. }
  12677. public setIsPlaying(isPlayer: boolean) {
  12678. this.isPlaying = isPlayer;
  12679. // 发送播放状态变化事件给歌单详情页面
  12680. try {
  12681. const eventPlaybackStatus: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYBACK_STATUS }
  12682. const currentFilePath = this.currentSong?.filePath || ''
  12683. const eventData: emitter.EventData = {
  12684. data: {
  12685. isPlaying: this.isPlaying,
  12686. curIndex: this.curIndex,
  12687. currentFilePath: currentFilePath
  12688. }
  12689. };
  12690. emitter.emit(eventPlaybackStatus, eventData)
  12691. Logger.info(`heanup 发送播放状态变化事件: isPlaying=${this.isPlaying}, curIndex=${this.curIndex}, currentFilePath=${currentFilePath}`)
  12692. } catch (error) {
  12693. Logger.error('heanup 发送播放状态变化事件失败: ' + error)
  12694. }
  12695. }
  12696. private setPlaybackStateChangeListener(): void {
  12697. this.castController?.on('playbackStateChange', 'all', this.playbackStateChangeListener);
  12698. this.castController?.on('endOfStream', this.reloadCasting);
  12699. this.castController?.on('playNext', this.playNextCallback);
  12700. this.castController?.on('playPrevious', this.playPreviousCallback);
  12701. }
  12702. private updateSessionPlayState(isPlay: boolean): void {
  12703. // if(!this.isBgPlayOpen)
  12704. // return
  12705. Logger.info(TAG, `updateIsPlay isPlay: ${isPlay}`);
  12706. this.setAVSessionPlayState({
  12707. state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : avSession.PlaybackState.PLAYBACK_STATE_PAUSE,
  12708. position: {
  12709. elapsedTime: this.mIjkMediaPlayer.getCurrentPosition(),
  12710. updateTime: new Date().getTime()
  12711. }
  12712. });
  12713. }
  12714. private setAVSessionPlayState(playbackState: avSession.AVPlaybackState): void {
  12715. this.avSessionController.setAvSessionPlayState(playbackState)
  12716. }
  12717. private positionChange(position: number) {
  12718. this.currentTime2 = position / 1000;
  12719. this.currentStringTime = secondToTime(Math.floor(position / 1000));
  12720. }
  12721. private playDurationChange(duration: number) {
  12722. this.duration = duration;
  12723. this.durationTime = Math.floor(this.duration / 1000);
  12724. this.durationStringTime = secondToTime((this.durationTime));
  12725. }
  12726. private playbackStateChangeListener = (playbackState: avSession.AVPlaybackState) => {
  12727. const duration = playbackState?.extras?.duration;
  12728. if (typeof duration === 'number') {
  12729. this.playDurationChange(duration as number);
  12730. }
  12731. if (typeof playbackState?.position?.elapsedTime !== 'undefined') {
  12732. this.positionChange(playbackState?.position?.elapsedTime);
  12733. }
  12734. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PAUSE ||
  12735. playbackState.state === CommonConstants2.PLAYBACK_STATE_STOP ||
  12736. playbackState.state === CommonConstants2.PLAYBACK_STATE_PREPARE ||
  12737. playbackState.state === CommonConstants2.PLAYBACK_STATE_INITIAL) {
  12738. this.isCastPlaying = false;
  12739. }
  12740. if (playbackState.state === CommonConstants2.PLAYBACK_STATE_PLAY) {
  12741. this.isCastPlaying = true;
  12742. }
  12743. };
  12744. private reloadCasting = async () => {
  12745. let item = this.songList[this.curIndex];
  12746. let uri = fileUri.getUriFromPath(item.filePath);
  12747. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  12748. // description.startPosition = 0;
  12749. this.castItem = {
  12750. itemId: this.curIndex,
  12751. description: {
  12752. assetId: item.filePath,
  12753. title: item.name,
  12754. artist: '',
  12755. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  12756. // mediaUri: item.filePath,
  12757. fdSrc: {
  12758. fd: file.fd
  12759. },
  12760. // 该字段大写,音频'AUDIO',视频'VIDEO'
  12761. mediaType: 'VIDEO',
  12762. mediaSize: item.videoSize,
  12763. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  12764. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  12765. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  12766. duration: this.duration,
  12767. // albumCoverUri: 'https://www.example.jpeg',
  12768. // albumTitle: '《ExampleAlbum》',
  12769. appName: this.appName,
  12770. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  12771. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  12772. }
  12773. };
  12774. this.prepare();
  12775. this.isCastPlaying = true;
  12776. };
  12777. public playNextCallback = (): void => {
  12778. this.playNext().catch(() => {
  12779. Logger.error('heanup playNextCallback', `播放下一首失败`);
  12780. });
  12781. };
  12782. public playPreviousCallback = (): void => {
  12783. this.playPrevious().catch(() => {
  12784. Logger.error('heanup playNextCallback', `播放上一首失败`);
  12785. });
  12786. };
  12787. async prepare() {
  12788. await this.castController?.prepare(this.castItem);
  12789. await this.castController?.start(this.castItem);
  12790. }
  12791. public initQueueItem() {
  12792. let item = this.songList[this.curIndex];
  12793. let time = this.currentTime;
  12794. let uri = fileUri.getUriFromPath(item.filePath);
  12795. let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  12796. this.castItem = {
  12797. itemId: this.curIndex,
  12798. description: {
  12799. assetId: item.filePath,
  12800. title: item.name,
  12801. artist: '',
  12802. // 网络资源投播,设置mediaUri; 本地资源投播,将本地文件打开后,相关的文件描述符设置到fdSrc
  12803. fdSrc: {
  12804. fd: file.fd
  12805. },
  12806. // 该字段大写,音频'AUDIO',视频'VIDEO'
  12807. mediaType: 'AUDIO',
  12808. mediaSize: item.videoSize,
  12809. //startPosition为投播当前进度,设置该字段可将本机播放进度同步到远端
  12810. startPosition: this.mIjkMediaPlayer.getCurrentPosition(),
  12811. // 投播资源播放时长,设置该字段可将本机播放时长同步到远端显示
  12812. duration: this.duration,
  12813. // albumCoverUri: 'https://www.example.jpeg',
  12814. // albumTitle: '《ExampleAlbum》',
  12815. appName: this.appName,
  12816. // DRM资源,需要配置支持的DRM类型, 以chinaDRM为例。
  12817. // drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c',
  12818. }
  12819. };
  12820. }
  12821. async stopCast() {
  12822. try {
  12823. this.castController?.off('playbackStateChange');
  12824. this.castController?.off('endOfStream');
  12825. this.castController?.off('playNext');
  12826. this.castController?.off('playPrevious');
  12827. this.castController?.off('error');
  12828. } catch (error) {
  12829. hilog.info(0x0000, TAG, `Failed to setAVCastController. code: ${error.code}, message: ${error.message}`);
  12830. }
  12831. }
  12832. private sessionPlayCallback = (): void => {
  12833. this.playOrPause()
  12834. };
  12835. private sessionPauseCallback = (): void => {
  12836. this.pause()
  12837. };
  12838. private playOrPause() {
  12839. if (!this.debounce()) {
  12840. return;
  12841. }
  12842. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  12843. this.pause();
  12844. } else {
  12845. console.info('onecold startPlayOrResumePlay 11064')
  12846. this.startPlayOrResumePlay();
  12847. this.playChange()
  12848. }
  12849. }
  12850. private sessionPlayNextCallback = (): void => {
  12851. this.playNext().catch(() => {
  12852. Logger.error('heanup sessionPlayPreviousCallback', `播放下 一首失败`);
  12853. });
  12854. };
  12855. private sessionPlayPreviousCallback = (): void => {
  12856. this.playPrevious().catch(() => {
  12857. Logger.error('heanup sessionPlayPreviousCallback', `播放上一首失败`);
  12858. });
  12859. };
  12860. private sessionStopCallback = (): void => {
  12861. this.stop()
  12862. };
  12863. private sessionFastForwardCallback = (time?: number) => {
  12864. if (!time) {
  12865. return;
  12866. }
  12867. if (this.mIjkMediaPlayer != null) {
  12868. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  12869. let seeTime = curPosition + time * 1000;
  12870. // 限制 seekValue 在合法范围内
  12871. if (seeTime < 0) {
  12872. seeTime = 0;
  12873. } else if (seeTime > this.duration) {
  12874. seeTime = this.duration;
  12875. }
  12876. Logger.info('onecold seeTime= ' + seeTime)
  12877. this.setSeekToActionProgress(seeTime)
  12878. this.seekTo(seeTime + "")
  12879. }
  12880. };
  12881. /**
  12882. * Gesture method onActionUpdate.
  12883. *
  12884. * @param event Gesture event.手势拖动设置快进和后退
  12885. */
  12886. private setSeekToActionProgress(position: number) {
  12887. // let position = this.mIjkMediaPlayer.getCurrentPosition();
  12888. let duration = this.mIjkMediaPlayer.getDuration();
  12889. let pos = 0;
  12890. if (duration > 0) {
  12891. this.slideEnable = true;
  12892. let curPercent = position / duration;
  12893. pos = curPercent * 100;
  12894. if (pos > this.PROGRESS_MAX_VALUE) {
  12895. this.progressValue = this.PROGRESS_MAX_VALUE
  12896. } else {
  12897. this.progressValue = pos;
  12898. }
  12899. }
  12900. // LogUtils.getInstance()
  12901. // .LOGI("setProgress position:" + position + ",duration:" + duration + ",progressValue:" + pos);
  12902. this.totalTime = this.stringForTime(duration);
  12903. if (position > duration) {
  12904. position = duration;
  12905. }
  12906. this.isCurrentTime = true;
  12907. this.currentTime = this.stringForTime(position);
  12908. this.isCurrentTime = false
  12909. }
  12910. private sessionRewindCallback = (time?: number) => {
  12911. if (!time) {
  12912. return;
  12913. }
  12914. if (this.mIjkMediaPlayer != null) {
  12915. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  12916. let seeTime = curPosition - time * 1000;
  12917. // 限制 seekValue 在合法范围内
  12918. if (seeTime < 0) {
  12919. seeTime = 0;
  12920. } else if (seeTime > this.duration) {
  12921. seeTime = this.duration;
  12922. }
  12923. Logger.info('onecold seeTime= ' + seeTime)
  12924. this.setSeekToActionProgress(seeTime)
  12925. this.seekTo(seeTime + "")
  12926. }
  12927. };
  12928. private sessionSeekCallback = (seekTime: number) => {
  12929. if (this.mIjkMediaPlayer != null) {
  12930. const curPosition = this.mIjkMediaPlayer.getCurrentPosition()
  12931. this.seekTo(seekTime + "")
  12932. }
  12933. };
  12934. private async getFileSize(filePath: string): Promise<number> {
  12935. try {
  12936. const stat = await fs.stat(filePath);
  12937. return stat.size;
  12938. } catch (err) {
  12939. console.error('Failed to get file size: ' + err.message);
  12940. return 0;
  12941. }
  12942. }
  12943. private pause() {
  12944. if (this.mIjkMediaPlayer.isPlaying()) {
  12945. this.savePlaybackPosition();
  12946. this.mIjkMediaPlayer.pause();
  12947. this.setProgress();
  12948. this.mDestroyPage = true;
  12949. this.CONTROL_PlayStatus = PlayStatus.PAUSE;
  12950. this.updateSessionPlayState(false)
  12951. this.playChange()
  12952. if (this.pipController) {
  12953. this.pipController.updatePiPControlStatus(PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE,
  12954. PiPWindow.PiPControlStatus.PAUSE);
  12955. }
  12956. }
  12957. }
  12958. private stop() {
  12959. this.savePlaybackPosition();
  12960. this.CONTROL_PlayStatus = PlayStatus.INIT;
  12961. this.mIjkMediaPlayer.stop();
  12962. this.mIjkMediaPlayer.release();
  12963. this.stopProgressTask();
  12964. this.updateSessionPlayState(false)
  12965. this.playChange()
  12966. this.watchStatus();
  12967. }
  12968. //保持记忆播放功能
  12969. private savePlaybackPosition() {
  12970. if (this.mIjkMediaPlayer != null) {
  12971. const position = this.mIjkMediaPlayer.getCurrentPosition();
  12972. // ToastUtil.showToast('保存记忆播放 = ' + position)
  12973. const duration = this.mIjkMediaPlayer.getDuration();
  12974. const threshold = 5000; // 阈值,单位为毫秒(这里设为5秒)
  12975. // 如果播放位置接近视频末尾,则保存 position 为 0
  12976. const playbackPosition = (duration - position < threshold) ? 0 : position;
  12977. PreferencesUtil.putSync(this.videoUrl, playbackPosition);
  12978. }
  12979. }
  12980. //获取记忆播放功能
  12981. private restorePlaybackPosition() {
  12982. const position: number = PreferencesUtil.getNumberSync(this.videoUrl, 0);
  12983. // ToastUtil.showToast('position = ' + position)
  12984. if (this.mIjkMediaPlayer != null && position > 0) {
  12985. // ToastUtil.showToast('seekTo = ' + position)
  12986. this.seekTo(position + "");
  12987. }
  12988. }
  12989. private seekTo(value: string) {
  12990. if (StrUtil.isNotEmpty(this.videoUrl) && this.videoUrl.toLowerCase().endsWith('.wma')) {
  12991. ToastUtil.showToast('wma格式不支持拖动快进。')
  12992. return
  12993. }
  12994. this.isSeekTo = true
  12995. this.mIjkMediaPlayer.seekTo(value);
  12996. console.info('onecold startPlayOrResumePlay 11227')
  12997. // this.startPlayOrResumePlay()
  12998. // 在这里恢复计时器状态
  12999. this.setProgress()
  13000. this.isSeekTo = false
  13001. }
  13002. // 添加到下一首播放
  13003. private addToNextPlay(song: VideoItem) {
  13004. if (!this.debounce()) {
  13005. return;
  13006. }
  13007. if (this.currentSong) {
  13008. if (this.currentSong === song) {
  13009. ToastUtil.showToast('当前已经在播放这首歌了!')
  13010. return
  13011. }
  13012. }
  13013. // 如果未开始播放或队列为空
  13014. if (this.curIndex === -1 || this.songList.length === 0) {
  13015. this.songList = [song];
  13016. this.curIndex = 0;
  13017. this.doPlay(song)
  13018. return;
  13019. }
  13020. // 插入到当前索引+1的位置
  13021. const insertPos = this.curIndex + 1;
  13022. this.songList.splice(insertPos, 0, song);
  13023. this.songList = [...this.songList]; // 触发状态更新
  13024. this.sonDataSource.pushArrayData(this.songList)
  13025. ToastUtil.showToast('已添加至下一首播放')
  13026. }
  13027. //后退10s,可再设置设置默认几秒
  13028. backForward() {
  13029. if(this.mIjkMediaPlayer){
  13030. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  13031. let value = pos - Number(this.fastForwardSeconds) * 1000;
  13032. this.seekTo(value+"");
  13033. }
  13034. }
  13035. //快进10s,可再设置设置默认几秒
  13036. fastForward() {
  13037. if(this.mIjkMediaPlayer){
  13038. let pos = this.mIjkMediaPlayer.getCurrentPosition();
  13039. let value = pos + Number(this.fastForwardSeconds) * 1000;
  13040. this.seekTo(value+"");
  13041. }
  13042. }
  13043. //下一个
  13044. private async playNext() {
  13045. if (!this.debounce()) {
  13046. return;
  13047. }
  13048. if (this.playType == 3) { //3:随机播放
  13049. await this.randomPlay()
  13050. return;
  13051. }
  13052. if (ArrayUtil.isNotEmpty(this.songList)) {
  13053. if (this.curIndex == this.songList.length - 1) {
  13054. this.curIndex = 0;
  13055. } else {
  13056. this.curIndex++;
  13057. }
  13058. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13059. this.stop();
  13060. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  13061. this.currentSong = this.songList[this.curIndex];
  13062. Logger.info('heanup playNext', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  13063. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13064. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13065. context: this.context,
  13066. autoParseMusicName: this.autoParseMusicName
  13067. });
  13068. this.artist = this.songList[this.curIndex].artist
  13069. this.name = this.songList[this.curIndex].name
  13070. //this.cover = this.songList[this.curIndex].pixelMapPath
  13071. this.changeImageAnimation()
  13072. }
  13073. }
  13074. changeImageAnimation() {
  13075. if(this.openSkipSongAnimate){
  13076. // 第一步:淡出动画
  13077. this.getUIContext()?.animateTo({
  13078. duration: 500,
  13079. curve: Curve.EaseOut,
  13080. }, () => {
  13081. this.opacityValueImage = 0.1;
  13082. if(this.isCoverRectangle){
  13083. this.scaleValueImage = 0.88
  13084. }
  13085. });
  13086. // 第二步:切换图片后淡入
  13087. setTimeout(() => {
  13088. this.cover = this.songList[this.curIndex].pixelMapPath
  13089. this.getUIContext()?.animateTo({
  13090. duration: 500,
  13091. curve: Curve.EaseIn,
  13092. }, () => {
  13093. this.opacityValueImage = 1;
  13094. this.scaleValueImage = 1 // 图标恢复到原始大小
  13095. this.startPlayOrResumePlay()
  13096. });
  13097. }, 500);
  13098. }else{
  13099. this.cover = this.songList[this.curIndex].pixelMapPath
  13100. this.startPlayOrResumePlay()
  13101. }
  13102. }
  13103. // 存储已播放的歌曲索引
  13104. private playedIndices: Set<number> = new Set();
  13105. //随机播放
  13106. private async randomPlay() {
  13107. // if (!this.debounce()) {
  13108. // return;
  13109. // }
  13110. if (ArrayUtil.isNotEmpty(this.songList)) {
  13111. if (this.songList.length > 3) {
  13112. // 如果所有歌曲都播放过一次,清空已播放索引集合
  13113. if (this.playedIndices.size === this.songList.length) {
  13114. this.playedIndices.clear();
  13115. }
  13116. // 随机选择一个未播放的歌曲索引
  13117. let newIndex: number;
  13118. // 添加超时机制防止无限循环
  13119. let attempt = 0;
  13120. const maxAttempts = 100; // 根据需求调整
  13121. do {
  13122. newIndex = RandomUtil.getRandomNumber(0, this.songList.length - 1);
  13123. attempt++;
  13124. } while (this.playedIndices.has(newIndex) && attempt < maxAttempts);
  13125. if (attempt >= maxAttempts) {
  13126. // 处理无法找到新索引的情况(如随机选择或按顺序播放)
  13127. newIndex = Math.floor(Math.random() * this.songList.length);
  13128. }
  13129. this.curIndex = newIndex;
  13130. this.playedIndices.add(newIndex);
  13131. } else {
  13132. // 当歌曲数量小于或等于3时,直接播放下一首
  13133. if (this.curIndex == this.songList.length - 1) {
  13134. this.curIndex = 0;
  13135. } else {
  13136. this.curIndex++;
  13137. }
  13138. }
  13139. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13140. this.stop();
  13141. this.currentSong = this.songList[this.curIndex];
  13142. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13143. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13144. context: this.context,
  13145. autoParseMusicName: this.autoParseMusicName
  13146. });
  13147. this.name = this.songList[this.curIndex].name;
  13148. this.artist = this.songList[this.curIndex].artist
  13149. // this.cover = this.songList[this.curIndex].pixelMapPath
  13150. this.changeImageAnimation()
  13151. }
  13152. }
  13153. private async playIndex(index: number) {
  13154. if (!this.debounce()) {
  13155. return;
  13156. }
  13157. if (ArrayUtil.isNotEmpty(this.songList)) {
  13158. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13159. this.stop();
  13160. this.curIndex = index;
  13161. this.currentSong = this.songList[index];
  13162. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13163. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13164. context: this.context,
  13165. autoParseMusicName: this.autoParseMusicName
  13166. });
  13167. this.name = this.currentSong.name
  13168. this.artist = this.currentSong.artist
  13169. this.changeImageAnimation()
  13170. }
  13171. }
  13172. //上一个
  13173. private async playPrevious() {
  13174. if (!this.debounce()) {
  13175. return;
  13176. }
  13177. if (this.playType == 3) { //3:随机播放的上一首应该应该播放历史记录的第二首
  13178. this.randomModePlayFromHistory()
  13179. return;
  13180. }
  13181. if (this.curIndex == 0) {
  13182. this.curIndex = this.songList.length - 1;
  13183. } else {
  13184. this.curIndex--;
  13185. }
  13186. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13187. this.stop();
  13188. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  13189. this.currentSong = this.songList[this.curIndex];
  13190. Logger.info('heanup playPrevious', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  13191. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13192. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13193. context: this.context,
  13194. autoParseMusicName: this.autoParseMusicName
  13195. });
  13196. this.name = this.songList[this.curIndex].name
  13197. this.artist = this.songList[this.curIndex].artist
  13198. this.changeImageAnimation()
  13199. }
  13200. //随机播放模式下点击上一首: 上一首应该应该播放历史记录的第二首
  13201. private async randomModePlayFromHistory() {
  13202. if (this.historyList.length >= 2) {
  13203. // 播放历史记录的第二首
  13204. const prevSong = this.historyList[1];
  13205. this.curIndex = this.songList.findIndex(song => song.filePath === prevSong.filePath);
  13206. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13207. this.stop();
  13208. // 直接使用历史记录中的歌曲信息,历史记录中的数据应该是完整的
  13209. this.currentSong = prevSong;
  13210. Logger.info('heanup randomModePlayFromHistory', `直接使用历史歌曲信息: ${prevSong.name}, type: ${prevSong.type}`);
  13211. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13212. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13213. context: this.context,
  13214. autoParseMusicName: this.autoParseMusicName
  13215. });
  13216. this.cover = prevSong.pixelMapPath
  13217. this.artist = prevSong.artist
  13218. this.name = prevSong.name;
  13219. console.info('onecold startPlayOrResumePlay 11434')
  13220. this.startPlayOrResumePlay();
  13221. } else {
  13222. // 如果历史记录不足两首,可根据需求处理,这里简单按普通逻辑处理
  13223. if (this.curIndex === 0) {
  13224. this.curIndex = this.songList.length - 1;
  13225. } else {
  13226. this.curIndex--;
  13227. }
  13228. this.CONTROL_PlayStatus = PlayStatus.INIT;
  13229. this.stop();
  13230. // 直接使用歌曲列表中的歌曲信息,songList中的数据已经是完整的
  13231. this.currentSong = this.songList[this.curIndex];
  13232. Logger.info('heanup randomModePlayFromHistory', `直接使用歌曲列表中的信息: ${this.currentSong.name}, type: ${this.currentSong.type}`);
  13233. // 设置videoUrl,WebDAV歌曲会通过webdav_account_id构建完整URL
  13234. this.videoUrl = await setVideoUrlForSong(this.currentSong, {
  13235. context: this.context,
  13236. autoParseMusicName: this.autoParseMusicName
  13237. });
  13238. this.artist = this.songList[this.curIndex].artist
  13239. this.name = this.songList[this.curIndex].name;
  13240. this.changeImageAnimation()
  13241. }
  13242. }
  13243. debounce() {
  13244. const delay = 600;
  13245. let cur = new Date().getTime();
  13246. if (cur - this.last > delay) {
  13247. this.last = cur;
  13248. return true;
  13249. }
  13250. return false;
  13251. }
  13252. /**
  13253. * Sets whether the screen is a constant based on the playback status.
  13254. */
  13255. watchStatus() {
  13256. // let windowClass = GlobalContext.getContext().getObject('windowClass') as window.Window;
  13257. if (this.CONTROL_PlayStatus === PlayStatus.PLAY) {
  13258. this.windowClass.setWindowKeepScreenOn(true);
  13259. } else {
  13260. this.windowClass.setWindowKeepScreenOn(false);
  13261. }
  13262. }
  13263. /**
  13264. * Volume gesture method onActionStart.
  13265. *
  13266. * @param event Gesture event.
  13267. */
  13268. private customDialogComponentIdMM: number = 0
  13269. @Builder
  13270. customDialogComponentMM() {
  13271. Column() {
  13272. Row() {
  13273. Blank()
  13274. Text('验证密码')
  13275. .fontSize(22)
  13276. .fontColor($r('app.color.pri_bg'))
  13277. .margin({ top: 18 })
  13278. Blank()
  13279. Image($r('app.media.close'))
  13280. .fillColor(Color.White)
  13281. .margin({ top: 18, right: 18 })
  13282. .width(20)
  13283. .onClick(() => {
  13284. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  13285. })
  13286. }
  13287. .width('100%') // 使Row占据整个宽度
  13288. .justifyContent(FlexAlign.SpaceBetween); // 在Row中创建空间
  13289. Verify({
  13290. onVerifyCompleted: this.handleVerifyCompleted.bind(this)
  13291. });
  13292. }.height('60%')
  13293. .backgroundColor($r('app.color.index_background'))
  13294. .justifyContent(FlexAlign.SpaceBetween)
  13295. }
  13296. private handleVerifyCompleted(isSuccess: boolean) {
  13297. if (isSuccess) {
  13298. console.log('验证成功');
  13299. // 在这里处理验证成功后的逻辑
  13300. promptAction.closeCustomDialog(this.customDialogComponentIdMM)
  13301. this.currentPath = this.lockPath
  13302. this.getSortedFiles(this.currentPath)
  13303. } else {
  13304. // console.log('验证失败');
  13305. ToastUtil.showToast('验证失败')
  13306. }
  13307. }
  13308. private showVerifyDialog() {
  13309. promptAction.openCustomDialog({
  13310. transition: TransitionEffect.asymmetric(
  13311. TransitionEffect.OPACITY.animation({ duration: 888 }).combine(
  13312. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  13313. ,
  13314. TransitionEffect.OPACITY.animation({ delay: 888, duration: 888 }).combine(
  13315. TransitionEffect.translate({ y: 888 }).animation({ duration: 888 }))
  13316. ),
  13317. builder: () => {
  13318. this.customDialogComponentMM()
  13319. },
  13320. isModal: true,
  13321. autoCancel: true,
  13322. maskColor: Color.Transparent,
  13323. alignment: DialogAlignment.Bottom,
  13324. onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
  13325. console.info("reason" + JSON.stringify(dismissDialogAction.reason))
  13326. console.log("dialog onWillDismiss")
  13327. if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
  13328. dismissDialogAction.dismiss()
  13329. }
  13330. if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
  13331. dismissDialogAction.dismiss()
  13332. }
  13333. }
  13334. }).then((dialogId: number) => {
  13335. this.customDialogComponentIdMM = dialogId
  13336. })
  13337. }
  13338. //左滑操作 移动文件 重命名 删除等操作
  13339. @Builder
  13340. DeleteButton(item: VideoItem, index: number, filePath: string) {
  13341. Row() {
  13342. //加入收藏
  13343. Button() {
  13344. Image(Utility.getIsFav(this.favList, item) ? $r('app.media.add_fac_light2') : $r('app.media.add_fac'))
  13345. .fillColor(Color.White)
  13346. .width(20)
  13347. }
  13348. .width(40)
  13349. .height(40)
  13350. .type(ButtonType.Circle)
  13351. .backgroundColor(this.themeColor)
  13352. .margin(5)
  13353. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13354. .onClick(() => {
  13355. if (item) {
  13356. this.doFav(item)
  13357. }
  13358. })
  13359. //加入下一首播放
  13360. Button() {
  13361. Image($r('app.media.next_to_play'))
  13362. .fillColor(Color.White)
  13363. .width(20)
  13364. }
  13365. .width(40)
  13366. .height(40)
  13367. .type(ButtonType.Circle)
  13368. .backgroundColor(this.themeColor)
  13369. .margin(5)
  13370. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13371. .onClick(() => {
  13372. this.addToNextPlay(item);
  13373. })
  13374. //复制文件
  13375. Button() {
  13376. Image($r('app.media.copy'))
  13377. .fillColor(Color.White)
  13378. .width(20)
  13379. }
  13380. .width(40)
  13381. .height(40)
  13382. .type(ButtonType.Circle)
  13383. .backgroundColor(this.themeColor)
  13384. .margin(5)
  13385. .id(filePath + 'copy')
  13386. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13387. .onClick(() => {
  13388. this.showCopyDialog(false, item, index, filePath + 'copy');
  13389. })
  13390. //移动文件
  13391. Button() {
  13392. Image($r('app.media.cut'))
  13393. .fillColor(Color.White)
  13394. .width(20)
  13395. }
  13396. .width(40)
  13397. .height(40)
  13398. .type(ButtonType.Circle)
  13399. .backgroundColor(this.themeColor)
  13400. .margin(5)
  13401. .id(filePath)
  13402. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13403. .onClick(() => {
  13404. this.showCutDialog(false, item, index, filePath);
  13405. })
  13406. Button() {
  13407. Image($r('app.media.cut_current'))
  13408. .fillColor(Color.White)
  13409. .width(20)
  13410. }
  13411. .width(40)
  13412. .height(40)
  13413. .type(ButtonType.Circle)
  13414. .backgroundColor(this.themeColor)
  13415. .margin(5)
  13416. .id(filePath + 'current')
  13417. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None :
  13418. (this.isHasDir ? Visibility.Visible : Visibility.None))
  13419. .onClick(() => {
  13420. this.showCutDialog(true, item, index, filePath + 'current');
  13421. })
  13422. //重命名
  13423. Button() {
  13424. Image($r('app.media.rename2'))
  13425. .fillColor(Color.White)
  13426. .width(20)
  13427. }
  13428. .width(40)
  13429. .height(40)
  13430. .type(ButtonType.Circle)
  13431. .backgroundColor(this.themeColor)
  13432. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  13433. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  13434. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  13435. .margin(5)
  13436. .onClick(() => {
  13437. this.showReNameDialog(item, index + '', filePath)
  13438. })
  13439. Button() {
  13440. Image($r('app.media.delete2'))
  13441. .fillColor(Color.White)
  13442. .width(20)
  13443. }
  13444. .width(40)
  13445. .height(40)
  13446. .type(ButtonType.Circle)
  13447. .backgroundColor(this.themeColor)
  13448. .visibility(item.type === CommonConstants.TYPE_IS_DIR ?
  13449. (item.name === LocalMusic.STR_LOCK_VIDEO || item.name === LocalMusic.STR_FAC_VIDEO ||
  13450. item.name === LocalMusic.STR_HISTORY_MUSIC ? Visibility.None : Visibility.Visible) : Visibility.Visible)
  13451. .margin(5)
  13452. .onClick(() => {
  13453. this.selectedFiles.push(item)
  13454. this.showWarnIsDelete()
  13455. // this.showWarnIsDeleteFile(item, index + '', filePath)
  13456. })
  13457. Button() {
  13458. Image($r('app.media.share2'))
  13459. .fillColor(Color.White)
  13460. .width(20)
  13461. }
  13462. .width(40)
  13463. .height(40)
  13464. .type(ButtonType.Circle)
  13465. .backgroundColor(this.themeColor)
  13466. .margin(5)
  13467. .visibility(item.type === CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  13468. .onClick(() => {
  13469. Utility.doShareMusic(item, getContext(this) as common.UIAbilityContext)
  13470. })
  13471. }
  13472. }
  13473. /**
  13474. * 穿山甲banner广告
  13475. */
  13476. // private declare bannerAd: CSJNativeExpressAd;
  13477. // @State private status: string = "未加载"
  13478. // @State private isShowAd: boolean = false
  13479. // private declare mAdSlot: AdSlot;
  13480. // private mBiddingAdm = '' //服务端bidding才需要设置
  13481. // private expressLoadAdListener: NativeExpressAdListener = {
  13482. // /**
  13483. // * 加载失败的回调
  13484. // *
  13485. // * @param code
  13486. // * @param message
  13487. // */
  13488. // onError: (code: number, message: string) => {
  13489. // console.error("加载广告失败,code=" + code + ",message=" + message);
  13490. // this.status = "加载广告失败,code=" + code + ",message=" + message;
  13491. // },
  13492. //
  13493. // /**
  13494. // * 广告加载成功的回调,接入方可以在这个回调中进行渲染
  13495. // *
  13496. // * @param ads 返回的广告列表
  13497. // */
  13498. //
  13499. // onNativeExpressAdLoad: (ads: ArrayList<CSJNativeExpressAd>) => {
  13500. // console.log("BannerExpressAdPage==onNativeExpressAdLoad......success");
  13501. // if (ads && ads.length > 0) {
  13502. // ads.forEach((ad: CSJNativeExpressAd, idx: number) => {
  13503. // ad.setExpressInteractionListener({
  13504. // /**
  13505. // *广告的点击回调
  13506. // * @param type 广告的交互类型
  13507. // */
  13508. // onAdClicked: (type: number) => {
  13509. // console.log("BannerExpressAdPage==onAdClicked......");
  13510. // },
  13511. //
  13512. // /**
  13513. // * 广告的展示回调 每个广告仅回调一次
  13514. // * @param type 广告的交互类型
  13515. // */
  13516. // onAdShow: (type: number) => {
  13517. // console.log("BannerExpressAdPage==onAdShow......");
  13518. // },
  13519. //
  13520. // /**
  13521. // * 模板渲染失败
  13522. // */
  13523. // onRenderFail: (code: number, msg: string) => {
  13524. // console.log("BannerExpressAdPage==onRenderFail...code=" + code + ",msg=" + msg);
  13525. // },
  13526. //
  13527. // /**
  13528. // * 模板渲染成功
  13529. // * @param width 返回view的宽 单位 vp
  13530. // * @param height 返回view的高 单位 vp
  13531. // */
  13532. // onRenderSuccess: (width: number, height: number) => {
  13533. // console.log("BannerExpressAdPage==onRenderSuccess......width=" + width + ",height=" + height);
  13534. // this.bannerAd = ad;
  13535. // this.status = "广告加载完成待展示";
  13536. //
  13537. // this.showBannerAd()
  13538. // }
  13539. // })
  13540. // //渲染广告
  13541. // ad.setSlideIntervalTime(30 * 1000); //设置轮播时间长
  13542. // this.setDislikeCallback(ad); //设置dislike
  13543. // ad.render(this.getUIContext())
  13544. // this.status = "广告加载中...";
  13545. // });
  13546. // }
  13547. // }
  13548. // }
  13549. //
  13550. // private setDislikeCallback(ad: CSJNativeExpressAd) {
  13551. // ad.setDislikeCallback({
  13552. // /**
  13553. // * dislike show
  13554. // */
  13555. // onShow: () => {
  13556. // console.log("BannerExpressAdPage==dislike......show");
  13557. // },
  13558. //
  13559. // /**
  13560. // * @param position 选择的位置
  13561. // * @param value 选择的内容
  13562. // * @param enforceRemove 是否强制关闭广告
  13563. // */
  13564. // onSelected: (position: number, value: string, enforceRemove: boolean) => {
  13565. // this.isShowAd = false;
  13566. // console.log("BannerExpressAdPage==dislike......onSelected:position=" + position + ",value:" + value +
  13567. // ",enforce=" + enforceRemove);
  13568. // },
  13569. //
  13570. // /**
  13571. // * 点击取消
  13572. // */
  13573. // onCancel: () => {
  13574. // console.log("BannerExpressAdPage==dislike......onCancel");
  13575. // }
  13576. //
  13577. // })
  13578. // }
  13579. /**
  13580. * 加载Banner广告
  13581. */
  13582. loadBannerAd(rit: string) {
  13583. // if (Utility.isNoble()) {
  13584. // return
  13585. // }
  13586. // if (!Utility.isPassInstallTime(2)) {
  13587. // return
  13588. // }
  13589. // this.isShowAd = false;
  13590. // let adCreator: CSJAdCreator = CSJAdSdk.getAdCreator()
  13591. // this.mAdSlot = new AdSlotBuilder()
  13592. // .setCodeId(rit)
  13593. // .setAcceptSize(CSJUtil.BANNER_WIGTH, CSJUtil.BANNER_HEIGHT)
  13594. // .setAdCount(1)
  13595. // .setBidAdm(this.mBiddingAdm)
  13596. // .build()
  13597. // PrintBiddingTokenUtils.printBiddingToken(this.mAdSlot, adCreator);
  13598. // adCreator.loadBannerAd(this.mAdSlot, this.expressLoadAdListener)
  13599. // this.status = "广告加载中..."
  13600. }
  13601. /**
  13602. * 展示Banner广告
  13603. */
  13604. // showBannerAd() {
  13605. // if (!this.bannerAd) {
  13606. // return
  13607. // }
  13608. // this.isShowAd = true
  13609. // this.status = "已展示"
  13610. // }
  13611. /**
  13612. * 穿山甲广告代码结束
  13613. */
  13614. /**
  13615. * 处理歌单播放请求
  13616. */
  13617. private async handlePlaylistPlayRequest(playlistId: string, playlistName:
  13618. string, songFilePaths: string[], startIndex: number) {
  13619. try {
  13620. Logger.info(`heanup 处理歌单播放请求: ${playlistName}, 歌曲数量: ${songFilePaths.length}, 开始索引: ${startIndex}`)
  13621. // 检查是否为WebDAV播放请求
  13622. if (playlistId === 'webdav-playlist') {
  13623. Logger.info(`heanup 检测到WebDAV播放请求,从内存读取videoItems`)
  13624. // 从全局内存读取videoItems数据
  13625. const videoItems = getWebdavVideoItems();
  13626. const currentPlayIndex = getWebdavCurrentPlayIndex();
  13627. Logger.info(`heanup 从内存读取到WebDAV歌曲列表,长度:${videoItems.length},索引:${currentPlayIndex}`)
  13628. if (videoItems && videoItems.length > 0) {
  13629. // 验证webdav_account_id设置情况
  13630. const accountIds = videoItems.map(item => item.webdav_account_id).filter(id => id);
  13631. Logger.info(`heanup 有 ${accountIds.length}/${videoItems.length} 首歌曲设置了webdav_account_id`)
  13632. this.finishLoadingPlaylist(videoItems, currentPlayIndex, playlistName)
  13633. return
  13634. } else {
  13635. return
  13636. }
  13637. }
  13638. // 从数据库重新加载这些歌曲,使用索引记录位置以保持顺序
  13639. const songMap: Map<number, VideoItem> = new Map()
  13640. let completedQueries = 0
  13641. Logger.info(`heanup 开始从数据库查询 ${songFilePaths.length} 首歌曲`)
  13642. // 遍历所有文件路径,使用索引记录位置
  13643. for (let i = 0; i < songFilePaths.length; i++) {
  13644. const filePath = songFilePaths[i]
  13645. const index = i
  13646. // Logger.info(`heanup 正在查询歌曲[${index}]: ${filePath}`)
  13647. // 使用已初始化的MediaTable实例从数据库查询歌曲信息
  13648. const queryPromise = this.table.queryVideoByFilePath(filePath)
  13649. // Logger.info(`heanup 创建了查询Promise,开始等待结果[${index}]: ${filePath}`)
  13650. queryPromise.then((videoItem) => {
  13651. completedQueries++
  13652. // Logger.info(`heanup 查询Promise返回结果[${index}]: ${filePath}, 找到歌曲: ${videoItem ? videoItem.name : 'null'}`)
  13653. if (videoItem) {
  13654. // 使用索引作为key保存到Map中,保持原始顺序
  13655. songMap.set(index, videoItem)
  13656. // Logger.info(`heanup 从数据库找到歌曲[${index}]: ${videoItem.name} (${completedQueries}/${songFilePaths.length})`)
  13657. } else {
  13658. Logger.warn(`heanup 数据库中未找到歌曲[${index}]: ${filePath} (${completedQueries}/${songFilePaths.length})`)
  13659. }
  13660. // 检查是否所有歌曲都已加载完成
  13661. if (completedQueries === songFilePaths.length) {
  13662. // Logger.info(`heanup 所有数据库查询完成,共找到 ${songMap.size} 首歌曲`)
  13663. // 按照索引顺序重建歌曲数组
  13664. const songs: VideoItem[] = []
  13665. for (let j = 0; j < songFilePaths.length; j++) {
  13666. const song = songMap.get(j)
  13667. if (song) {
  13668. songs.push(song)
  13669. // Logger.info(`heanup 按顺序添加歌曲[${j}]: ${song.name}`)
  13670. }
  13671. }
  13672. Logger.info(`heanup 最终歌曲列表顺序: ${songs.map((s, idx) => `[${idx}]${s.name}`).join(', ')}`)
  13673. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  13674. }
  13675. }).catch((error: Error) => {
  13676. completedQueries++
  13677. Logger.error(`heanup 查询歌曲失败[${index}]: ${filePath}, 错误: ${error.message} (${completedQueries}/${songFilePaths.length})`)
  13678. // 即使出错也要检查是否完成所有查询
  13679. if (completedQueries === songFilePaths.length) {
  13680. Logger.info(`heanup 所有数据库查询完成(包含错误),共找到 ${songMap.size} 首歌曲`)
  13681. // 按照索引顺序重建歌曲数组
  13682. const songs: VideoItem[] = []
  13683. for (let j = 0; j < songFilePaths.length; j++) {
  13684. const song = songMap.get(j)
  13685. if (song) {
  13686. songs.push(song)
  13687. }
  13688. }
  13689. this.finishLoadingPlaylist(songs, startIndex, playlistName)
  13690. }
  13691. })
  13692. }
  13693. } catch (error) {
  13694. Logger.error('heanup 处理简化歌单播放请求失败: ' + error)
  13695. ToastUtil.showToast('播放失败')
  13696. }
  13697. }
  13698. /**
  13699. * 完成歌单加载并开始播放
  13700. */
  13701. private finishLoadingPlaylist(songs: VideoItem[], startIndex: number, playlistName: string) {
  13702. if (songs.length === 0) {
  13703. Logger.error('heanup 没有找到任何可播放的歌曲')
  13704. ToastUtil.showToast('没有找到可播放的歌曲')
  13705. return
  13706. }
  13707. this.songList = songs
  13708. this.sonDataSource.pushArrayData(songs)
  13709. this.sonDataSource.notifyDataReload()
  13710. this.curIndex = startIndex
  13711. if (songs[startIndex]) {
  13712. // 确保当前播放的歌曲也更新到存储
  13713. AppStorage.setOrCreate('currentSong', songs[startIndex])
  13714. // 设置isFromSonPlayList=true,避免doPlay方法重新从全局列表构建播放列表
  13715. this.doPlay(songs[startIndex], startIndex, true)
  13716. }
  13717. PreferencesUtil.putSync('LastMusicList', this.songList)
  13718. ToastUtil.showToast(`开始播放歌单: ${playlistName}`)
  13719. }
  13720. }
  13721. //视频气泡窗口的布局
  13722. @Builder
  13723. function customPopupBuilder(dataBu: BubbleBean) {
  13724. List() {
  13725. LazyForEach(new LazyDataSource(dataBu.data), (item: string, index: number) => {
  13726. ListItem() {
  13727. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13728. Row() {
  13729. Column() {
  13730. Image(dataBu.imageRes[index])
  13731. .height(28)
  13732. .fillColor(dataBu.color)
  13733. .alignSelf(ItemAlign.Center)
  13734. }
  13735. .width(32)
  13736. Text(item)
  13737. .padding({
  13738. top: 10,
  13739. bottom: 10,
  13740. right: 10,
  13741. left: 10
  13742. })
  13743. .fontColor(dataBu.modeType == index ? dataBu.color : $r('app.color.index_tab_font_color'))
  13744. .textAlign(TextAlign.Start)
  13745. .width("100%")
  13746. }
  13747. }
  13748. .backgroundColor($r('app.color.settings_background_main'))
  13749. .margin({ top: 6, bottom: 6 })
  13750. }
  13751. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  13752. .animation({ duration: 500, curve: Curve.Ease, delay: 100 * index }),
  13753. TransitionEffect.scale({ x: 0, y: 0 })))
  13754. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  13755. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  13756. .onClick(() => {
  13757. dataBu.onItemClick?.(index)
  13758. })
  13759. })
  13760. }
  13761. .scrollBar(BarState.Off)
  13762. .width(120)
  13763. .divider({
  13764. strokeWidth: 1,
  13765. color: "#22FFFFFF"
  13766. })
  13767. }
  13768. // Function to calculate a hash for the file list
  13769. function simpleHash(fileList: string[]): string {
  13770. let hash = 0;
  13771. const str = fileList.join(',');
  13772. for (let i = 0; i < str.length; i++) {
  13773. const char = str.charCodeAt(i);
  13774. hash = (hash << 5) - hash + char;
  13775. hash |= 0; // Convert to 32bit integer
  13776. }
  13777. return hash.toString();
  13778. }
  13779. interface MoreItem {
  13780. id: number;
  13781. image: Resource;
  13782. title: string;
  13783. }
  13784. //视频气泡窗口的布局
  13785. @Builder
  13786. function cutPopupBuilder(dataBu: BubbleBean) {
  13787. Column() {
  13788. Text(dataBu.isCopy ? '将文件复制到' : '将文件移动到')
  13789. .padding({
  13790. top: 10,
  13791. bottom: 10,
  13792. right: 10,
  13793. left: 10
  13794. })
  13795. .textAlign(TextAlign.Start)
  13796. .width(160)
  13797. .fontWeight(666)
  13798. .fontSize(16)
  13799. List() {
  13800. ForEach(dataBu.data, (item: string, index: number) => {
  13801. ListItem() {
  13802. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  13803. Row() {
  13804. Column() {
  13805. Image($r('app.media.music_group'))
  13806. .height(28)
  13807. .fillColor(dataBu.color)
  13808. .alignSelf(ItemAlign.Center)
  13809. }
  13810. .width(32)
  13811. Text(item.startsWith('.') ? item.replace(/\./g, '') : item)
  13812. .padding({
  13813. top: 10,
  13814. bottom: 10,
  13815. right: 10,
  13816. left: 10
  13817. })
  13818. .textAlign(TextAlign.Start).width("100%")// .fontColor(Color.Gray)
  13819. .fontSize(15)
  13820. }
  13821. }
  13822. .backgroundColor(Color.Transparent)
  13823. .margin({ top: 7, bottom: 7 })
  13824. }
  13825. .transition(TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.BOTTOM)
  13826. .animation({ duration: 500 }),
  13827. TransitionEffect.scale({ x: 0, y: 0 })))
  13828. // .transition(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 1.2, y: 1.2 }).animation({ duration: 500 }),
  13829. // TransitionEffect.scale({ x: 0, y: 0 }) ))
  13830. .onClick(() => {
  13831. dataBu.onItemClick?.(index)
  13832. })
  13833. })
  13834. }
  13835. .scrollBar(BarState.Off)
  13836. .width(150)
  13837. .divider({
  13838. strokeWidth: 1,
  13839. color: "#22FFFFFF"
  13840. })
  13841. }
  13842. .height(300)
  13843. .padding({
  13844. bottom: 30
  13845. })
  13846. }
  13847. function getFileDirName(filePath: string,rootPath:string): string{
  13848. if(filePath===rootPath){
  13849. return '首页'
  13850. }
  13851. let result = FileUtil.getFileName(filePath)
  13852. if(StrUtil.isEmpty(result))
  13853. return ''
  13854. if(result.startsWith('.'))
  13855. result = result.replace(/\./g, '')
  13856. return result
  13857. }
  13858. //只扫描当前目录下文件(不扫描子文件夹)的方法
  13859. @Concurrent
  13860. async function scanCurrentDirectoryTask(context: Context, dirPath: string, lockPath: string, cover_api: string) {
  13861. const table: MediaTable = new MediaTable(context);
  13862. try {
  13863. // 直接获取当前目录下的文件列表
  13864. const files = FileUtil.listFileSync(dirPath);
  13865. await Promise.all(files.map(async (file) => {
  13866. const fPath = `${dirPath}/${file}`;
  13867. // 跳过目录,只处理文件
  13868. if (FileUtil.isDirectory(fPath)) {
  13869. return;
  13870. }
  13871. // 跳过特定格式文件
  13872. if (fPath.endsWith('.lrc') || fPath.endsWith('.srt')) {
  13873. return;
  13874. }
  13875. // 检查是否为媒体文件
  13876. if (Utility.isMeidaByExtension(fPath)) {
  13877. let mType = CommonConstants.TYPE_LOCAL;
  13878. if (fPath.includes(lockPath)) {
  13879. mType = CommonConstants.TYPE_LOCK;
  13880. }
  13881. const mediaItem = await Utility.uriGetMusicAssetsFromFile(
  13882. context, fPath, mType, true
  13883. );
  13884. table.insert(mediaItem, (id: number) => {
  13885. // 插入回调函数
  13886. }, cover_api);
  13887. }
  13888. }));
  13889. } catch (error) {
  13890. console.error(' 扫描当前目录失败:', error);
  13891. }
  13892. }
  13893. //内嵌标签后更新库
  13894. @Concurrent
  13895. async function updateInfoDb(
  13896. context: Context,
  13897. filePath: string,
  13898. titleStr: string,
  13899. artistStr: string,
  13900. albumStr: string,
  13901. lyricConStr: string,
  13902. yearStr: string,
  13903. genreStr: string,
  13904. trackStr: string,
  13905. albumArtistStr: string,
  13906. composerStr: string,
  13907. lyricistStr: string,
  13908. commentStr: string,
  13909. discStr: string,
  13910. ): Promise<boolean> {
  13911. const table: MediaTable = new MediaTable(context);
  13912. await new Promise<void>((resolve, reject) => {
  13913. table.getRdbStore(context, (err:Error) => {
  13914. err ? reject(err) : resolve();
  13915. });
  13916. });
  13917. return await new Promise<boolean>((resolve) => {
  13918. table.updateMediaInfo(filePath, titleStr, artistStr, albumStr, lyricConStr,
  13919. yearStr, genreStr, trackStr, albumArtistStr, composerStr, lyricistStr, commentStr, discStr,
  13920. (success: boolean, error?: string) => {
  13921. if (success) {
  13922. console.log("onecold 编辑信息成功,数据库已同步");
  13923. } else {
  13924. console.error("onecold 编辑信息数据库失败原因: " + error);
  13925. }
  13926. resolve(success);
  13927. });
  13928. });
  13929. }